mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
368
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42fdbfe899 | ||
|
|
e40cd36151 | ||
|
|
ab54536886 | ||
|
|
72196c3447 | ||
|
|
48d2d52d28 | ||
|
|
6199a93f52 | ||
|
|
8397965df2 | ||
|
|
6c8a086190 | ||
|
|
3ef49faa26 | ||
|
|
55b30fbf1d | ||
|
|
7464bd7697 | ||
|
|
22694a380d | ||
|
|
6c7242aa64 | ||
|
|
92e4eecb58 | ||
|
|
24dfa920b5 | ||
|
|
c32852e311 | ||
|
|
1c758abd04 | ||
|
|
9796345987 | ||
|
|
c359eac6df | ||
|
|
d16ca4d8a8 | ||
|
|
0e44b3a032 | ||
|
|
dae92488ce | ||
|
|
4d0a65722a | ||
|
|
8e643b4747 | ||
|
|
a9622c9c29 | ||
|
|
0136fb6196 | ||
|
|
13e712c849 | ||
|
|
5cd0aaa99a | ||
|
|
e1b5309593 | ||
|
|
f12ae2f60d | ||
|
|
e37f20625b | ||
|
|
e5bea33cdc | ||
|
|
506cd5876e | ||
|
|
7c508e8940 | ||
|
|
7e6bac5d01 | ||
|
|
1fbe162b49 | ||
|
|
efd93dd9b4 | ||
|
|
20185ab7e9 | ||
|
|
3dc58e58cb | ||
|
|
b50d333f6c | ||
|
|
d0f0aa4502 | ||
|
|
ee0fb08268 | ||
|
|
cf06f89c11 | ||
|
|
e9f8f9d717 | ||
|
|
42146570fb | ||
|
|
2503d69293 | ||
|
|
5e38e79c96 | ||
|
|
5e5ffee93e | ||
|
|
a7662ae13a | ||
|
|
a249e896f7 | ||
|
|
ca3743520e | ||
|
|
98822fdd27 | ||
|
|
8d0225932c | ||
|
|
40bca96db5 | ||
|
|
a2a9586b54 | ||
|
|
2fe6ba36c4 | ||
|
|
e4c84e6e24 | ||
|
|
10ef8c4bd6 | ||
|
|
8e01cfb2ef | ||
|
|
b25c4ea26b | ||
|
|
cebad5692d | ||
|
|
6b2c8ace09 | ||
|
|
feff080d5b | ||
|
|
7ef64474e3 | ||
|
|
db034d6598 | ||
|
|
4d1b8421fb | ||
|
|
44866db692 | ||
|
|
0fd3a1a2b8 | ||
|
|
ced4ac5db8 | ||
|
|
e190f57b53 | ||
|
|
22f02fb6bf | ||
|
|
52c67df4c7 | ||
|
|
8d9b7084f8 | ||
|
|
1c8f78a082 | ||
|
|
cd24e503ba | ||
|
|
259fa57d5c | ||
|
|
88dfddd18a | ||
|
|
2204da404a | ||
|
|
f08eedb3f6 | ||
|
|
de1a734fb5 | ||
|
|
d0f7264ea8 | ||
|
|
06d728b218 | ||
|
|
194a6a58c2 | ||
|
|
36f65bed5a | ||
|
|
4209654d0a | ||
|
|
be9939d82c | ||
|
|
e67177a15b | ||
|
|
049ce1d6b0 | ||
|
|
5ce46e0a5d | ||
|
|
bf033f2f11 | ||
|
|
e4c375ad0d | ||
|
|
0cafa83ea7 | ||
|
|
435beb7f19 | ||
|
|
78fcb60fd5 | ||
|
|
4995b3553b | ||
|
|
3c2878cc52 | ||
|
|
715032062d | ||
|
|
dde08414fc | ||
|
|
3c3639100f | ||
|
|
ee1d861955 | ||
|
|
0c9b059edc | ||
|
|
efa03d62ac | ||
|
|
d238a94018 | ||
|
|
f9be8f0c44 | ||
|
|
8cf0373b5e | ||
|
|
844a1a2473 | ||
|
|
fda618618c | ||
|
|
23a964f8a7 | ||
|
|
9ffad375ae | ||
|
|
9e6fe314ae | ||
|
|
68dc1c4549 | ||
|
|
ec24b3a472 | ||
|
|
6455b1dade | ||
|
|
542ad3e060 | ||
|
|
910fb47692 | ||
|
|
3dd14dd625 | ||
|
|
d1b0ac4df1 | ||
|
|
0e225d0c6e | ||
|
|
d9cd0d2cc8 | ||
|
|
eadebc46d5 | ||
|
|
96d7c66535 | ||
|
|
90690d1c5c | ||
|
|
abbcb8e3ad | ||
|
|
fe60b3c279 | ||
|
|
c7455b74ff | ||
|
|
c875ceda4d | ||
|
|
666abd134f | ||
|
|
c115916962 | ||
|
|
0579e688ba | ||
|
|
bc50de3b55 | ||
|
|
6489232598 | ||
|
|
c23c436502 | ||
|
|
fad52ec125 | ||
|
|
d22e458d64 | ||
|
|
1b7cb4179d | ||
|
|
c1c22dfd37 | ||
|
|
0043cefab5 | ||
|
|
41f68ef1a1 | ||
|
|
9743ac3abc | ||
|
|
ca6cfcd193 | ||
|
|
d41424170a | ||
|
|
f4678935c4 | ||
|
|
416eb41d8d | ||
|
|
6e0d456dd7 | ||
|
|
8ac555664a | ||
|
|
4bf4e53ecf | ||
|
|
3d50e6b1ae | ||
|
|
846b20f78a | ||
|
|
a229d196bb | ||
|
|
61bfc04704 | ||
|
|
9b90386e73 | ||
|
|
ddc4c18faf | ||
|
|
fb8361b197 | ||
|
|
a5fd64f9f2 | ||
|
|
e0a7ce4f88 | ||
|
|
b213ae77b4 | ||
|
|
6e5932cb68 | ||
|
|
38e3fa2a33 | ||
|
|
8e1a676f19 | ||
|
|
7c946db440 | ||
|
|
eaf26c8a20 | ||
|
|
0a96767657 | ||
|
|
32054e156e | ||
|
|
fd6d6b7c46 | ||
|
|
c101a451e3 | ||
|
|
a76ba69217 | ||
|
|
d06caf9838 | ||
|
|
134fa167fe | ||
|
|
da42a5d7a7 | ||
|
|
b6c1d3c09c | ||
|
|
a58b0ac3e0 | ||
|
|
e1700ba982 | ||
|
|
736ac7db74 | ||
|
|
6e2966be43 | ||
|
|
679948e792 | ||
|
|
e0fc8362b8 | ||
|
|
9d8ff9615f | ||
|
|
1304809240 | ||
|
|
343a516e1a | ||
|
|
7c08cb58ae | ||
|
|
7e81668de2 | ||
|
|
d231564f8e | ||
|
|
37e89c5b4d | ||
|
|
e070bd72e0 | ||
|
|
9310d19857 | ||
|
|
4454a6d39a | ||
|
|
453f6f5180 | ||
|
|
6d0484941e | ||
|
|
cf47910881 | ||
|
|
4f0f0cf5b1 | ||
|
|
a78d5cb600 | ||
|
|
206c8a8846 | ||
|
|
bf17ce1151 | ||
|
|
ef38c975b9 | ||
|
|
61953c4f7b | ||
|
|
1f13285ab8 | ||
|
|
1bc23ac169 | ||
|
|
50f50b16e0 | ||
|
|
adc86fc7df | ||
|
|
f3fd3a2307 | ||
|
|
1e877fa602 | ||
|
|
906009a33a | ||
|
|
08559a02f8 | ||
|
|
1d93626453 | ||
|
|
9d0989374b | ||
|
|
3278afaa1a | ||
|
|
bf221ffbbd | ||
|
|
c636eea355 | ||
|
|
ffaa906cd1 | ||
|
|
d61af961c1 | ||
|
|
bc01b77752 | ||
|
|
a1b01a04a8 | ||
|
|
b44235c495 | ||
|
|
b80d5db176 | ||
|
|
d3c0d258b7 | ||
|
|
9dcdbf245a | ||
|
|
369e218afb | ||
|
|
119d24bf6b | ||
|
|
2a905510d5 | ||
|
|
da29919b5a | ||
|
|
05608ac4d4 | ||
|
|
135b84a501 | ||
|
|
e7cbba37d1 | ||
|
|
d9bb5e15b0 | ||
|
|
46cdc32cf1 | ||
|
|
387572e733 | ||
|
|
9f46c7a50b | ||
|
|
0607bb0b3a | ||
|
|
b89d87cbde | ||
|
|
06e06b9673 | ||
|
|
b896e7a3b9 | ||
|
|
c91daa9147 | ||
|
|
31ea194f3d | ||
|
|
472bb28c88 | ||
|
|
eaa4a7a047 | ||
|
|
4fa467c800 | ||
|
|
beb96e6f0c | ||
|
|
26cb9e2f03 | ||
|
|
6dc74523c3 | ||
|
|
3858a69867 | ||
|
|
49a5f4aa94 | ||
|
|
4cc9f2a3f3 | ||
|
|
b0d7fc01d8 | ||
|
|
9cc40246a3 | ||
|
|
423cf11919 | ||
|
|
33f7213599 | ||
|
|
6f1fb462ed | ||
|
|
336b8851f7 | ||
|
|
5da3cf673c | ||
|
|
9e54e094fb | ||
|
|
eb9ca4ab6b | ||
|
|
e7b6876877 | ||
|
|
c535f6ef6e | ||
|
|
db2e1d7da2 | ||
|
|
f5e204eb1d | ||
|
|
705a5e7b2a | ||
|
|
e60eae3646 | ||
|
|
b04900b1b2 | ||
|
|
6357543b44 | ||
|
|
67fb338e5d | ||
|
|
ba140c4ab5 | ||
|
|
f5fdbc7941 | ||
|
|
90ae85da4d | ||
|
|
f3600fa618 | ||
|
|
2d8befe1cb | ||
|
|
f982ffcaf7 | ||
|
|
255c64551e | ||
|
|
746f28c1b2 | ||
|
|
2b481ba250 | ||
|
|
49622623de | ||
|
|
69f99ade42 | ||
|
|
c236e9711f | ||
|
|
4c2efb6688 | ||
|
|
7eb2d1cf1a | ||
|
|
b4ff83cf9f | ||
|
|
7b20b70c6b | ||
|
|
86207f9d0e | ||
|
|
eda5ece382 | ||
|
|
3404bbc128 | ||
|
|
b5a431aa3c | ||
|
|
49249f6541 | ||
|
|
5614621d6e | ||
|
|
0816562065 | ||
|
|
39618e6862 | ||
|
|
c66e4ba4b3 | ||
|
|
e4b033861f | ||
|
|
85a07a556c | ||
|
|
8dfc48d58b | ||
|
|
82ebdaa0b5 | ||
|
|
ec016f85bc | ||
|
|
c2c812deaa | ||
|
|
eec3428f78 | ||
|
|
4a5e4b76e3 | ||
|
|
43f952b2fb | ||
|
|
0d86bec34d | ||
|
|
47a6f29ad7 | ||
|
|
84834f180e | ||
|
|
bfd445618a | ||
|
|
eddfd37b93 | ||
|
|
d7341863bf | ||
|
|
2f51be7b5a | ||
|
|
fbc0014d14 | ||
|
|
46df6171fc | ||
|
|
761b62914f | ||
|
|
91b0299f77 | ||
|
|
6d08e59d10 | ||
|
|
83cc0fe585 | ||
|
|
c711c627b8 | ||
|
|
0b34690721 | ||
|
|
b640734db5 | ||
|
|
f8feb63dde | ||
|
|
25a5d3fe5d | ||
|
|
41dd93fd25 | ||
|
|
adf3c9405d | ||
|
|
abf4f57b47 | ||
|
|
c1e36975d4 | ||
|
|
0bfa0915d4 | ||
|
|
4da87672a2 | ||
|
|
3ba0d287e9 | ||
|
|
b4a86cb5bb | ||
|
|
0fa1f2f868 | ||
|
|
71610ddfdb | ||
|
|
5c9e683769 | ||
|
|
32a5e83b88 | ||
|
|
88904c08f7 | ||
|
|
9928bfe780 | ||
|
|
a491dec5c4 | ||
|
|
17ef33ee31 | ||
|
|
06caaee343 | ||
|
|
1c161a76dd | ||
|
|
aa05ab03fa | ||
|
|
43ea3f3181 | ||
|
|
3966b27948 | ||
|
|
7e24327621 | ||
|
|
d025aa3c6d | ||
|
|
325f6893c5 | ||
|
|
466419407d | ||
|
|
cbd4ce6636 | ||
|
|
d4130181e7 | ||
|
|
16a9d0af2a | ||
|
|
e51698e01f | ||
|
|
519091dd86 | ||
|
|
972088f1b3 | ||
|
|
542d31daf0 | ||
|
|
8f9a849c48 | ||
|
|
e8bfe6e520 | ||
|
|
15618f357b | ||
|
|
b74010435a | ||
|
|
0a58a7faee | ||
|
|
0d21e2f913 | ||
|
|
ebb82d2dc9 | ||
|
|
557e346810 | ||
|
|
08b2cf0894 | ||
|
|
4e90e03536 | ||
|
|
11d997dc65 | ||
|
|
454193da9b | ||
|
|
cdd5c99bc7 | ||
|
|
fb1da1c39a | ||
|
|
b29ece82c8 | ||
|
|
0e1f6f15a1 | ||
|
|
48054a86ab | ||
|
|
38d658abf5 | ||
|
|
5547391cfc | ||
|
|
05933a5ee3 | ||
|
|
c96f2d1070 | ||
|
|
f58bf9b23c | ||
|
|
d59734e375 | ||
|
|
8cfd54a739 |
No files matched your search
@@ -0,0 +1,3 @@
|
||||
# Vendored files preserve upstream license spacing and unified-diff context lines.
|
||||
tools/comet/LICENSE whitespace=-blank-at-eof
|
||||
tools/comet/droiddeck.patch whitespace=-blank-at-eol,-blank-at-eof
|
||||
@@ -0,0 +1,101 @@
|
||||
name: Build desktop package (KDE Plasma)
|
||||
|
||||
# The desktop the app installs into its Linux runtime on first use: KDE Plasma as SteamOS's desktop
|
||||
# mode has it, the closure of tools/desktop-kde/seeds.txt over Arch Linux ARM minus what the runtime
|
||||
# already carries, plus tools/desktop-kde/overlay (tools/desktop-kde/build.sh), every package
|
||||
# signature-checked. Published as a release in Droid-Deck/DroidDeck-Components with DroidDeck's
|
||||
# other components; the apk pins it in tools/desktop-kde/release.env (tag, sha256, size). A
|
||||
# published tag is never rebuilt: the packages are Arch Linux ARM's current ones, so a rebuild
|
||||
# would not match the pinned sha256. A changed package gets a new tag (desktop-kde-r2, ...) and a
|
||||
# release.env update.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/desktop-kde/**'
|
||||
- '.github/workflows/build-desktop-kde.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish as (e.g. desktop-kde-r1); empty = artifact only'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
kwin:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build KWin with nested desktop scaling
|
||||
run: |
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq zstd xz-utils gpgv patch binutils >/dev/null
|
||||
bash tools/desktop-kde/build-kwin.sh out/kwin
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-kde-kwin
|
||||
retention-days: 7
|
||||
path: out/kwin/
|
||||
build:
|
||||
needs: kwin
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: desktop-kde-kwin
|
||||
path: out/kwin
|
||||
- uses: actions/create-github-app-token@v2
|
||||
id: components-token
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
with:
|
||||
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
|
||||
private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }}
|
||||
owner: Droid-Deck
|
||||
repositories: DroidDeck-Components
|
||||
- name: Refuse a published tag
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.components-token.outputs.token }}
|
||||
run: |
|
||||
if gh release view '${{ inputs.tag }}' -R Droid-Deck/DroidDeck-Components >/dev/null 2>&1; then
|
||||
echo "::error::${{ inputs.tag }} is already published, and published tags are never replaced: use a new tag"
|
||||
exit 1
|
||||
fi
|
||||
- name: Build
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq zstd xz-utils gpgv >/dev/null
|
||||
KDE_KWIN_OVERRIDE="$PWD/out/kwin" tools/desktop-kde/build.sh out
|
||||
cp out/kwin/desktop-kde.kwin.txt out/
|
||||
echo "size $(stat -c %s out/desktop-kde.tar.zst) sha256 $(cat out/desktop-kde.sha256)"
|
||||
# The package itself too, briefly: enough to try a build on a device before publishing it.
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-kde
|
||||
retention-days: 7
|
||||
compression-level: 0
|
||||
path: |
|
||||
out/desktop-kde.tar.zst
|
||||
out/desktop-kde.packages.txt
|
||||
out/desktop-kde.kwin.txt
|
||||
out/desktop-kde.sha256
|
||||
- name: Publish
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.components-token.outputs.token }}
|
||||
GH_REPO: Droid-Deck/DroidDeck-Components
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG='${{ inputs.tag }}'
|
||||
if gh release view "$TAG" >/dev/null 2>&1; then
|
||||
echo "::error::$TAG is already published in DroidDeck-Components, and published tags are never replaced: use a new tag"
|
||||
exit 1
|
||||
fi
|
||||
gh release create "$TAG" --latest=false --prerelease=false --title "$TAG" \
|
||||
--notes "KDE Plasma desktop package for DroidDeck's Linux runtime ($GITHUB_REPOSITORY tools/desktop-kde, $GITHUB_SHA). size $(stat -c %s out/desktop-kde.tar.zst), sha256 $(cat out/desktop-kde.sha256). desktop-kde.packages.txt lists the signature-checked Arch Linux ARM packages it was built from." \
|
||||
out/desktop-kde.tar.zst out/desktop-kde.sha256 out/desktop-kde.packages.txt out/desktop-kde.kwin.txt
|
||||
gh release edit "$TAG" --latest=false --prerelease=false
|
||||
@@ -42,4 +42,7 @@ jobs:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh release create "${{ inputs.tag }}" --title "${{ inputs.tag }}" --notes "gamescope 3.16.29 with tools/gamescope/patches; staged by the apk over /usr/local/bin/gamescope. sha256 $(cut -d' ' -f1 gamescope.tzst.sha256)" gamescope.tzst gamescope.tzst.sha256 || gh release upload "${{ inputs.tag }}" gamescope.tzst gamescope.tzst.sha256 --clobber
|
||||
gh release create "${{ inputs.tag }}" --latest=false --prerelease=false --title "${{ inputs.tag }}" --notes "gamescope 3.16.29 with tools/gamescope/patches; staged by the apk over /usr/local/bin/gamescope. sha256 $(cut -d' ' -f1 gamescope.tzst.sha256)" gamescope.tzst gamescope.tzst.sha256 || gh release upload "${{ inputs.tag }}" gamescope.tzst gamescope.tzst.sha256 --clobber
|
||||
# A component the apk fetches by tag, never something users install: it must not
|
||||
# become the repo's Latest release or appear as a pre-release, also when re-uploaded.
|
||||
gh release edit "${{ inputs.tag }}" --latest=false --prerelease=false
|
||||
@@ -0,0 +1,31 @@
|
||||
name: Build Venus (Mali)
|
||||
# The Mali (Venus) route's binaries from tools/venus (David Cimo's recipes): Mesa's Venus ICD and the
|
||||
# Mali compatibility layer (glibc, for the session) and virglrenderer's vtest server (bionic, run by
|
||||
# the app over the phone's own Vulkan driver), packed as venus.tzst rooted at app/src/main. The apk
|
||||
# build fetches it by tools/venus/release.env (tag + sha256); nothing compiled is kept in this repo.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [test/non-adreno-all]
|
||||
paths: ['tools/venus/**', '.github/workflows/build-venus.yml']
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 120
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Tools
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq ninja-build pkg-config zstd python3-pip
|
||||
pip3 install --break-system-packages 'meson>=1.5'
|
||||
- name: Build
|
||||
run: ANDROID_NDK_HOME="$ANDROID_NDK_LATEST_HOME" WORK=$PWD/venus-work tools/venus/ci-build.sh
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: venus
|
||||
path: |
|
||||
venus-work/venus.tzst
|
||||
venus-work/venus.tzst.sha256
|
||||
@@ -1,46 +0,0 @@
|
||||
name: Build wlroots (patched)
|
||||
|
||||
# The desktop's wlroots (Arch Linux ARM's wlroots0.20, what the desktop package's labwc links)
|
||||
# rebuilt with tools/wlroots/patches: a Vulkan DMA-BUF allocator for the Adreno node, which is not
|
||||
# a DRM device, so labwc's vulkan and gles2 renderers can start. Built in an Arch Linux ARM
|
||||
# container on an arm64 runner and published as a release asset the apk build fetches
|
||||
# (tools/wlroots/release.env names the tag and sha). The hosted desktop package is never changed.
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- 'tools/wlroots/**'
|
||||
- '.github/workflows/build-wlroots.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish as (e.g. wlroots-0.20.2-p1); empty = artifact only'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Build in Arch Linux ARM
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run --rm -v "$PWD:/work" -w /work menci/archlinuxarm:base-devel bash tools/wlroots/build-in-arch.sh
|
||||
sudo chown -R "$(id -u):$(id -g)" .
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: wlroots-patched
|
||||
path: |
|
||||
wlroots.tzst
|
||||
wlroots.tzst.sha256
|
||||
- name: Publish
|
||||
if: github.event_name == 'workflow_dispatch' && inputs.tag != ''
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gh release create "${{ inputs.tag }}" --title "${{ inputs.tag }}" --notes "wlroots 0.20.2 with tools/wlroots/patches (Vulkan DMA-BUF allocator for non-DRM GPU nodes); staged by the apk at /usr/local/lib/droiddeck-wlroots for the desktop's GPU renderers. sha256 $(cut -d' ' -f1 wlroots.tzst.sha256)" wlroots.tzst wlroots.tzst.sha256 || gh release upload "${{ inputs.tag }}" wlroots.tzst wlroots.tzst.sha256 --clobber
|
||||
+272
-65
@@ -28,7 +28,7 @@ concurrency:
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
PRELOAD_CACHE_VERSION: v2
|
||||
PRELOAD_CACHE_VERSION: v3
|
||||
|
||||
jobs:
|
||||
build:
|
||||
@@ -44,6 +44,19 @@ jobs:
|
||||
ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Check co-authors
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --no-tags origin main
|
||||
base=$(git merge-base origin/main HEAD)
|
||||
messages=$(git log --format=%B "$base..HEAD")
|
||||
messages+=$'\n'"$(jq -r '.pull_request.title, (.pull_request.body // "")' "$GITHUB_EVENT_PATH")"
|
||||
if grep -Eiq '^[[:space:]]*Co-authored-by:.*(Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\])' <<<"$messages"; then
|
||||
echo "::error::AI and bot identities cannot be co-authors; remove the Co-authored-by trailer."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: The packages a signed build ships as
|
||||
id: variants
|
||||
run: echo "list=$(awk '!/^#/ && NF { print $1 }' tools/release/variants.txt | jq -R . | jq -sc .)" >> "$GITHUB_OUTPUT"
|
||||
@@ -57,6 +70,22 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Version bumps are isolated
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --no-tags origin main
|
||||
base=$(git merge-base origin/main HEAD)
|
||||
diff=$(git diff -U0 "$base..HEAD" -- app/build.gradle)
|
||||
grep -Eq '^[+-][[:space:]]*version(Code|Name)[[:space:]]' <<<"$diff" || exit 0
|
||||
other_files=$(git diff --name-only "$base..HEAD" | grep -v '^app/build.gradle$' || true)
|
||||
other_gradle=$(grep -E '^[+-]' <<<"$diff" | grep -Ev '^(---|\+\+\+)' | grep -Ev '^[+-][[:space:]]*version(Code|Name)[[:space:]]' || true)
|
||||
if [[ -n "$other_files" || -n "$other_gradle" ]]; then
|
||||
echo "::error::versionCode/versionName changes must be isolated in their own PR"
|
||||
echo "A version PR may only change the versionCode/versionName lines in app/build.gradle." >> "$GITHUB_STEP_SUMMARY"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Merge onto main, or say what conflicts
|
||||
if: github.event_name == 'pull_request'
|
||||
run: |
|
||||
@@ -157,7 +186,7 @@ jobs:
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/mangoapp/*') }}
|
||||
key: preloads-${{ env.PRELOAD_CACHE_VERSION }}-${{ hashFiles('app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/cpp/adrenotools/src/hook/kgsl.h', 'tools/quest/*', 'tools/linuxfs/preload/*.c', 'tools/linuxfs/build-x86-preloads.sh', 'tools/linuxfs/fex/*', 'tools/linuxfs/clipboard/*.c', 'tools/linuxfs/ssbs/*.c', 'tools/linuxfs/xclipse-layer/*', 'tools/proot/fastpath/*.c', 'tools/linuxfs/overlay/usr/local/bin/*', 'tools/linuxfs/overlay/usr/bin/**', 'tools/linuxfs/desktop/*', 'tools/gamescope/release.env', 'tools/wlroots/release.env', 'tools/linuxfs/uruntime.env', 'tools/linuxfs/licenses/*', 'tools/mangoapp/*', 'tools/msitools/**', 'tools/comet/**', 'tools/vkbridge/client/**', 'tools/vkbridge/common/**', 'tools/vkbridge/tests/**', 'tools/vkbridge/build-client-linux.sh', 'tools/linuxfs/debian-image.env') }}
|
||||
|
||||
- name: Build libfakeinput.so and libblsession.so (glibc aarch64)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
@@ -166,7 +195,7 @@ jobs:
|
||||
run: |
|
||||
set -euo pipefail
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu >/dev/null
|
||||
sudo apt-get install -y -qq gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libvulkan-dev >/dev/null
|
||||
D=app/src/main/assets/linuxfs
|
||||
mkdir -p "$D"
|
||||
aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \
|
||||
@@ -176,7 +205,28 @@ jobs:
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so"
|
||||
for script in tools/linuxfs/overlay/usr/local/bin/bannerlator-*; do
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \
|
||||
-fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$D/libblaudit.so" tools/proot/fastpath/audit.c
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libblaudit.so"
|
||||
# Force-SSBS adapter, preloaded into a game's Wine only when the game asks for it.
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \
|
||||
-o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/libssbs.so"
|
||||
# Samsung Xclipse driver workarounds, a Vulkan layer the system-driver path enables there.
|
||||
mkdir -p "$D/usr/local/lib/droiddeck-xclipse"
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \
|
||||
-o "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so" tools/linuxfs/xclipse-layer/xclipse_layer.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/lib/droiddeck-xclipse/libVkLayer_droiddeck_xclipse.so"
|
||||
install -m644 tools/linuxfs/xclipse-layer/VkLayer_droiddeck_xclipse.json "$D/usr/local/lib/droiddeck-xclipse/"
|
||||
mkdir -p "$D/usr/local/bin"
|
||||
# The Mali bridge's Linux side: ICD, manifest and self-test (tools/vkbridge).
|
||||
tools/vkbridge/build-client-linux.sh "$D" aarch64-linux-gnu-gcc
|
||||
aarch64-linux-gnu-gcc -O2 -Wall -Wextra -o "$D/usr/local/bin/droiddeck-clipboard" tools/linuxfs/clipboard/clipboard.c -ldl
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$D/usr/local/bin/droiddeck-clipboard"
|
||||
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
|
||||
for f in tools/linuxfs/overlay/usr/bin/* tools/linuxfs/overlay/usr/bin/steamos-polkit-helpers/*; do
|
||||
@@ -184,20 +234,18 @@ jobs:
|
||||
done
|
||||
if [ -f tools/gamescope/release.env ]; then
|
||||
. tools/gamescope/release.env
|
||||
gh release download "${GAMESCOPE_TAG}" -R "${GITHUB_REPOSITORY}" -p gamescope.tzst -O gamescope.tzst
|
||||
gh release download "${GAMESCOPE_TAG}" -R "${GAMESCOPE_REPO:-${GITHUB_REPOSITORY}}" -p gamescope.tzst -O gamescope.tzst
|
||||
echo "${GAMESCOPE_SHA256} gamescope.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf gamescope.tzst -C "$D"
|
||||
test -f "$D/usr/local/bin/gamescope"
|
||||
rm gamescope.tzst
|
||||
fi
|
||||
if [ -f tools/wlroots/release.env ]; then
|
||||
. tools/wlroots/release.env
|
||||
gh release download "${WLROOTS_TAG}" -R "${GITHUB_REPOSITORY}" -p wlroots.tzst -O wlroots.tzst
|
||||
echo "${WLROOTS_SHA256} wlroots.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf wlroots.tzst -C "$D"
|
||||
test -f "$D/usr/local/lib/droiddeck-wlroots/libwlroots-0.20.so"
|
||||
rm wlroots.tzst
|
||||
fi
|
||||
. tools/linuxfs/uruntime.env
|
||||
curl -fsSL --retry 3 -o uruntime "https://github.com/VHSgunzo/uruntime/releases/download/${URUNTIME_VERSION}/${URUNTIME_ASSET}"
|
||||
echo "${URUNTIME_SHA256} uruntime" | sha256sum -c -
|
||||
install -Dm644 uruntime "$D/usr/local/lib/droiddeck/uruntime"
|
||||
install -Dm644 tools/linuxfs/licenses/uruntime-LICENSE "$D/usr/local/share/licenses/uruntime/LICENSE"
|
||||
rm uruntime
|
||||
M="$D/usr/local/lib/mangoapp"
|
||||
mkdir -p "$M" mango-pkgs
|
||||
grep -v '^#' tools/mangoapp/packages.txt | while read -r sum url; do
|
||||
@@ -208,21 +256,113 @@ jobs:
|
||||
rm mango-pkgs/pkg.tar.zst
|
||||
done
|
||||
install -m644 mango-pkgs/usr/bin/mangoapp "$M/mangoapp"
|
||||
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1 libtracefs.so.1; do
|
||||
for so in libfmt.so.10 libspdlog.so.1.13 libglfw.so.3 libtraceevent.so.1; do
|
||||
cp -L "mango-pkgs/usr/lib/$so" "$M/$so"
|
||||
done
|
||||
# Ours, not the package's: GPU memory without tracefs (tools/mangoapp/libtracefs-shim.c).
|
||||
aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wl,-soname,libtracefs.so.1 \
|
||||
-o "$M/libtracefs.so.1" tools/mangoapp/libtracefs-shim.c
|
||||
aarch64-linux-gnu-strip --strip-unneeded "$M/libtracefs.so.1"
|
||||
install -Dm644 tools/mangoapp/mangoapp "$D/usr/local/bin/mangoapp"
|
||||
rm -rf mango-pkgs
|
||||
ls -l "$M"
|
||||
# The Windows components installer's tools (tools/msitools/packages.txt).
|
||||
T="$D/usr/local/lib/droiddeck-msitools"
|
||||
mkdir -p "$T" msi-pkgs
|
||||
grep -v '^#' tools/msitools/packages.txt | while read -r sum url; do
|
||||
[ -n "$url" ] || continue
|
||||
curl -fsSL --retry 3 -o msi-pkgs/pkg.tar.xz "$url"
|
||||
echo "$sum msi-pkgs/pkg.tar.xz" | sha256sum -c -
|
||||
tar -xJf msi-pkgs/pkg.tar.xz -C msi-pkgs
|
||||
rm msi-pkgs/pkg.tar.xz
|
||||
done
|
||||
install -m644 msi-pkgs/usr/bin/msiinfo "$T/msiinfo"
|
||||
install -m644 msi-pkgs/usr/bin/cabextract "$T/cabextract"
|
||||
# 7-Zip (the full build with its format plugin) opens installer .exe wrappers.
|
||||
install -m644 msi-pkgs/usr/lib/7zip/7z "$T/7z"
|
||||
install -m644 msi-pkgs/usr/lib/7zip/7z.so "$T/7z.so"
|
||||
for so in libmsi-1.0.so.0 libgsf-1.so.114 libgcab-1.0.so.0; do
|
||||
cp -L "msi-pkgs/usr/lib/$so" "$T/$so"
|
||||
done
|
||||
for f in NOTICE GPL-2 GPL-3 LGPL-2.1 7zip-License 7zip-unRarLicense; do
|
||||
install -Dm644 "tools/msitools/licenses/$f" "$D/usr/local/share/licenses/droiddeck-msitools/$f"
|
||||
done
|
||||
rm -rf msi-pkgs
|
||||
ls -l "$T"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop "$D/usr/local/bin/droiddeck-desktop"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-gpu "$D/usr/local/bin/droiddeck-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/droiddeck-desktop-gpu "$D/usr/local/bin/droiddeck-desktop-gpu"
|
||||
install -Dm644 tools/linuxfs/desktop/autostart "$D/etc/xdg/labwc/autostart"
|
||||
install -Dm644 tools/linuxfs/desktop/rc.xml "$D/etc/xdg/labwc/rc.xml"
|
||||
install -Dm644 tools/linuxfs/desktop/panel.conf "$D/etc/xdg/lxqt/panel.conf"
|
||||
install -Dm644 tools/linuxfs/desktop/kwin_wayland_wrapper "$D/usr/local/bin/kwin_wayland_wrapper"
|
||||
install -Dm644 tools/linuxfs/desktop/firefox-droiddeck.js "$D/usr/lib/firefox/defaults/pref/droiddeck.js"
|
||||
ls -lR "$D"
|
||||
|
||||
# The Debian 11 image the preloads are compiled in comes from a release on this repo
|
||||
# (published once by ci-debian-image.yml, pinned in tools/linuxfs/debian-image.env): the
|
||||
# public registry mirrors rate-limit the shared runner addresses and failed builds on a
|
||||
# busy evening. Only if that download fails is the image pulled, with retries.
|
||||
- name: Fetch the Debian image the preloads build in
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
. tools/linuxfs/debian-image.env
|
||||
image=public.ecr.aws/docker/library/debian:bullseye
|
||||
if gh release download "$DEBIAN_IMAGE_TAG" -R "$GITHUB_REPOSITORY" -p "$DEBIAN_IMAGE_ASSET" -O /tmp/debian-image.tar.zst \
|
||||
&& { [ -z "$DEBIAN_IMAGE_SHA256" ] || echo "$DEBIAN_IMAGE_SHA256 /tmp/debian-image.tar.zst" | sha256sum -c -; }; then
|
||||
zstd -dc /tmp/debian-image.tar.zst | docker load
|
||||
rm -f /tmp/debian-image.tar.zst
|
||||
else
|
||||
echo "::warning::the hosted Debian image could not be fetched; pulling from the registry instead"
|
||||
for attempt in 1 2 3 4 5; do
|
||||
docker pull "$image" && break
|
||||
[ "$attempt" -lt 5 ] || { echo "::error::could not pull $image after $attempt attempts"; exit 1; }
|
||||
echo "pull attempt $attempt failed (registry busy?); retrying in $((attempt * 30)) s"
|
||||
sleep $((attempt * 30))
|
||||
done
|
||||
fi
|
||||
docker image ls "$image"
|
||||
|
||||
- name: Build the x86 preloads FEX guests load (glibc 2.31)
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker run --rm -v "$PWD:/src" -w /src public.ecr.aws/docker/library/debian:bullseye bash -c '
|
||||
set -euo pipefail
|
||||
printf "deb http://archive.debian.org/debian bullseye main\ndeb http://archive.debian.org/debian-security bullseye-security main\n" > /etc/apt/sources.list
|
||||
apt-get -o Acquire::Check-Valid-Until=false update -qq
|
||||
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends gcc g++ gcc-multilib g++-multilib binutils >/dev/null
|
||||
tools/linuxfs/build-x86-preloads.sh app/src/main/assets/linuxfs
|
||||
'
|
||||
sudo chown -R "$(id -u):$(id -g)" app/src/main/assets/linuxfs
|
||||
ls -l app/src/main/assets/linuxfs/x86_64 app/src/main/assets/linuxfs/i386
|
||||
|
||||
- name: Bundle the droiddeck-esync packs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -f tools/droiddeck-esync/release.env ]; then
|
||||
. tools/droiddeck-esync/release.env
|
||||
gh release download "$SYNC_BUNDLE_TAG" -R "$SYNC_BUNDLE_REPO" -p "$SYNC_BUNDLE_ASSET" -O sync-bundle.tzst
|
||||
echo "$SYNC_BUNDLE_SHA256 sync-bundle.tzst" | sha256sum -c -
|
||||
mkdir -p app/src/main/assets/droiddeck-esync
|
||||
tar --use-compress-program=unzstd -xf sync-bundle.tzst -C app/src/main/assets/droiddeck-esync
|
||||
rm sync-bundle.tzst
|
||||
gh release download "$SYNC_BUNDLE_TAG" -R "$SYNC_BUNDLE_REPO" -p index.json -O sync-index.json
|
||||
revoked=$(python3 -c 'import json, sys; print(" ".join(p["id"] for p in json.load(open(sys.argv[1]))["packs"] if p.get("revoked") is True))' sync-index.json)
|
||||
for id in $revoked; do
|
||||
if [ -e "app/src/main/assets/droiddeck-esync/packs/$id.tzst" ]; then
|
||||
echo "::warning::$SYNC_BUNDLE_ASSET carries revoked pack $id; it is left out of the APK (point tools/droiddeck-esync/release.env at a newer bundle)"
|
||||
rm -f "app/src/main/assets/droiddeck-esync/packs/$id.tzst"
|
||||
fi
|
||||
done
|
||||
rm sync-index.json
|
||||
test -f app/src/main/assets/droiddeck-esync/index.json
|
||||
test -f app/src/main/assets/droiddeck-esync/index.json.sig
|
||||
ls -lR app/src/main/assets/droiddeck-esync
|
||||
fi
|
||||
|
||||
- name: Cache PulseAudio 13.0 source
|
||||
id: pa-src
|
||||
uses: actions/cache@v4
|
||||
@@ -235,6 +375,11 @@ jobs:
|
||||
set -euo pipefail
|
||||
curl -fsSL -o pa.tar.gz https://github.com/pulseaudio/pulseaudio/archive/refs/tags/v13.0.tar.gz
|
||||
mkdir -p pa13 && tar -xzf pa.tar.gz -C pa13 --strip-components=1 && rm pa.tar.gz
|
||||
# DirectAudio - the game driver (one set per Wine audio interface), the Android-side helper and
|
||||
# the Steam client's sinks - comes from a pinned release of The412Banner/directaudio, checksummed,
|
||||
# exactly like gamescope; nothing compiled for audio is kept in this repo.
|
||||
- name: Fetch DirectAudio (tools/directaudio/release.env)
|
||||
run: tools/directaudio/fetch.sh "$PWD" "$PWD/sink-out"
|
||||
- name: Build the AAudio sink into the audio bundle
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -244,12 +389,12 @@ jobs:
|
||||
tar --use-compress-program=unzstd -xf app/src/main/assets/pulseaudio.tzst -C pa-bundle
|
||||
test ! -f pa-bundle/modules/arm64/module-aaudio-sink.so
|
||||
install -m755 sink-out/module-aaudio-sink.so pa-bundle/modules/arm64/module-aaudio-sink.so
|
||||
install -m755 sink-out/module-directaudio-sink.so pa-bundle/modules/arm64/module-directaudio-sink.so
|
||||
install -m755 sink-out/module-directaudio-native-sink.so pa-bundle/modules/arm64/module-directaudio-native-sink.so
|
||||
(cd pa-bundle && tar --use-compress-program='zstd -19' -cf ../pulseaudio.tzst .)
|
||||
mv pulseaudio.tzst app/src/main/assets/pulseaudio.tzst
|
||||
tar --use-compress-program=unzstd -tf app/src/main/assets/pulseaudio.tzst | grep -c '\.so$'
|
||||
mkdir -p app/build/prepared-assets
|
||||
mv pulseaudio.tzst app/build/prepared-assets/pulseaudio.tzst
|
||||
tar --use-compress-program=unzstd -tf app/build/prepared-assets/pulseaudio.tzst | grep -c '\.so$'
|
||||
rm -rf pa-bundle sink-out
|
||||
|
||||
- name: Cache proot
|
||||
id: proot
|
||||
uses: actions/cache@v4
|
||||
@@ -268,30 +413,64 @@ jobs:
|
||||
- name: Check the preloads
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash tools/linuxfs/check-preloads.sh app/src/main/assets/linuxfs
|
||||
D=app/src/main/assets/linuxfs
|
||||
NEED=$(readelf -d "$D/libfakeinput.so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p')
|
||||
for bad in libstdc++.so.6 libgcc_s.so.1; do
|
||||
if printf '%s\n' "$NEED" | grep -qx "$bad"; then
|
||||
echo "::error::libfakeinput.so links $bad - the C++ runtime must stay static"; exit 1
|
||||
fi
|
||||
done
|
||||
syms() { readelf -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; }
|
||||
FAKE=$(syms "$D/libfakeinput.so")
|
||||
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
|
||||
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
|
||||
done
|
||||
# The static C++ runtime stays private: every session process preloads this library,
|
||||
# and an exported personality routine takes over other programs' unwinding (shadPS4
|
||||
# aborted in pthread_exit).
|
||||
if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
|
||||
echo "::error::libfakeinput.so exports the C++ runtime"; exit 1
|
||||
fi
|
||||
SESSION=$(syms "$D/libblsession.so")
|
||||
for sym in socket bind getsockname setsockopt statfs statvfs; do
|
||||
grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; }
|
||||
done
|
||||
test -f "$D/usr/local/bin/bannerlator-session"
|
||||
test -f "$D/usr/local/bin/bannerlator-proton-extra"
|
||||
# The bridge ICD: libc only, and nothing exported but the loader's three entry points.
|
||||
VKB="$D/usr/local/lib/vkbridge/libvulkan_droidbridge.so"
|
||||
test -f "$VKB" && test -f "$D/usr/local/share/vkbridge/droidbridge_icd.json" && test -f "$D/usr/local/bin/droiddeck-vkbridge-smoke"
|
||||
VKB_NEED=$(readelf -d "$VKB" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p' | grep -vx 'libc.so.6' | grep -vx 'ld-linux-aarch64.so.1' || true)
|
||||
[ -z "$VKB_NEED" ] || { echo "::error::the bridge ICD needs $VKB_NEED"; exit 1; }
|
||||
[ "$(syms "$VKB" | grep -c '^vk_icd')" = 3 ] || { echo "::error::the bridge ICD does not export the loader interface"; exit 1; }
|
||||
|
||||
# Mali (Venus), David Cimo's route: the vtest server (jniLibs), the Venus ICD (assets/venus)
|
||||
# and the Mali compatibility layer (assets/linuxfs), built by build-venus.yml and fetched by
|
||||
# tag + sha256 like gamescope. The app uses it only on a GPU that is not an Adreno.
|
||||
- name: Fetch the Mali (Venus) component (tools/venus/release.env)
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
. tools/venus/release.env
|
||||
gh release download "${VENUS_TAG}" -R "${VENUS_REPO}" -p venus.tzst -O venus.tzst
|
||||
echo "${VENUS_SHA256} venus.tzst" | sha256sum -c -
|
||||
tar --use-compress-program=unzstd -xf venus.tzst -C app/src/main
|
||||
test -f app/src/main/jniLibs/arm64-v8a/libvirgl_test_server.so
|
||||
test -f app/src/main/assets/venus/libvulkan_virtio.so
|
||||
rm venus.tzst
|
||||
|
||||
# The store download engines (app/src/main/rust/stores) are Rust, built by Gradle's
|
||||
# buildRustStores task through cargo-ndk. rustup and cargo are on the runner image; the Android
|
||||
# target and cargo-ndk are added here. Cache = cargo registry + cargo-ndk + the crate's target
|
||||
# tree, keyed on the rustc version and Cargo.lock, so a source-only change rebuilds this crate
|
||||
# on top of the cached dependency objects, and a lockfile change still starts from the
|
||||
# previous objects (restore-keys).
|
||||
- name: Rust toolchain for the store engines (aarch64-linux-android)
|
||||
id: rust
|
||||
run: |
|
||||
set -euo pipefail
|
||||
rustup target add aarch64-linux-android
|
||||
echo "rustc=$(rustc -V | awk '{print $2}')" >> "$GITHUB_OUTPUT"
|
||||
rustc -V; cargo -V
|
||||
|
||||
- name: Cache cargo registry and the store engines' target
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry/index
|
||||
~/.cargo/registry/cache
|
||||
~/.cargo/git/db
|
||||
~/.cargo/bin/cargo-ndk
|
||||
app/src/main/rust/stores/target
|
||||
key: stores-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
stores-${{ steps.rust.outputs.rustc }}-
|
||||
|
||||
- name: cargo-ndk
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v cargo-ndk >/dev/null || cargo install cargo-ndk --locked
|
||||
cargo ndk --version
|
||||
|
||||
- name: Cache the CMake build tree
|
||||
uses: actions/cache@v4
|
||||
@@ -303,41 +482,69 @@ jobs:
|
||||
restore-keys: |
|
||||
cxx-${{ env.NDK_VERSION }}-
|
||||
|
||||
- name: Build GOG Galaxy companion
|
||||
if: steps.preloads.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
rustup toolchain install 1.90.0 --profile minimal
|
||||
rustup target add --toolchain 1.90.0 aarch64-unknown-linux-gnu
|
||||
RUSTUP_TOOLCHAIN=1.90.0 bash tools/comet/build.sh
|
||||
|
||||
- name: Build
|
||||
id: build
|
||||
env:
|
||||
DROIDDECK_BUILD_LABEL: ${{ steps.build-label.outputs.label }}
|
||||
SGDB_API_KEY: ${{ secrets.SGDB_API_KEY }}
|
||||
run: |
|
||||
set -o pipefail
|
||||
python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
|
||||
python3 tools/powervr/fetch.py
|
||||
python3 tools/release/runtime_inputs.py record
|
||||
./gradlew assembleRelease --console=plain -PndkVersion="$NDK_VERSION" 2>&1 | tee /tmp/build.log
|
||||
python3 tools/release/check_session_assets.py app/build/outputs/apk/release/app-release.apk
|
||||
python3 tools/release/runtime_inputs.py apk app/build/outputs/apk/release/app-release.apk
|
||||
|
||||
- name: Check the store engines' library
|
||||
# The exports Kotlin binds must be in the apk's libdroiddeckstores.so, or the stores fail on
|
||||
# the device with an UnsatisfiedLinkError instead of here. The lockfile check is the
|
||||
# reproducibility guard: cargo must not have had to re-resolve anything.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||
python3 tools/release/check_android_libraries.py app/build/outputs/apk/release/app-release.apk \
|
||||
--readelf "$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin/llvm-readelf"
|
||||
git diff --stat -- app/src/main/rust/stores/Cargo.lock
|
||||
git diff --exit-code -- app/src/main/rust/stores/Cargo.lock \
|
||||
|| { echo "::error::Cargo.lock changed during the build; commit the regenerated lockfile (uploaded as stores-cargo-lock)"; exit 1; }
|
||||
|
||||
- name: Store engines host unit tests
|
||||
# The crate's #[test] functions are pure host-side logic (manifest parsing, chunk plans,
|
||||
# assembly from a cache, hashes), so a plain `cargo test` on the runner's own architecture
|
||||
# runs them; the Android build above compiles none of them. Informational on this first
|
||||
# run - the point is to learn whether they pass - and bounded so a hang can never hold
|
||||
# the apk. Make it blocking once it is known green.
|
||||
timeout-minutes: 10
|
||||
continue-on-error: true
|
||||
run: |
|
||||
cd app/src/main/rust/stores
|
||||
cargo test --locked 2>&1 | tail -60
|
||||
|
||||
- name: Upload the regenerated Cargo.lock
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: stores-cargo-lock
|
||||
path: app/src/main/rust/stores/Cargo.lock
|
||||
if-no-files-found: ignore
|
||||
|
||||
- name: Steam import and game environment tests
|
||||
run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
|
||||
run: |
|
||||
# The Xclipse layer regression test compiles the layer against the distribution's headers.
|
||||
sudo apt-get update -qq && sudo apt-get install -y -qq libvulkan-dev >/dev/null
|
||||
python3 -m unittest discover -s tools/tests -p 'test_*.py'
|
||||
|
||||
- name: Unit tests
|
||||
run: ./gradlew testReleaseUnitTest --console=plain -PndkVersion="$NDK_VERSION"
|
||||
|
||||
- name: Check the native dependency closure
|
||||
run: |
|
||||
set -euo pipefail
|
||||
APK=$(find app/build/outputs/apk -name '*.apk' | head -1)
|
||||
WORK=$(mktemp -d)
|
||||
unzip -q "$APK" 'lib/arm64-v8a/*' -d "$WORK"
|
||||
cd "$WORK/lib/arm64-v8a"
|
||||
SYSTEM="libc.so libm.so libdl.so liblog.so libandroid.so libz.so libvulkan.so libstdc++.so
|
||||
libGLESv2.so libEGL.so libnativewindow.so libjnigraphics.so libaaudio.so
|
||||
libOpenSLES.so libmediandk.so libcamera2ndk.so libsync.so libneuralnetworks.so"
|
||||
fail=0
|
||||
for so in *.so; do
|
||||
for need in $(readelf -d "$so" | sed -n 's/.*NEEDED.*\[\(.*\)\]/\1/p'); do
|
||||
[ -f "$need" ] && continue
|
||||
case " $(echo $SYSTEM) " in *" $need "*) continue ;; esac
|
||||
echo "::error::$so needs $need, which is neither in the apk nor a platform library"
|
||||
fail=1
|
||||
done
|
||||
done
|
||||
exit $fail
|
||||
|
||||
- name: Sign with the testkey (v1 + v2 + v3)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
name: Publish the CI Debian image
|
||||
|
||||
# Pulls the Debian 11 image the x86 preloads build in, once, and publishes it as a release asset
|
||||
# on this repo so build.yml never depends on a registry mirror's rate limit. Run it again (with a
|
||||
# new tag) only to refresh the image; tools/linuxfs/debian-image.env names the one builds use.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Release tag to publish to (a new -rN tag for a refresh; builds pin the one in tools/linuxfs/debian-image.env)'
|
||||
required: true
|
||||
default: 'ci-debian-bullseye-r2'
|
||||
replace:
|
||||
description: 'Overwrite the asset if the release already has one (changes its checksum: re-pin it in debian-image.env)'
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- name: Pull, save and publish
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
REPLACE: ${{ inputs.replace }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
image=public.ecr.aws/docker/library/debian:bullseye
|
||||
# A published image is pinned by checksum in the build; never replace one by accident.
|
||||
if [ "$REPLACE" != true ] && gh release view "$TAG" -R "$GITHUB_REPOSITORY" --json assets -q '.assets[].name' 2>/dev/null | grep -qx debian-bullseye.tar.zst; then
|
||||
echo "::error::$TAG already carries debian-bullseye.tar.zst; publish to a new tag, or set replace and re-pin tools/linuxfs/debian-image.env"
|
||||
exit 1
|
||||
fi
|
||||
for attempt in 1 2 3 4 5 6; do
|
||||
docker pull "$image" && break
|
||||
[ "$attempt" -lt 6 ] || { echo "::error::could not pull $image"; exit 1; }
|
||||
echo "pull attempt $attempt failed (registry busy?); retrying in $((attempt * 30)) s"
|
||||
sleep $((attempt * 30))
|
||||
done
|
||||
docker image inspect "$image" --format 'image id {{.Id}} created {{.Created}}'
|
||||
docker save "$image" | zstd -19 -T0 -o debian-bullseye.tar.zst
|
||||
sha256sum debian-bullseye.tar.zst | tee SHA256SUMS
|
||||
ls -l debian-bullseye.tar.zst
|
||||
if ! gh release view "$TAG" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
gh release create "$TAG" -R "$GITHUB_REPOSITORY" --title "CI Debian 11 image ($TAG)" --latest=false \
|
||||
--notes "The debian:bullseye image build.yml compiles the x86 preloads in (glibc 2.31), saved with docker save and compressed with zstd. Pulled from public.ecr.aws/docker/library/debian:bullseye on $(date -u +%Y-%m-%d); image id $(docker image inspect "$image" --format '{{.Id}}'). Pinned in tools/linuxfs/debian-image.env."
|
||||
fi
|
||||
gh release upload "$TAG" -R "$GITHUB_REPOSITORY" debian-bullseye.tar.zst SHA256SUMS --clobber
|
||||
{ echo "Published \`$TAG\`:"; echo; echo '```'; cat SHA256SUMS; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
|
||||
@@ -13,13 +13,28 @@ permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
|
||||
concurrency:
|
||||
group: pr-release-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
cleanup:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Check the current PR state
|
||||
id: state
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
state=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .state)
|
||||
echo "closed=$([ "$state" = closed ] && echo true || echo false)" >> "$GITHUB_OUTPUT"
|
||||
# A token of the org's "DroidDeck CI Publisher" app, as build.yml's announce job uses.
|
||||
- uses: actions/create-github-app-token@v2
|
||||
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||
id: ci-token
|
||||
with:
|
||||
app-id: ${{ vars.DROIDDECK_CI_APP_ID }}
|
||||
@@ -27,6 +42,7 @@ jobs:
|
||||
owner: Droid-Deck
|
||||
repositories: DroidDeck-CI
|
||||
- name: Delete the test build
|
||||
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||
env:
|
||||
GH_TOKEN: ${{ steps.ci-token.outputs.token }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
@@ -42,6 +58,19 @@ jobs:
|
||||
done
|
||||
[ "$found" = 1 ] || echo "No test build for PR #$PR_NUMBER"
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||
with:
|
||||
ref: main
|
||||
persist-credentials: false
|
||||
- name: Retire the Discord PR announcement
|
||||
if: ${{ steps.state.outputs.closed == 'true' }}
|
||||
env:
|
||||
WEBHOOK: ${{ secrets.DISCORD_PR_BUILDS_WEBHOOK }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
run: python3 tools/release/pr_discord.py retire
|
||||
|
||||
catalog:
|
||||
needs: cleanup
|
||||
if: ${{ always() }}
|
||||
|
||||
@@ -26,6 +26,7 @@ permissions:
|
||||
concurrency:
|
||||
group: pr-release-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'workflow_run' && github.event.workflow_run.pull_requests[0].number || inputs.pr_number }}
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
authorize:
|
||||
@@ -88,7 +89,8 @@ jobs:
|
||||
esac
|
||||
fi
|
||||
pr=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null
|
||||
jq -e '.state == "open" and .draft == false and .base.ref == "main"' <<<"$pr" >/dev/null ||
|
||||
{ echo "::error::PR #$PR_NUMBER must be open, ready for review, and target main"; exit 1; }
|
||||
head=$(jq -r '.head.sha' <<<"$pr")
|
||||
base=$(jq -r '.base.sha' <<<"$pr")
|
||||
|
||||
@@ -114,36 +116,39 @@ jobs:
|
||||
sleep 30
|
||||
done
|
||||
[[ -n "$run_id" ]] || { echo '::error::The PR build did not finish within 30 minutes'; exit 1; }
|
||||
# GitHub leaves a run's pull_requests empty when its head is in a fork, so the build is
|
||||
# tied to this PR by its head repository, branch and commit instead.
|
||||
run=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id")
|
||||
jq -e --arg head "$head" --arg base "$base" --argjson number "$PR_NUMBER" '
|
||||
jq -e --arg head "$head" --arg repo "$(jq -r .head.repo.full_name <<<"$pr")" --arg ref "$(jq -r .head.ref <<<"$pr")" '
|
||||
.event == "pull_request" and .head_sha == $head and .conclusion == "success" and
|
||||
any(.pull_requests[]?; .number == $number and .head.sha == $head and .base.sha == $base)
|
||||
' <<<"$run" >/dev/null
|
||||
.head_repository.full_name == $repo and .head_branch == $ref
|
||||
' <<<"$run" >/dev/null ||
|
||||
{ echo "::error::Build run $run_id is not a green build of PR #$PR_NUMBER at ${head:0:7}"; exit 1; }
|
||||
|
||||
sdk=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}
|
||||
tools=$(find "$sdk/build-tools" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -1)
|
||||
stable_tag=$(gh api "repos/$GITHUB_REPOSITORY/releases/latest" --jq .tag_name)
|
||||
mkdir -p "$RUNNER_TEMP/stable" "$RUNNER_TEMP/pr"
|
||||
gh release download "$stable_tag" -R "$GITHUB_REPOSITORY" \
|
||||
-p "DroidDeck-$stable_tag.apk" -D "$RUNNER_TEMP/stable"
|
||||
# A PR build is made from the PR merged onto main, so it must install over main's own
|
||||
# build. main is what this job checked out; no release has to exist or be marked latest.
|
||||
main_code=$(sed -n 's/^[[:space:]]*versionCode[[:space:]][[:space:]]*\([0-9][0-9]*\)[[:space:]]*$/\1/p' app/build.gradle)
|
||||
[[ "$main_code" =~ ^[0-9]+$ ]] || { echo "::error::No numeric versionCode in main's app/build.gradle"; exit 1; }
|
||||
mkdir -p "$RUNNER_TEMP/pr"
|
||||
gh run download "$run_id" -R "$GITHUB_REPOSITORY" -n droiddeck-apk -D "$RUNNER_TEMP/pr"
|
||||
mapfile -t apks < <(find "$RUNNER_TEMP/pr" -type f -name '*.apk')
|
||||
[[ ${#apks[@]} == 1 ]] || { echo '::error::Expected one PR APK'; exit 1; }
|
||||
package_line() {
|
||||
"$tools/aapt" dump badging "$1" | sed -n "s/^package: name='\\([^']*\\)' versionCode='\\([^']*\\)'.*/\\1 \\2/p"
|
||||
}
|
||||
stable=$(package_line "$RUNNER_TEMP/stable/DroidDeck-$stable_tag.apk")
|
||||
candidate=$(package_line "${apks[0]}")
|
||||
[[ "$stable" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && "$candidate" =~ ^com\.droiddeck\.launcher\ [0-9]+$ &&
|
||||
${candidate##* } -ge ${stable##* } ]] || {
|
||||
echo "::error::PR package/versionCode '$candidate' cannot install over stable '$stable'"; exit 1;
|
||||
[[ "$candidate" =~ ^com\.droiddeck\.launcher\ [0-9]+$ && ${candidate##* } -ge $main_code ]] || {
|
||||
echo "::error::PR package/versionCode '$candidate' cannot install over main (versionCode $main_code)"; exit 1;
|
||||
}
|
||||
|
||||
current=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
|
||||
jq -e --arg head "$head" --arg base "$base" '
|
||||
.state == "open" and .draft == false and .base.ref == "main" and
|
||||
.head.sha == $head and .base.sha == $base
|
||||
' <<<"$current" >/dev/null
|
||||
' <<<"$current" >/dev/null ||
|
||||
{ echo "::error::PR #$PR_NUMBER moved on while its build was checked; publish again"; exit 1; }
|
||||
{
|
||||
echo "pr_number=$PR_NUMBER"
|
||||
echo "run_id=$run_id"
|
||||
@@ -174,6 +179,10 @@ jobs:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
persist-credentials: false
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: droiddeck-pr-signed-*
|
||||
@@ -303,39 +312,27 @@ jobs:
|
||||
$NEXT
|
||||
EOF
|
||||
)
|
||||
id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --paginate \
|
||||
--jq ".[] | select(.body | startswith(\"$mark\")) | .id" | head -1 || true)
|
||||
comment=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" --paginate --slurp | \
|
||||
jq "[.[][] | select(.user.login == \"github-actions[bot]\") | select(.body | startswith(\"$mark\"))] | first // {}")
|
||||
id=$(jq -r '.id // empty' <<<"$comment")
|
||||
if [ -n "$id" ]; then
|
||||
state=$(jq -r '.body | split("\n")[] | select(startswith("<!-- droiddeck-discord: ") and endswith(" -->"))' <<<"$comment")
|
||||
if [ -n "$state" ]; then body=$(printf '%s\n%s' "$body" "$state"); fi
|
||||
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -f body="$body" >/dev/null
|
||||
else
|
||||
gh api -X POST "repos/$GITHUB_REPOSITORY/issues/$PR_NUMBER/comments" -f body="$body" >/dev/null
|
||||
fi
|
||||
|
||||
# Asked for (the label, a manual run): always announced. Signed on its own after a push:
|
||||
# only a PR's first test build is, and later ones update its release quietly.
|
||||
- name: Post to Discord
|
||||
if: ${{ always() && steps.publish.outcome == 'success' && (needs.authorize.outputs.automatic != 'true' || steps.publish.outputs.first == 'true') }}
|
||||
- name: Update the Discord PR announcement
|
||||
if: ${{ always() && steps.publish.outcome == 'success' }}
|
||||
env:
|
||||
WEBHOOK: ${{ secrets.DISCORD_BUILDS_WEBHOOK }}
|
||||
WEBHOOK: ${{ secrets.DISCORD_PR_BUILDS_WEBHOOK }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ needs.authorize.outputs.pr_number }}
|
||||
HEAD_SHA: ${{ needs.authorize.outputs.head_sha }}
|
||||
RELEASE: ${{ steps.publish.outputs.release }}
|
||||
APK: ${{ steps.publish.outputs.apk }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "$WEBHOOK" ]; then
|
||||
echo "::notice::No DISCORD_BUILDS_WEBHOOK secret; nothing posted"
|
||||
exit 0
|
||||
fi
|
||||
short=${HEAD_SHA:0:7}
|
||||
title=$(gh api "repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER" --jq .title)
|
||||
what="[#$PR_NUMBER]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/pull/$PR_NUMBER): $title"
|
||||
get=$(printf 'Download: [standard APK](<%s>) · [all variants](<%s>)' "$APK" "$RELEASE")
|
||||
content=$(printf '**New signed PR test build** \`pr-%s\` · \`%s\`\n%s\n_Not merged — for testing._\n%s' "$PR_NUMBER" "$short" "$what" "$get")
|
||||
jq -n --arg content "$content" '{content: $content, allowed_mentions: {parse: []}}' |
|
||||
curl -fsS -H 'Content-Type: application/json' -d @- "$WEBHOOK" -o /dev/null
|
||||
echo "Posted: $content"
|
||||
run: python3 tools/release/pr_discord.py publish
|
||||
|
||||
catalog:
|
||||
needs: publish
|
||||
|
||||
@@ -62,3 +62,59 @@ jobs:
|
||||
label: ${{ inputs.version }}
|
||||
artifact: droiddeck-release
|
||||
secrets: inherit
|
||||
|
||||
# The release is made here, from the apks this run signed, so it traces back to its Build APK run.
|
||||
publish:
|
||||
name: publish the release
|
||||
needs: [find, sign]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: droiddeck-release-*
|
||||
merge-multiple: true
|
||||
path: out
|
||||
|
||||
- name: Publish
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
BUILD_RUN: ${{ needs.find.outputs.run_id }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
notes="docs/releases/$VERSION.md"
|
||||
[ -f "$notes" ] || { echo "::error::$notes is missing: add the release notes first"; exit 1; }
|
||||
if gh release view "$VERSION" -R "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
|
||||
echo "::error::release $VERSION already exists"; exit 1
|
||||
fi
|
||||
# The notes' first line is the title; media paths become raw URLs at this release's tag.
|
||||
title=$(sed -n '1s/^# *//p' "$notes")
|
||||
[ -n "$title" ] || title="DroidDeck $VERSION"
|
||||
raw="https://raw.githubusercontent.com/$GITHUB_REPOSITORY/$VERSION/docs/releases/media/"
|
||||
{
|
||||
sed '1{/^# /d;}' "$notes" | sed -E "s#(\]\(|src=\")media/#\1$raw#g"
|
||||
echo
|
||||
echo "---"
|
||||
echo
|
||||
echo "Built by [Build APK run $BUILD_RUN]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN) from \`$GITHUB_SHA\`, signed and published by [Release APKs run $GITHUB_RUN_ID]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID)."
|
||||
} > "$RUNNER_TEMP/body.md"
|
||||
( cd out && cat SHA256SUMS-*.txt | sort -k2 > SHA256SUMS.txt && rm SHA256SUMS-*.txt && cat SHA256SUMS.txt )
|
||||
gh release create "$VERSION" -R "$GITHUB_REPOSITORY" out/*.apk out/SHA256SUMS.txt \
|
||||
--target "$GITHUB_SHA" --title "$title" --notes-file "$RUNNER_TEMP/body.md" --latest
|
||||
echo "Published [$title]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/releases/tag/$VERSION)" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# A release made with this run's token fires no release event, so the in-app catalog is refreshed here.
|
||||
catalog:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/update-catalog.yml
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
secrets: inherit
|
||||
@@ -13,6 +13,7 @@ permissions:
|
||||
concurrency:
|
||||
group: update-app-catalog
|
||||
cancel-in-progress: false
|
||||
queue: max
|
||||
|
||||
jobs:
|
||||
catalog:
|
||||
|
||||
@@ -13,7 +13,13 @@ captures/
|
||||
app/src/main/assets/linuxfs/
|
||||
app/src/main/jniLibs/arm64-v8a/libproot.so
|
||||
app/src/main/jniLibs/arm64-v8a/.proot-inputs
|
||||
app/src/main/jniLibs/arm64-v8a/.proot-outputs
|
||||
app/src/main/jniLibs/arm64-v8a/libproot-loader.so
|
||||
app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so
|
||||
# The store download engines (app/src/main/rust/stores) are cross-compiled by Gradle into
|
||||
# app/build/rustJniLibs; cargo's own build tree stays next to the crate. Neither is source.
|
||||
app/src/main/rust/stores/target/
|
||||
app/src/main/assets/droiddeck-esync/
|
||||
|
||||
# Kotlin compiler session files (build-tool state, never source).
|
||||
.kotlin/
|
||||
@@ -33,3 +39,5 @@ __pycache__/
|
||||
|
||||
# Local signing with the release key (tools/build_local.sh); holds a password.
|
||||
.signing.env
|
||||
app/src/main/assets/directaudio/
|
||||
app/src/main/assets/hybris/
|
||||
@@ -5,30 +5,36 @@
|
||||
</picture>
|
||||
</p>
|
||||
|
||||
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Adreno handheld, with Windows games through Valve's ARM64 Proton.
|
||||
DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big Picture on your Android handheld, with Windows games through Valve's ARM64 Proton.
|
||||
|
||||
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
|
||||
|
||||
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
|
||||
|
||||
> Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team.
|
||||
|
||||
## Requirements and install
|
||||
|
||||
Use Android 9 or newer on a supported Adreno device (730 or newer, or 8xx). Mali, Xclipse, PowerVR, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; see [docs/development/flatpak.md](docs/development/flatpak.md).
|
||||
Use Android 9 or newer. Supported Adreno devices include 730 or newer, or 8xx. Adreno 6xx is experimental: DirectX 11 uses DXVK 2 and may run, and DirectX 12 games can still crash. PowerVR support is experimental: where the system Vulkan backend is available, the app selects it automatically. Mali, Xclipse, and Adreno 710 are unsupported. No root is required. Allow about 3 GB for the runtime and 1.1 GB more for the desktop and emulators. Install the APK from [Releases](https://github.com/Droid-Deck/DroidDeck/releases), install the Linux runtime, then press **Play** and sign in. Steam downloads on first launch. Install **Desktop & apps** to use the desktop and emulators. The **Store** installs Linux apps and games from Flathub (ARM64 builds) with Flatpak; with additional options to install Appimages and set up scripts. **Stores** (Setup › Stores › "Show Stores in the rail") signs in to GOG, Epic Games and Amazon Games, browses their catalogs and libraries, downloads games into the Games storage and adds each one to the Steam client as a non-Steam game, so it launches through Proton like everything else; the cog on its chip row sets which tab a store opens on and the download speed tier.
|
||||
|
||||
On Android 12+, if Steam exits without a log, turn off **Restrict child processes** in Developer options.
|
||||
Before Steam launches, you must turn off **Restrict child processes** in Developer options. If this option is not available in developer settings (Android 12 and 13 devices), first launch of Steam will present a "Fix it for me" button, which will help automate the setup process.
|
||||
|
||||
## Community
|
||||
|
||||
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the session folder from `Download/DroidDeck/` so the logs come with it.
|
||||
Join the [DroidDeck Discord](https://discord.gg/JRGAvawjsm) for help, Preview builds, and device reports. Bug reports go in its **#bug-reports** forum; attach the zip from **Share logs** (Setup, or the session drawer) so the logs come with it.
|
||||
|
||||
## Build
|
||||
|
||||
Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, and `zstd` installed. It builds the ARM64 audio sinks from PulseAudio 13.0 and packages them into the APK at `app/build/outputs/apk/release/app-release.apk`. Set `DROIDDECK_PA13_SOURCE_DIR` to an existing PulseAudio 13.0 source directory to skip downloading it. To install the APK on an attached device, run `tools/deploy_local.sh`.
|
||||
Run `tools/build_local.sh` with Docker, Java 17, the Android SDK/NDK, Rust through rustup, GitHub CLI, Python 3, and `zstd` installed. It prepares the same native libraries, pinned components and audio sinks as CI, then checks the APK's assets, JNI exports and dependencies. The APK is at `app/build/outputs/apk/release/app-release.apk`. Set `DROIDDECK_PA13_SOURCE_DIR` to an existing PulseAudio 13.0 source directory to skip downloading it. Set `DROIDDECK_SIGNING_ENV` to a signing environment file to install over a release build; relative keystore paths resolve beside that file. To install on an attached device, run `tools/deploy_local.sh`.
|
||||
|
||||
After preparation, ordinary `./gradlew :app:assembleRelease` builds can reuse the verified inputs. If native sources, component pins or staged files change, packaging stops with instructions to rerun the helper. Generated audio stays under `app/build/`; the tracked base bundle is never modified. `./gradlew -PskipRust=true :app:testDebugUnitTest` needs no native preparation. For an APK without store engines, use `DROIDDECK_SKIP_RUST=1 tools/build_local.sh`; it omits cached engine libraries too.
|
||||
|
||||
Run the helper and preload regression suite with `bash tools/test_local.sh`. On macOS it runs in Linux through Docker, matching the helpers' runtime and CI instead of compiling Linux preloads against macOS headers.
|
||||
|
||||
## Limits
|
||||
|
||||
Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. See the session logs in `Download/DroidDeck/` when diagnosing problems.
|
||||
Compatibility and performance vary by device; hardware validation is limited. Desktop compositing uses software rendering. Firefox sandboxing is reduced under proot. Logs are kept app-private (`files/logs/`, the last 30 sessions); **Share logs** packs the newest session, with the stores and tool logs, into one scrubbed zip.
|
||||
|
||||
## Credits and licence
|
||||
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
|
||||
+132
-2
@@ -59,6 +59,19 @@ def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'tr
|
||||
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
|
||||
// When the source was committed, for "built 3 hours ago": fixed per commit, so it costs no rebuilds.
|
||||
def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with { it.isLong() ? it : '0' }
|
||||
// The desktop package this apk installs (tools/desktop-kde/release.env): published once per tag in
|
||||
// DroidDeck-Components, pinned here with its checksum like gamescope and the esync packs, so the
|
||||
// desktop scripts in the apk always get the package they were made for.
|
||||
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
|
||||
.findAll { it.contains('=') && !it.startsWith('#') }
|
||||
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
|
||||
def desktopRemovalSources = new groovy.json.JsonSlurper().parse(file('src/main/assets/desktop-removal/sources.json'))
|
||||
if (desktopRemovalSources.archives[desktopKde.DESKTOP_KDE_TAG] != desktopKde.DESKTOP_KDE_SHA256) {
|
||||
throw new GradleException('Desktop removal inventories do not match the pinned archive')
|
||||
}
|
||||
if (!file('src/main/assets/desktop-removal/versions.txt').readLines().contains(desktopKde.DESKTOP_KDE_TAG)) {
|
||||
throw new GradleException('Regenerate desktop removal inventories for ' + desktopKde.DESKTOP_KDE_TAG)
|
||||
}
|
||||
// tools/release/variants.txt as "package=suffix;...", so the updater picks the apk of the package it runs as.
|
||||
def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
|
||||
.findAll { it.trim() && !it.startsWith('#') }
|
||||
@@ -79,8 +92,8 @@ android {
|
||||
// file out of its own data directory, and this app's entire job is to exec a rootfs:
|
||||
// proot, gamescope, the Steam client and everything it launches all live under files/.
|
||||
targetSdkVersion 28
|
||||
versionCode 9
|
||||
versionName "0.2.0"
|
||||
versionCode 13
|
||||
versionName "0.4.0"
|
||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||
@@ -88,6 +101,11 @@ android {
|
||||
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
|
||||
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
|
||||
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
|
||||
buildConfigField "String", "SGDB_API_KEY", "\"${System.getenv("SGDB_API_KEY") ?: project.findProperty("sgdbApiKey") ?: ""}\""
|
||||
buildConfigField "String", "DESKTOP_KDE_TAG", "\"${desktopKde.DESKTOP_KDE_TAG}\""
|
||||
buildConfigField "String", "DESKTOP_KDE_URL", "\"https://github.com/${desktopKde.DESKTOP_KDE_REPO}/releases/download/${desktopKde.DESKTOP_KDE_TAG}/desktop-kde.tar.zst\""
|
||||
buildConfigField "String", "DESKTOP_KDE_SHA256", "\"${desktopKde.DESKTOP_KDE_SHA256}\""
|
||||
buildConfigField "long", "DESKTOP_KDE_SIZE", "${desktopKde.DESKTOP_KDE_SIZE}L"
|
||||
|
||||
ndk {
|
||||
abiFilters 'arm64-v8a'
|
||||
@@ -131,6 +149,9 @@ android {
|
||||
release {
|
||||
minifyEnabled false
|
||||
signingConfig signingConfigs.testkey
|
||||
// Mali bridge development fork: debuggable so `adb shell run-as` reaches the session
|
||||
// logs and VkBridgeNative's development override (-Pdroiddeck.notDebuggable to drop).
|
||||
debuggable !project.hasProperty('droiddeck.notDebuggable')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,6 +186,8 @@ android {
|
||||
testOptions {
|
||||
// Plain JVM tests: a stray android.util.Log call returns a default instead of throwing.
|
||||
unitTests.returnDefaultValues = true
|
||||
// Robolectric tests start activities whose text is now all string resources.
|
||||
unitTests.includeAndroidResources = true
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
@@ -176,20 +199,124 @@ android {
|
||||
}
|
||||
}
|
||||
|
||||
// Session scripts must follow this checkout even when the native asset bundle is cached.
|
||||
// A stale local bundle can omit a newly required helper on a fresh runtime install.
|
||||
def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
|
||||
from(rootProject.file('tools/linuxfs/overlay')) {
|
||||
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
|
||||
}
|
||||
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
|
||||
|
||||
// Prepared audio lives under build/, so native builds never rewrite the tracked base bundle.
|
||||
// Copying into one asset root also prevents an old base bundle winning a duplicate asset merge.
|
||||
def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets')
|
||||
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
|
||||
dependsOn(stageSessionScripts)
|
||||
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
|
||||
from(layout.buildDirectory.dir('prepared-assets'))
|
||||
into(runtimeAssetsDir)
|
||||
}
|
||||
android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir])
|
||||
tasks.named('preBuild').configure { dependsOn(stageRuntimeAssets) }
|
||||
|
||||
// Unit tests and previews remain usable without Docker. Packaging an APK requires the complete
|
||||
// runtime payload prepared by the local helper or CI, with matching sources and output hashes.
|
||||
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
|
||||
// The session scripts are re-copied into the asset tree by stageSessionScripts; with parallel
|
||||
// task execution this check once hashed a file mid-copy and failed a main build. Hash only
|
||||
// once the staging has finished.
|
||||
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
|
||||
workingDir rootProject.projectDir
|
||||
commandLine 'python3', 'tools/release/runtime_inputs.py', 'verify'
|
||||
}
|
||||
tasks.configureEach { task ->
|
||||
if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs)
|
||||
}
|
||||
|
||||
// The GOG / Epic / Amazon download engines are Rust (app/src/main/rust/stores, ported from
|
||||
// Bannerlator's bl-steam-client crate). cargo-ndk cross-compiles them for arm64-v8a into the build
|
||||
// directory, which is one more jniLibs source below: nothing compiled is committed, the same rule
|
||||
// the preloads, proot and the DirectAudio relay follow. cargo-ndk exports the NDK clang/llvm-ar as
|
||||
// the C compiler for the one C-compiling crate (ring, under rustls) - the step Bannerlator's CI
|
||||
// does by hand - and reads the NDK from ANDROID_NDK_HOME, which is set to the NDK this build pins.
|
||||
// -PskipRust=true builds without the library, for a checkout with no Rust toolchain: the stores
|
||||
// then report themselves unavailable instead of the build failing.
|
||||
def rustCrateDir = layout.projectDirectory.dir('src/main/rust/stores')
|
||||
def rustJniLibsDir = layout.buildDirectory.dir('rustJniLibs')
|
||||
def skipRust = (project.findProperty('skipRust') ?: 'false').toString().toBoolean()
|
||||
def buildRustStores = tasks.register('buildRustStores', Exec) {
|
||||
description = 'Cross-compiles the store download engines (libdroiddeckstores.so) with cargo-ndk.'
|
||||
onlyIf { !skipRust }
|
||||
inputs.dir(rustCrateDir.dir('src'))
|
||||
inputs.files(rustCrateDir.file('Cargo.toml'), rustCrateDir.file('Cargo.lock'))
|
||||
inputs.property('ndkVersion', android.ndkVersion)
|
||||
if (!skipRust) inputs.property('rustToolchain', providers.exec {
|
||||
environment 'PATH', "${System.getProperty('user.home')}/.cargo/bin${File.pathSeparator}${System.getenv('PATH')}"
|
||||
commandLine 'rustup', 'run', 'stable', 'rustc', '-Vv'
|
||||
}.standardOutput.asText)
|
||||
outputs.dir(rustJniLibsDir)
|
||||
workingDir rustCrateDir
|
||||
// The configuration cache serialises the task, so everything it needs is resolved here, not
|
||||
// in doFirst. ~/.cargo/bin is where rustup puts cargo and cargo-ndk; an IDE-launched Gradle
|
||||
// does not always have it on PATH.
|
||||
def cargoBin = "${System.getProperty('user.home')}/.cargo/bin"
|
||||
environment 'PATH', "${cargoBin}${File.pathSeparator}${System.getenv('PATH')}"
|
||||
environment 'ANDROID_NDK_HOME', android.ndkDirectory.absolutePath
|
||||
environment 'CARGO_TERM_COLOR', 'never'
|
||||
if (!skipRust) environment 'RUSTC', providers.exec {
|
||||
commandLine 'rustup', 'which', '--toolchain', 'stable', 'rustc'
|
||||
}.standardOutput.asText.get().trim()
|
||||
// --platform 26 = minSdkVersion: the engines link against the API 26 libc, like the C++ code.
|
||||
// Homebrew's cargo/rustc can precede rustup on macOS and use a different sysroot, despite
|
||||
// rustup reporting the Android target installed. Run both through the selected toolchain.
|
||||
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '26',
|
||||
'--output-dir', rustJniLibsDir.get().asFile.absolutePath,
|
||||
'build', '--release', '--locked'
|
||||
}
|
||||
// Skipping Rust must omit its library even if another build left a cached .so behind.
|
||||
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildRustStores) }
|
||||
|
||||
// The Mali bridge's server (tools/vkbridge, app/src/main/cpp/vkbridge) is a program, not a library:
|
||||
// it runs beside the session as the app's child, so a driver crash ends that process and not the
|
||||
// app. AGP's CMake integration packages only shared libraries, so the NDK's clang builds it here
|
||||
// into one more jniLibs source, named libvkbridge_server.so so Android extracts it (the native
|
||||
// library directory is the one place the app may exec from).
|
||||
def vkbridgeJniLibsDir = layout.buildDirectory.dir('vkbridgeJniLibs')
|
||||
def buildVkBridgeServer = tasks.register('buildVkBridgeServer', Exec) {
|
||||
description = 'Builds the Vulkan bridge server (libvkbridge_server.so) with the NDK.'
|
||||
inputs.dir(rootProject.file('tools/vkbridge/common'))
|
||||
inputs.dir(layout.projectDirectory.dir('src/main/cpp/vkbridge'))
|
||||
inputs.file(rootProject.file('tools/vkbridge/build-server-android.sh'))
|
||||
outputs.dir(vkbridgeJniLibsDir)
|
||||
commandLine 'bash', rootProject.file('tools/vkbridge/build-server-android.sh').absolutePath,
|
||||
android.ndkDirectory.absolutePath, vkbridgeJniLibsDir.get().asFile.absolutePath
|
||||
}
|
||||
android.sourceSets.main.jniLibs.srcDir(vkbridgeJniLibsDir)
|
||||
tasks.named('preBuild').configure { dependsOn(buildVkBridgeServer) }
|
||||
|
||||
dependencies {
|
||||
// The runtime tarball is a zstd-compressed tar.
|
||||
implementation 'com.github.luben:zstd-jni:1.5.2-3@aar'
|
||||
implementation 'org.apache.commons:commons-compress:1.27.1'
|
||||
// Bannerlator's Windows components come as .tar.xz (WinComponents).
|
||||
implementation 'org.tukaani:xz:1.10'
|
||||
// The UI: every menu, dialog and overlay is Compose. The session's SurfaceView and the
|
||||
// on-screen pad are Views underneath it, which is what they are in every Compose app.
|
||||
implementation platform('androidx.compose:compose-bom:2024.02.00')
|
||||
implementation 'androidx.compose.ui:ui'
|
||||
implementation 'androidx.compose.material3:material3'
|
||||
// @Preview for the composables; the tooling that renders them is a debug-only dependency.
|
||||
implementation 'androidx.compose.ui:ui-tooling-preview'
|
||||
debugImplementation 'androidx.compose.ui:ui-tooling'
|
||||
implementation 'androidx.activity:activity-compose:1.8.2'
|
||||
// The File Manager, Bannerlator's: its icon set, image thumbnails and the coroutines it
|
||||
// copies on. Same versions as Bannerlator so the screen stays a straight copy.
|
||||
implementation 'androidx.compose.material:material-icons-extended'
|
||||
implementation 'io.coil-kt:coil-compose:2.6.0'
|
||||
implementation 'com.caverock:androidsvg-aar:1.4'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||
// ADB-over-Wi-Fi pairing and authenticated shell client. Users still approve pairing from
|
||||
// Android's Wireless debugging screen; DroidDeck only runs its one fixed setting command.
|
||||
@@ -199,4 +326,7 @@ dependencies {
|
||||
|
||||
testImplementation 'junit:junit:4.13.2'
|
||||
testImplementation 'org.robolectric:robolectric:4.16.1'
|
||||
testImplementation 'androidx.compose.ui:ui-test-junit4'
|
||||
// The Android archive does not include the host natives used by JVM archive tests.
|
||||
testRuntimeOnly 'com.github.luben:zstd-jni:1.5.2-3@jar'
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application>
|
||||
<!-- Debug builds only. Android grants DUMP to adb shell; release APKs have no bridge. -->
|
||||
<activity
|
||||
android:name=".agent.AgentStartActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:permission="android.permission.DUMP"
|
||||
android:theme="@style/SessionTheme" />
|
||||
<provider
|
||||
android:name=".agent.AgentBridgeProvider"
|
||||
android:authorities="${applicationId}.agent"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.DUMP"
|
||||
android:grantUriPermissions="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -1,166 +0,0 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.Manifest
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.Binder
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** A shell-only control surface, installed only by debug builds. */
|
||||
class AgentBridgeProvider : ContentProvider() {
|
||||
override fun onCreate(): Boolean {
|
||||
val appContext = context?.applicationContext ?: return false
|
||||
Thread({
|
||||
try {
|
||||
SessionArtifacts.finishAbandoned(appContext)
|
||||
} finally {
|
||||
recoveryComplete.countDown()
|
||||
}
|
||||
}, "agent-recover-artifacts").start()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
|
||||
val context = requireNotNull(context)
|
||||
if (Binder.getCallingUid() != Process.myUid() &&
|
||||
context.checkCallingPermission(Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
throw SecurityException("android.permission.DUMP is required")
|
||||
}
|
||||
|
||||
val response = try {
|
||||
when (method) {
|
||||
"state" -> state(context).put("ok", true)
|
||||
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
|
||||
"stop" -> stop(context)
|
||||
"resume" -> resume(context)
|
||||
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
error("COMMAND_FAILED", e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
return Bundle().apply { putString(RESULT_JSON, response.toString()) }
|
||||
}
|
||||
|
||||
private fun state(context: Context): JSONObject {
|
||||
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
|
||||
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: latestSessionDirectory()
|
||||
val session = JSONObject()
|
||||
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
|
||||
.put("phase", SessionState.phase.name)
|
||||
.put("running", SessionState.running)
|
||||
.put("mode", SessionState.mode)
|
||||
.put("program", SessionState.program ?: JSONObject.NULL)
|
||||
.put("steamUi", SessionState.steamUi ?: JSONObject.NULL)
|
||||
.put("steamUrl", SessionState.steamUrl ?: JSONObject.NULL)
|
||||
.put("suspended", SessionState.suspended)
|
||||
.put("firstFrame", SessionState.firstFrameSeen)
|
||||
.put("output", JSONArray().put(SessionState.outputSize.first).put(SessionState.outputSize.second))
|
||||
.put("refreshHz", SessionState.refreshHz.toDouble())
|
||||
.put("lastTransitionAt", SessionState.lastTransitionAt)
|
||||
.put("guestPid", SessionState.guestPid.takeIf { it > 1 } ?: JSONObject.NULL)
|
||||
.put("installing", SessionState.installing ?: JSONObject.NULL)
|
||||
.put("logDir", dir?.absolutePath ?: JSONObject.NULL)
|
||||
.put("eventsFile", dir?.let { File(it, "events.jsonl").absolutePath } ?: JSONObject.NULL)
|
||||
.put("artifactsAvailable", dir?.isDirectory ?: false)
|
||||
.put("artifactsComplete", dir?.let { File(it, ".complete").isFile } ?: false)
|
||||
|
||||
val failure = if (SessionState.failureCode == null) JSONObject.NULL else JSONObject()
|
||||
.put("code", SessionState.failureCode)
|
||||
.put("message", SessionState.failureMessage ?: JSONObject.NULL)
|
||||
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
|
||||
session.put("failure", failure)
|
||||
|
||||
return JSONObject()
|
||||
.put("schema", 1)
|
||||
.put("build", BuildConfig.BUILD_LABEL)
|
||||
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
.put("runtime", JSONObject()
|
||||
.put("installed", LinuxRuntime.isInstalled(context))
|
||||
.put("version", runtimeVersion ?: JSONObject.NULL))
|
||||
.put("session", session)
|
||||
}
|
||||
|
||||
private fun latestSessionDirectory(): File? {
|
||||
val parent = LinuxRuntime.debugLogDir()
|
||||
return parent.listFiles { file -> file.isDirectory && file.name.startsWith("session-") }
|
||||
?.maxWithOrNull(compareBy<File> { it.lastModified() }.thenBy { it.name })
|
||||
}
|
||||
|
||||
private fun stop(context: Context): JSONObject {
|
||||
if (SessionState.running) {
|
||||
SessionService.stop(context)
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
if (SessionState.phase == SessionPhase.STOPPING) {
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
if (SessionState.phase in STARTING_PHASES) {
|
||||
SessionState.stopRequested = true
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stop_requested")
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
return error("NO_ACTIVE_SESSION", "There is no session to stop")
|
||||
}
|
||||
|
||||
private fun resume(context: Context): JSONObject {
|
||||
if (!SessionState.running || !SessionState.suspended) {
|
||||
return error("SESSION_NOT_SUSPENDED", "There is no suspended session to resume")
|
||||
}
|
||||
SessionService.resume(context)
|
||||
return JSONObject().put("ok", true).put("command", "resume")
|
||||
}
|
||||
|
||||
private fun error(code: String, message: String) = JSONObject()
|
||||
.put("ok", false)
|
||||
.put("error", JSONObject().put("code", code).put("message", message))
|
||||
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
||||
override fun getType(uri: Uri): String? = null
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
|
||||
companion object {
|
||||
const val RESULT_JSON = "json"
|
||||
private val recoveryComplete = CountDownLatch(1)
|
||||
|
||||
fun awaitRecovery() {
|
||||
try {
|
||||
if (!recoveryComplete.await(90, TimeUnit.SECONDS)) {
|
||||
throw IllegalStateException("Session artifact recovery did not finish")
|
||||
}
|
||||
} catch (e: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
throw IllegalStateException("Interrupted while recovering session artifacts", e)
|
||||
}
|
||||
}
|
||||
|
||||
private val STARTING_PHASES = setOf(
|
||||
SessionPhase.PREPARING,
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
SessionPhase.STARTING_COMPOSITOR,
|
||||
SessionPhase.STARTING_GUEST,
|
||||
SessionPhase.STARTING_STEAM,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,17 @@
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<!-- Store download progress and "installed" / "failed" notices (Android 13+). -->
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<!-- The session keeps running while the app is not on screen: a foreground service holds the
|
||||
process at perceptible priority, and a high-performance WiFi lock keeps a backgrounded
|
||||
download from being throttled to nothing by the radio's power-save. -->
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<!-- Optional Wi-Fi discovery: requested only from Steam settings after an explanation. -->
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.VIBRATE" />
|
||||
<!-- Ends background processes of another app that holds the Steam login. GameHub starts
|
||||
itself with the phone via boot receivers and signs this client out seconds after every
|
||||
@@ -24,12 +30,16 @@
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<!-- Installs DroidDeck's own updates (Updates page) over itself, after the user allows it. -->
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<!-- A paired Steam Controller, read over Bluetooth LE out of lizard mode (SteamControllerBle).
|
||||
Granted at install below targetSdk 31; no scan, so no location. -->
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
|
||||
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
||||
<uses-feature android:name="android.hardware.gamepad" android:required="false" />
|
||||
|
||||
<application
|
||||
android:name=".App"
|
||||
android:localeConfig="@xml/locales_config"
|
||||
android:allowBackup="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
@@ -56,6 +66,20 @@
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="droiddeck" android:host="game" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.CREATE_SHORTCUT" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="com.droiddeck.launcher.LAUNCH_GAME" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- Android owns the Home key. This small translucent Home handler routes the resulting
|
||||
@@ -108,10 +132,26 @@
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<!-- A store's own sign-in page (GOG, Epic Games, Amazon Games) in a WebView. -->
|
||||
<activity
|
||||
android:name=".stores.StoreLoginActivity"
|
||||
android:exported="false"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".agent.AgentStartActivity"
|
||||
android:exported="true"
|
||||
android:excludeFromRecents="true"
|
||||
android:noHistory="true"
|
||||
android:permission="android.permission.DUMP"
|
||||
android:theme="@style/SessionTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".SessionActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTop"
|
||||
android:supportsPictureInPicture="true"
|
||||
android:launchMode="singleTask"
|
||||
android:theme="@style/SessionTheme"
|
||||
android:preferMinimalPostProcessing="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
@@ -135,6 +175,11 @@
|
||||
<service
|
||||
android:name=".core.WirelessAdbPairingService"
|
||||
android:exported="false" />
|
||||
<!-- Keeps the process alive while a store (GOG, Epic, Amazon) game downloads. -->
|
||||
<service
|
||||
android:name=".stores.download.StoreDownloadService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
<!-- Hands a zipped session folder to the share sheet; nothing else is exposed. -->
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
@@ -157,5 +202,11 @@
|
||||
<action android:name="android.content.action.DOCUMENTS_PROVIDER" />
|
||||
</intent-filter>
|
||||
</provider>
|
||||
<provider
|
||||
android:name=".agent.AgentBridgeProvider"
|
||||
android:authorities="${applicationId}.agent"
|
||||
android:exported="true"
|
||||
android:permission="android.permission.DUMP"
|
||||
android:grantUriPermissions="false" />
|
||||
</application>
|
||||
</manifest>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"archives": {
|
||||
"lxqt-r1": "c2bb860b3b1688287451e2495be5db313ec07f8c8af501dfac2768a9f417bc86",
|
||||
"desktop-kde-r1": "55747e75d0ec055ab7ea1e92a757f3be227cc3205bb9101f5b53cadef6318579",
|
||||
"desktop-kde-r2": "9ba832677b498654136c69d8c8330434d17e4d53cd099acac9bde3ba429b35bf",
|
||||
"emulators-r1": "a1f4806a9663d28f424b4cab1277e0ede80a92e69de5bc063cdc8b45af220164"
|
||||
},
|
||||
"desktopApplications": {
|
||||
"ark-26.08.1-1-aarch64.pkg.tar.xz": "93e2c2b75ff20cd29b4f312ed1979ef6f27255b93232b93bfcdb31239903c1d4",
|
||||
"breeze-6.7.5-1-aarch64.pkg.tar.xz": "1d7f4eb9d8d234caaea23621909f5233d19462c2f058afeeb54bed7b81bd03bd",
|
||||
"breeze-gtk-6.7.5-1-any.pkg.tar.xz": "a0f59bc4fc426879c8f8a97f6dcc707fb7d1b52913da5eb7e9db83777b6957b7",
|
||||
"breeze-icons-6.30.0-1-aarch64.pkg.tar.xz": "4bae4689032501156687a227024e56554820747644953c67fc8d2e2b6b0b045a",
|
||||
"dolphin-26.08.1-1-aarch64.pkg.tar.xz": "fef738ab8132d3eba1156b98c116699ce0a5efcb4cb462efbacdcf4c47f79a23",
|
||||
"firefox-157.0.1-1-aarch64.pkg.tar.xz": "d142fdb8a339a65eca7cea6a2bba5b29202386166abd9d59851d6757c9eb2163",
|
||||
"gwenview-26.08.1-1-aarch64.pkg.tar.xz": "a9dc7d5ab73fa677905d5a57248b1b9b404b6b16e862958cc7443d387f684a47",
|
||||
"kate-26.08.1-1-aarch64.pkg.tar.xz": "acf50710042746f243a3b219a1ae0f788e338f3dd9d75093e8bb671a618b83b6",
|
||||
"kde-cli-tools-6.7.5-1-aarch64.pkg.tar.xz": "af466398a912a994a97fadfe46aff401d88a90d7fdce7e843dc4218098fa38ac",
|
||||
"kde-gtk-config-6.7.5-1-aarch64.pkg.tar.xz": "ba6cb4cb01dbb3f2c247f2f6973ede3b64c0849f89340217b51dfbf11cb8cb5c",
|
||||
"kinfocenter-6.7.5-1-aarch64.pkg.tar.xz": "f3d5416db96b50f9a5b8a284d82ae21d834a8cce646010abdd7087491c399b0b",
|
||||
"konsole-26.08.1-1-aarch64.pkg.tar.xz": "1ecf87c0d11d620ebe4aeafb02788e0d5f4fe9019ad9c5d9f1011c43237dd5ec",
|
||||
"kscreen-6.7.5-1-aarch64.pkg.tar.xz": "8fbaa6fedf93edeba021a5416b551663654919b27c2ee237d696ec0b0ce7d5b7",
|
||||
"kwin-6.7.5-1-aarch64.pkg.tar.xz": "a7535710c74b90359f80306134b2b7581132cbac508dc84b7e07ef275cc8c3fe",
|
||||
"mpv-1:0.41.0-6-aarch64.pkg.tar.xz": "6c89d00736820210a3c7f32af4cf95d155191d463f9df8bd22137c45f30a554a",
|
||||
"plasma-desktop-6.7.5-1-aarch64.pkg.tar.xz": "b266dd42cea965b5ab1cc1ae600877e9d3bc83ec642c61fe1669c4457e641a55",
|
||||
"plasma-integration-6.7.5-1-aarch64.pkg.tar.xz": "daa96da14d9a4d12c0d9c0341e1be6836a9a437c469d61da5e9844d51e2606cf",
|
||||
"plasma-pa-6.7.5-1-aarch64.pkg.tar.xz": "02dbefe9d3e0069b2bb37cac2a6be18b8f0a1887c87704a0716e7a9268eadcd8",
|
||||
"plasma-workspace-6.7.5-1-aarch64.pkg.tar.xz": "3a1455857afaa9ccf342ab6167f0f15794ee9d248b0925398ea6f62f12730a86",
|
||||
"spectacle-1:6.7.5-1-aarch64.pkg.tar.xz": "0c9837412ea6119edef18bcb0a8fceb74634cb35be0ca78b3e1dd1ff2443866e",
|
||||
"systemsettings-6.7.5-1-aarch64.pkg.tar.xz": "b02b6a726857d5125c92d1ec95379216c7a3bc1f187a3b46e88c0d056b29ce70",
|
||||
"xdg-desktop-portal-kde-6.7.5-1-aarch64.pkg.tar.xz": "2c57d17d34d577023eb9cd7b0fca1ba9163549afe60450f6271aa148af099ef2"
|
||||
},
|
||||
"legacyApplications": {
|
||||
"featherpad-1.6.3-1-aarch64.pkg.tar.xz": "fcac55215815c0b712453f9bcc09abfe4b518e36025a111a7a7598ef04913f3d",
|
||||
"labwc-0.20.2-1-aarch64.pkg.tar.xz": "bcd4cc3945165b0fdd33c0117cd7b9dfd05cf8c327326c37f3c3a27ef23ee5ca",
|
||||
"lximage-qt-2.4.0-1-aarch64.pkg.tar.xz": "5d6bdd5472ea6bcb4b993b36df3ab7010bb2e62b36a78a649708fc9a52cb0928",
|
||||
"lxqt-config-2.4.0-1-aarch64.pkg.tar.xz": "4b601d798fc7689ee76787dbef8c8958c02429ee60248cd99d950c919dbefba5",
|
||||
"lxqt-panel-2.4.1-1-aarch64.pkg.tar.xz": "a141e0f8049e73f859d843510c6f45d6ed9087c990bcebf44f5f2430621024c4",
|
||||
"lxqt-qtplugin-2.4.0-3-aarch64.pkg.tar.xz": "61c8f828be73111ee0bd5e3163b0d64c2098dd0189710a190f42be11137695cf",
|
||||
"lxqt-runner-2.4.0-1-aarch64.pkg.tar.xz": "5afa74652a37366ea4e7774cf33379977582fbdca599cef1005ebf637cbcae4b",
|
||||
"lxqt-session-2.4.0-2-aarch64.pkg.tar.xz": "e9c7c8a0011859029622ad202e0d3826e4e5bc8d64659031f6efa211456ff6eb",
|
||||
"lxqt-themes-2.4.0-1-any.pkg.tar.xz": "7ea16c62a1fa70cdac13cb3f8fdcdaad299ae1f5bd514acfda671484755787bf",
|
||||
"lxqt-wayland-session-0.4.1-1-any.pkg.tar.xz": "cd8dc11f5035469d23b6bbd937a90593402428c43de37517412aa43fe1fc6b10",
|
||||
"papirus-icon-theme-20260801-1-any.pkg.tar.xz": "4aae3f47b800a60d6fd360e55adc581408ceaafc481c5a420a681741a3966510",
|
||||
"pcmanfm-qt-2.4.1-1-aarch64.pkg.tar.xz": "7ec1a6b39dd0e4055b39f0e2c0549ea263d83004e1b821fb9e42f1d7f5fff0f9",
|
||||
"qterminal-2.4.0-1-aarch64.pkg.tar.xz": "aa4adc9c9d47641b9452ec8d879038a9cb4762c3b6b5299045fac968fd0ed22d",
|
||||
"swaybg-1.2.2-1-aarch64.pkg.tar.xz": "a26caa16ca7d581b5ca05758677058b4b60af10dc8d83e447ad6824b762b48b8",
|
||||
"wlr-randr-0.5.0-1-aarch64.pkg.tar.xz": "58c3651c6a15dc8f95a310c7e225f759aa766be2fb3c0981a9a8b567854675b3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
desktop-kde-r1
|
||||
desktop-kde-r2
|
||||
@@ -1,115 +0,0 @@
|
||||
# DirectAudio for the Linux Steam client (relay build)
|
||||
|
||||
This is the driver for games that run under **Valve's ARM64 Proton inside a Linux
|
||||
runtime on Android** - Bannerlator's linuxfs session with the native Steam client -
|
||||
where the game process is a glibc process and cannot touch Android's audio
|
||||
libraries itself.
|
||||
|
||||
Two pieces, both required:
|
||||
|
||||
| piece | what it is | where it runs |
|
||||
|---|---|---|
|
||||
| `aarch64-unix/winedirectaudio.so` + the two PE shells | the Wine `mmdevapi` driver, glibc build, **no AAudio inside** | in the game, inside the Linux rootfs |
|
||||
| `directaudio-relay` | a small bionic program that owns the AAudio output and microphone streams | on the Android side, under the app's uid |
|
||||
|
||||
They meet over a unix socket. The driver connects, sends its launch config, and
|
||||
gets back two shared-memory rings: one it fills with mixed game audio, one the
|
||||
helper fills with microphone audio. The helper plays and records; the driver
|
||||
keeps doing everything else it always did.
|
||||
|
||||
## Which Proton
|
||||
|
||||
Built inside `ValveSoftware/wine` at `proton_11.0`. The private `mmdevapi`
|
||||
interface it implements is byte-identical across **Proton 11.0 (ARM64)**,
|
||||
**Proton Experimental (ARM64)** and our own Wine-11 layers (checked 2026-09-19),
|
||||
so this one build serves any of them. A future Proton on a Wine 12 base will
|
||||
need a rebuild - the interface is not versioned, and a mismatch is silence, not
|
||||
an error.
|
||||
|
||||
## Installing the driver next to Proton (not into it)
|
||||
|
||||
Steam verifies and updates its Proton depots, so files added under
|
||||
`steamapps/common/Proton .../files/lib/wine/` will not survive. Put the driver
|
||||
in a directory of its own and point Wine at it:
|
||||
|
||||
```
|
||||
<somewhere>/directaudio/lib/wine/aarch64-unix/winedirectaudio.so
|
||||
<somewhere>/directaudio/lib/wine/aarch64-windows/winedirectaudio.drv
|
||||
<somewhere>/directaudio/lib/wine/i386-windows/winedirectaudio.drv
|
||||
```
|
||||
|
||||
and set, for the game process:
|
||||
|
||||
```
|
||||
WINEDLLPATH=<somewhere>/directaudio/lib/wine
|
||||
```
|
||||
|
||||
Wine searches `WINEDLLPATH` entries with the per-arch subdirectories appended,
|
||||
so both the PE shell and the unixlib are found there. In Bannerlator's runtime
|
||||
the natural place to export it is the `bannerlator-proton` compatibility-tool
|
||||
wrapper, which every Proton launch goes through.
|
||||
|
||||
## Selecting the driver
|
||||
|
||||
`mmdevapi` only tries the drivers named in the registry (or its built-in
|
||||
`pulse,alsa,oss,coreaudio` list, which does not know about this one). Set, in the
|
||||
game's prefix:
|
||||
|
||||
```
|
||||
wine reg add "HKCU\Software\Wine\Drivers" /v Audio /d directaudio /f
|
||||
```
|
||||
|
||||
Under Proton the prefix is `compatdata/<appid>/pfx`; run the command with that
|
||||
prefix as `WINEPREFIX` using Proton's own `bin-arm64/wine`, or write the key from
|
||||
the wrapper before it hands off to Proton.
|
||||
|
||||
## Running the helper
|
||||
|
||||
```
|
||||
directaudio-relay --socket <path> [--log]
|
||||
```
|
||||
|
||||
- Run it **under the app's uid**, the way the app already runs its PulseAudio
|
||||
daemon. Android checks `RECORD_AUDIO` against the calling uid, so a helper
|
||||
started any other way can play but cannot record.
|
||||
- Start it **before** the game: the driver asks "is a helper there?" once, when
|
||||
Wine picks an audio driver, and falls back to unavailable if not.
|
||||
- The socket path must be reachable from inside the Linux rootfs. Bannerlator
|
||||
binds the app's files directory and its runtime directory into the session at
|
||||
their own paths, so any socket under either works unchanged on both sides.
|
||||
- The helper serves any number of game processes; each gets its own streams.
|
||||
It exits on `SIGTERM`; a game exiting tears down that game's streams only.
|
||||
|
||||
## Telling the driver where the helper is
|
||||
|
||||
```
|
||||
BANNER_AUDIO_DIRECT_RELAY=<the same socket path>
|
||||
```
|
||||
|
||||
Unset, the driver looks for `$XDG_RUNTIME_DIR/directaudio-relay`.
|
||||
|
||||
## Everything else is unchanged
|
||||
|
||||
All `BANNER_AUDIO_DIRECT_*` knobs mean what they mean in the in-process build:
|
||||
`_PERF`, `_ADAPTIVE`, `_DECAY`, `_MS`, `_MAXMS`, `_BF`, `_MBF`, `_EXCLUSIVE`,
|
||||
`_WATCHDOG`, `_STALL_MS`, `_DECAY_*`, `_LOG`, `_PERIOD_MS`, `_MINPERIOD_MS`, and
|
||||
the live-config mailbox `_RUNTIME` (the helper watches the file; it must be a
|
||||
path the helper can read on the Android side). **`BANNER_AUDIO_DIRECT_MIC=1`**
|
||||
exposes the capture endpoint exactly as before: the helper opens the input
|
||||
stream (`VOICE_COMMUNICATION` preset) when the game connects and makes it hot on
|
||||
the game's first capture start.
|
||||
|
||||
One thing is different: there is one extra hand-off, the ring. The helper's
|
||||
callback pulls a burst from it, so the driver keeps two bursts queued (about 8 ms
|
||||
on a 192-frame device) on top of the AAudio buffer the presets control, and the
|
||||
helper raises that if a callback ever finds the ring short. `get_latency` reports
|
||||
the sum, so a game that sizes its own buffers from it still sees the truth.
|
||||
|
||||
## Proving it is running
|
||||
|
||||
- Helper side: `logcat -s DA-Relay:I` shows `hello from <exe>`, then `open: buffer
|
||||
... ring target ...`, then `capture open` / `capture start` for the mic.
|
||||
- Game side: the session log carries `DirectAudio: relay: connected - ...`.
|
||||
- The game process's `/proc/<pid>/maps` shows `winedirectaudio.so` and **no**
|
||||
`libaaudio.so` (it is in the helper's maps instead). The AudioFlinger track is
|
||||
owned by the helper's pid.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,4 +0,0 @@
|
||||
directaudio linux-wine11 relay build
|
||||
source 3548a4a730e8d01cb0cb0268d51a2fb8f23dcd33
|
||||
wine ValveSoftware/wine@proton_11.0
|
||||
unixlib.h sha256 fdbed263338d0719c4d12e02b045c23721de33219ec8878e4c2d7ebc9efcbe09
|
||||
@@ -44,6 +44,11 @@ add_subdirectory(waylandcomp)
|
||||
add_library(sdnative SHARED sdnative/sdnative.c)
|
||||
target_link_libraries(sdnative log)
|
||||
|
||||
# The device info window's Vulkan section: the phone's own driver, asked once through the system
|
||||
# loader (opened with dlopen, so a phone without Vulkan still loads the app).
|
||||
add_library(deviceinfo SHARED deviceinfo/vkinfo.c)
|
||||
target_link_libraries(deviceinfo dl)
|
||||
|
||||
# Rebuild Termux terminal-emulator's PTY JNI helper with the app's NDK instead of carrying its
|
||||
# prebuilt libtermux.so with a redundant libstdc++.so dependency.
|
||||
add_library(termux SHARED termux/termux.c)
|
||||
@@ -0,0 +1,112 @@
|
||||
// What the phone's own Vulkan driver says about its GPU, for the app's device info window: one
|
||||
// instance on the system loader, the first physical device's properties, a few limits and the
|
||||
// extensions DXVK and VKD3D-Proton lean on. Returned as "key=value" lines; nothing is kept open.
|
||||
#include <dlfcn.h>
|
||||
#include <jni.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#define VK_NO_PROTOTYPES
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
#define LINE(...) do { if (used < sizeof(out)) used += snprintf(out + used, sizeof(out) - used, __VA_ARGS__); } while (0)
|
||||
|
||||
static const char *const EXTENSIONS[] = {
|
||||
"VK_EXT_robustness2", "VK_EXT_transform_feedback", "VK_EXT_custom_border_color",
|
||||
"VK_KHR_dynamic_rendering", "VK_EXT_extended_dynamic_state3", "VK_EXT_descriptor_indexing",
|
||||
"VK_KHR_timeline_semaphore", "VK_EXT_mesh_shader", "VK_KHR_ray_query",
|
||||
};
|
||||
|
||||
static const char *type_name(VkPhysicalDeviceType type) {
|
||||
switch (type) {
|
||||
case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU: return "integrated GPU";
|
||||
case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU: return "discrete GPU";
|
||||
case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU: return "virtual GPU";
|
||||
case VK_PHYSICAL_DEVICE_TYPE_CPU: return "CPU";
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL
|
||||
Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz) {
|
||||
static char out[4096];
|
||||
size_t used = 0;
|
||||
out[0] = 0;
|
||||
void *lib = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!lib) { LINE("error=no Vulkan loader\n"); return (*env)->NewStringUTF(env, out); }
|
||||
PFN_vkGetInstanceProcAddr gipa = (PFN_vkGetInstanceProcAddr) dlsym(lib, "vkGetInstanceProcAddr");
|
||||
PFN_vkCreateInstance create = gipa ? (PFN_vkCreateInstance) gipa(NULL, "vkCreateInstance") : NULL;
|
||||
PFN_vkEnumerateInstanceVersion instanceVersion = gipa ? (PFN_vkEnumerateInstanceVersion) gipa(NULL, "vkEnumerateInstanceVersion") : NULL;
|
||||
if (!create) { LINE("error=no vkCreateInstance\n"); dlclose(lib); return (*env)->NewStringUTF(env, out); }
|
||||
uint32_t loader = VK_API_VERSION_1_0;
|
||||
if (instanceVersion) instanceVersion(&loader);
|
||||
LINE("loader=%u.%u.%u\n", VK_API_VERSION_MAJOR(loader), VK_API_VERSION_MINOR(loader), VK_API_VERSION_PATCH(loader));
|
||||
|
||||
VkApplicationInfo app = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "DroidDeck device info",
|
||||
.apiVersion = loader >= VK_API_VERSION_1_1 ? VK_API_VERSION_1_1 : VK_API_VERSION_1_0 };
|
||||
VkInstanceCreateInfo info = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &app };
|
||||
VkInstance instance = VK_NULL_HANDLE;
|
||||
if (create(&info, NULL, &instance) != VK_SUCCESS) { LINE("error=vkCreateInstance failed\n"); dlclose(lib); return (*env)->NewStringUTF(env, out); }
|
||||
|
||||
#define GET(name) PFN_##name name = (PFN_##name) gipa(instance, #name)
|
||||
GET(vkDestroyInstance); GET(vkEnumeratePhysicalDevices); GET(vkGetPhysicalDeviceProperties);
|
||||
GET(vkGetPhysicalDeviceProperties2); GET(vkGetPhysicalDeviceMemoryProperties);
|
||||
GET(vkEnumerateDeviceExtensionProperties); GET(vkGetPhysicalDeviceFeatures);
|
||||
uint32_t count = 1;
|
||||
VkPhysicalDevice device = VK_NULL_HANDLE;
|
||||
VkResult listed = vkEnumeratePhysicalDevices ? vkEnumeratePhysicalDevices(instance, &count, &device) : VK_ERROR_INITIALIZATION_FAILED;
|
||||
if ((listed != VK_SUCCESS && listed != VK_INCOMPLETE) || count == 0 || !device || !vkGetPhysicalDeviceProperties) {
|
||||
LINE("error=no Vulkan device\n");
|
||||
} else {
|
||||
VkPhysicalDeviceProperties p;
|
||||
vkGetPhysicalDeviceProperties(device, &p);
|
||||
LINE("device=%s\n", p.deviceName);
|
||||
LINE("type=%s\n", type_name(p.deviceType));
|
||||
LINE("api=%u.%u.%u\n", VK_API_VERSION_MAJOR(p.apiVersion), VK_API_VERSION_MINOR(p.apiVersion), VK_API_VERSION_PATCH(p.apiVersion));
|
||||
// Qualcomm packs its driver version as 10.10.12 bits, the same layout as VK_MAKE_VERSION.
|
||||
LINE("driver_version=%u.%u.%u\n", p.driverVersion >> 22, (p.driverVersion >> 12) & 0x3ff, p.driverVersion & 0xfff);
|
||||
LINE("vendor_id=0x%04x\ndevice_id=0x%08x\n", p.vendorID, p.deviceID);
|
||||
LINE("max_image_2d=%u\n", p.limits.maxImageDimension2D);
|
||||
|
||||
// Driver name and build string (Vulkan 1.2 or VK_KHR_driver_properties).
|
||||
uint32_t extCount = 0;
|
||||
if (vkEnumerateDeviceExtensionProperties) vkEnumerateDeviceExtensionProperties(device, NULL, &extCount, NULL);
|
||||
static VkExtensionProperties exts[512];
|
||||
if (extCount > 512) extCount = 512;
|
||||
if (extCount && vkEnumerateDeviceExtensionProperties) vkEnumerateDeviceExtensionProperties(device, NULL, &extCount, exts);
|
||||
int driverProps = p.apiVersion >= VK_API_VERSION_1_2;
|
||||
for (uint32_t i = 0; i < extCount; i++)
|
||||
if (!strcmp(exts[i].extensionName, "VK_KHR_driver_properties")) driverProps = 1;
|
||||
if (driverProps && vkGetPhysicalDeviceProperties2) {
|
||||
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_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("extension_count=%u\n", extCount);
|
||||
for (size_t e = 0; e < sizeof(EXTENSIONS) / sizeof(*EXTENSIONS); e++) {
|
||||
int has = 0;
|
||||
for (uint32_t i = 0; i < extCount && !has; i++) has = !strcmp(exts[i].extensionName, EXTENSIONS[e]);
|
||||
LINE("ext.%s=%s\n", EXTENSIONS[e], has ? "yes" : "no");
|
||||
}
|
||||
if (vkGetPhysicalDeviceFeatures) {
|
||||
VkPhysicalDeviceFeatures f;
|
||||
vkGetPhysicalDeviceFeatures(device, &f);
|
||||
LINE("geometry_shader=%s\ntessellation_shader=%s\ntexture_bc=%s\n",
|
||||
f.geometryShader ? "yes" : "no", f.tessellationShader ? "yes" : "no", f.textureCompressionBC ? "yes" : "no");
|
||||
}
|
||||
if (vkGetPhysicalDeviceMemoryProperties) {
|
||||
VkPhysicalDeviceMemoryProperties m;
|
||||
vkGetPhysicalDeviceMemoryProperties(device, &m);
|
||||
VkDeviceSize largest = 0;
|
||||
for (uint32_t i = 0; i < m.memoryHeapCount; i++)
|
||||
if ((m.memoryHeaps[i].flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) && m.memoryHeaps[i].size > largest) largest = m.memoryHeaps[i].size;
|
||||
LINE("device_heap_mb=%llu\n", (unsigned long long) (largest >> 20));
|
||||
}
|
||||
}
|
||||
if (vkDestroyInstance) vkDestroyInstance(instance, NULL);
|
||||
dlclose(lib);
|
||||
return (*env)->NewStringUTF(env, out);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -136,6 +136,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
|
||||
if (!arg_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for argv");
|
||||
argv[i] = strdup(arg_utf8);
|
||||
(*env)->ReleaseStringUTFChars(env, arg_java_string, arg_utf8);
|
||||
(*env)->DeleteLocalRef(env, arg_java_string);
|
||||
}
|
||||
argv[size] = NULL;
|
||||
}
|
||||
@@ -151,6 +152,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
|
||||
if (!env_utf8) return throw_runtime_exception(env, "GetStringUTFChars() failed for env");
|
||||
envp[i] = strdup(env_utf8);
|
||||
(*env)->ReleaseStringUTFChars(env, env_java_string, env_utf8);
|
||||
(*env)->DeleteLocalRef(env, env_java_string);
|
||||
}
|
||||
envp[size] = NULL;
|
||||
}
|
||||
@@ -160,7 +162,7 @@ JNIEXPORT jint JNICALL Java_com_termux_terminal_JNI_createSubprocess(
|
||||
char const* cmd_utf8 = (*env)->GetStringUTFChars(env, cmd, NULL);
|
||||
int ptm = create_subprocess(env, cmd_utf8, cmd_cwd, argv, envp, &procId, rows, columns);
|
||||
(*env)->ReleaseStringUTFChars(env, cmd, cmd_utf8);
|
||||
(*env)->ReleaseStringUTFChars(env, cmd, cmd_cwd);
|
||||
(*env)->ReleaseStringUTFChars(env, cwd, cmd_cwd);
|
||||
|
||||
if (argv) {
|
||||
for (char** tmp = argv; *tmp; ++tmp) free(*tmp);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,194 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* The command buffers each device has handed out, so that a handle the driver never gave (or has
|
||||
* since freed, with its pool) is refused here instead of reaching the driver. Handles arrive from
|
||||
* clients as plain numbers; one the driver did not know took the whole app down inside Mali's
|
||||
* vkBeginCommandBuffer (SIGSEGV at 0x10, Steam's Zink on an Edge 60 and a Tab S11). A refused
|
||||
* command buffer fails its call with VK_ERROR_DEVICE_LOST, which the client reports, and is logged
|
||||
* once per handle.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define CBT_BUCKETS 1024
|
||||
|
||||
typedef struct cbt_entry {
|
||||
VkCommandBuffer cb;
|
||||
VkCommandPool pool;
|
||||
struct cbt_entry *next;
|
||||
} cbt_entry;
|
||||
|
||||
typedef struct vkb_cbtrack {
|
||||
pthread_mutex_t lock;
|
||||
cbt_entry *b[CBT_BUCKETS];
|
||||
VkCommandBuffer last_refused;
|
||||
PFN_vkAllocateCommandBuffers alloc;
|
||||
PFN_vkFreeCommandBuffers free_cbs;
|
||||
PFN_vkDestroyCommandPool destroy_pool;
|
||||
PFN_vkBeginCommandBuffer begin;
|
||||
PFN_vkQueueSubmit submit;
|
||||
PFN_vkQueueSubmit2 submit2;
|
||||
} vkb_cbtrack;
|
||||
|
||||
static unsigned bucket(VkCommandBuffer cb)
|
||||
{
|
||||
uint64_t k = (uint64_t)(uintptr_t)cb;
|
||||
k ^= k >> 31;
|
||||
k *= 0x9e3779b97f4a7c15ull;
|
||||
return (unsigned)(k >> 54) & (CBT_BUCKETS - 1);
|
||||
}
|
||||
|
||||
static vkb_cbtrack *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->cbtrack : NULL;
|
||||
}
|
||||
|
||||
static int known_locked(vkb_cbtrack *k, VkCommandBuffer cb)
|
||||
{
|
||||
for (cbt_entry *e = k->b[bucket(cb)]; e; e = e->next)
|
||||
if (e->cb == cb) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int vkb_cbtrack_known(vkb_srv_table *t, VkCommandBuffer cb, const char *what)
|
||||
{
|
||||
vkb_cbtrack *k = t ? t->cbtrack : NULL;
|
||||
if (!k) return cb != VK_NULL_HANDLE;
|
||||
pthread_mutex_lock(&k->lock);
|
||||
int ok = cb && known_locked(k, cb);
|
||||
int first = !ok && k->last_refused != cb;
|
||||
if (!ok) k->last_refused = cb;
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
if (first)
|
||||
VKB_ERR("device %u: %s on command buffer %p, which this device never allocated or has freed; refused (the client "
|
||||
"gets VK_ERROR_DEVICE_LOST)", t->id, what, (void *)cb);
|
||||
return ok;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_AllocateCommandBuffers(VkDevice device, const VkCommandBufferAllocateInfo *info,
|
||||
VkCommandBuffer *out)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
VkResult r = k->alloc(device, info, out);
|
||||
if (r != VK_SUCCESS || !info) return r;
|
||||
pthread_mutex_lock(&k->lock);
|
||||
for (uint32_t i = 0; i < info->commandBufferCount; i++) {
|
||||
if (!out[i] || known_locked(k, out[i])) continue;
|
||||
cbt_entry *e = malloc(sizeof(*e));
|
||||
if (!e) continue;
|
||||
e->cb = out[i];
|
||||
e->pool = info->commandPool;
|
||||
unsigned h = bucket(out[i]);
|
||||
e->next = k->b[h];
|
||||
k->b[h] = e;
|
||||
}
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void forget_locked(vkb_cbtrack *k, VkCommandBuffer cb, VkCommandPool pool)
|
||||
{
|
||||
for (unsigned h = cb ? bucket(cb) : 0; h < CBT_BUCKETS; h = cb ? CBT_BUCKETS : h + 1) {
|
||||
cbt_entry **pp = &k->b[h];
|
||||
while (*pp) {
|
||||
cbt_entry *e = *pp;
|
||||
if ((cb && e->cb == cb) || (!cb && e->pool == pool)) {
|
||||
*pp = e->next;
|
||||
free(e);
|
||||
} else {
|
||||
pp = &e->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cbt_FreeCommandBuffers(VkDevice device, VkCommandPool pool, uint32_t n, const VkCommandBuffer *cbs)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
pthread_mutex_lock(&k->lock);
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (cbs[i]) forget_locked(k, cbs[i], pool);
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
k->free_cbs(device, pool, n, cbs);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL cbt_DestroyCommandPool(VkDevice device, VkCommandPool pool, const VkAllocationCallbacks *a)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
if (pool) {
|
||||
pthread_mutex_lock(&k->lock);
|
||||
forget_locked(k, VK_NULL_HANDLE, pool);
|
||||
pthread_mutex_unlock(&k->lock);
|
||||
}
|
||||
k->destroy_pool(device, pool, a);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_BeginCommandBuffer(VkCommandBuffer cb, const VkCommandBufferBeginInfo *info)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
if (!vkb_cbtrack_known(vkb_srv_current_table(), cb, "vkBeginCommandBuffer")) return VK_ERROR_DEVICE_LOST;
|
||||
return k->begin(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_QueueSubmit(VkQueue queue, uint32_t n, const VkSubmitInfo *s, VkFence fence)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
for (uint32_t j = 0; j < s[i].commandBufferCount; j++)
|
||||
if (!vkb_cbtrack_known(t, s[i].pCommandBuffers[j], "vkQueueSubmit")) return VK_ERROR_DEVICE_LOST;
|
||||
return k->submit(queue, n, s, fence);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL cbt_QueueSubmit2(VkQueue queue, uint32_t n, const VkSubmitInfo2 *s, VkFence fence)
|
||||
{
|
||||
vkb_cbtrack *k = cur();
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
for (uint32_t j = 0; j < s[i].commandBufferInfoCount; j++)
|
||||
if (!vkb_cbtrack_known(t, s[i].pCommandBufferInfos[j].commandBuffer, "vkQueueSubmit2")) return VK_ERROR_DEVICE_LOST;
|
||||
return k->submit2(queue, n, s, fence);
|
||||
}
|
||||
|
||||
void vkb_cbtrack_device_init(vkb_srv_table *t)
|
||||
{
|
||||
if (!t->dt.vkAllocateCommandBuffers || !t->dt.vkFreeCommandBuffers || !t->dt.vkDestroyCommandPool || !t->dt.vkBeginCommandBuffer ||
|
||||
!t->dt.vkQueueSubmit)
|
||||
return;
|
||||
vkb_cbtrack *k = calloc(1, sizeof(*k));
|
||||
if (!k) return;
|
||||
pthread_mutex_init(&k->lock, NULL);
|
||||
k->alloc = t->dt.vkAllocateCommandBuffers;
|
||||
k->free_cbs = t->dt.vkFreeCommandBuffers;
|
||||
k->destroy_pool = t->dt.vkDestroyCommandPool;
|
||||
k->begin = t->dt.vkBeginCommandBuffer;
|
||||
k->submit = t->dt.vkQueueSubmit;
|
||||
k->submit2 = t->dt.vkQueueSubmit2;
|
||||
t->cbtrack = k;
|
||||
t->dt.vkAllocateCommandBuffers = cbt_AllocateCommandBuffers;
|
||||
t->dt.vkFreeCommandBuffers = cbt_FreeCommandBuffers;
|
||||
t->dt.vkDestroyCommandPool = cbt_DestroyCommandPool;
|
||||
t->dt.vkBeginCommandBuffer = cbt_BeginCommandBuffer;
|
||||
t->dt.vkQueueSubmit = cbt_QueueSubmit;
|
||||
if (k->submit2) t->dt.vkQueueSubmit2 = cbt_QueueSubmit2;
|
||||
}
|
||||
|
||||
void vkb_cbtrack_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_cbtrack *k = t->cbtrack;
|
||||
if (!k) return;
|
||||
for (unsigned h = 0; h < CBT_BUCKETS; h++) {
|
||||
while (k->b[h]) {
|
||||
cbt_entry *e = k->b[h];
|
||||
k->b[h] = e->next;
|
||||
free(e);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&k->lock);
|
||||
free(k);
|
||||
t->cbtrack = NULL;
|
||||
}
|
||||
@@ -0,0 +1,608 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Connections: one thread per client thread, requests executed in order, replies sent back.
|
||||
* A command buffer's recorded commands arrive in one message at vkEndCommandBuffer and are
|
||||
* replayed here.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <setjmp.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static pthread_mutex_t tables_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static vkb_srv_table *tables[VKB_MAX_TABLES];
|
||||
static uint32_t next_table_id = 1;
|
||||
|
||||
static pthread_mutex_t procs_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static vkb_srv_proc *procs;
|
||||
|
||||
static __thread vkb_srv_table *tls_table;
|
||||
__thread const char *vkb_srv_current_cmd;
|
||||
|
||||
vkb_srv_table *vkb_srv_current_table(void) { return tls_table; }
|
||||
void vkb_srv_set_current_table(vkb_srv_table *t) { tls_table = t; }
|
||||
|
||||
/* Server side of the generated encoders' helpers: handles are already the server's values. */
|
||||
uint64_t vkb_remote(const void *h) { return (uint64_t)(uintptr_t)h; }
|
||||
int vkb_cb_begin_is_secondary(const VkCommandBufferBeginInfo *s) { (void)s; return 1; }
|
||||
|
||||
uint32_t vkb_table_register(vkb_srv_table *t)
|
||||
{
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
uint32_t id = 0;
|
||||
for (uint32_t tries = 0; tries < VKB_MAX_TABLES; tries++) {
|
||||
uint32_t cand = next_table_id++;
|
||||
if (next_table_id >= VKB_MAX_TABLES) next_table_id = 1;
|
||||
if (!tables[cand]) {
|
||||
id = cand;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (id) {
|
||||
t->id = id;
|
||||
tables[id] = t;
|
||||
}
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
return id;
|
||||
}
|
||||
|
||||
void vkb_table_unregister(vkb_srv_table *t)
|
||||
{
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
if (t->id && t->id < VKB_MAX_TABLES && tables[t->id] == t) tables[t->id] = NULL;
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
}
|
||||
|
||||
vkb_srv_table *vkb_table_get(uint32_t id)
|
||||
{
|
||||
if (!id || id >= VKB_MAX_TABLES) return NULL;
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
vkb_srv_table *t = tables[id];
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
return t;
|
||||
}
|
||||
|
||||
void vkb_srv_reply_status(vkb_srv_call *c, uint32_t status)
|
||||
{
|
||||
c->status = status;
|
||||
}
|
||||
|
||||
void vkb_srv_bad_message(vkb_srv_call *c)
|
||||
{
|
||||
VKB_ERR("malformed request");
|
||||
c->status = VKB_ST_BAD_MESSAGE;
|
||||
}
|
||||
|
||||
void vkb_srv_missing(vkb_srv_call *c, const char *name)
|
||||
{
|
||||
VKB_ERR("the driver has no %s", name);
|
||||
c->status = VKB_ST_MISSING;
|
||||
}
|
||||
|
||||
void vkb_srv_close_after_send(vkb_srv_call *c, int fd)
|
||||
{
|
||||
if (c->nclose < VKB_MAX_FDS) c->close_after[c->nclose++] = fd;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ process cleanup */
|
||||
|
||||
void vkb_proc_cleanup(vkb_srv_proc *p)
|
||||
{
|
||||
/* Devices first, then their instances. */
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
for (uint32_t i = 1; i < VKB_MAX_TABLES; i++) {
|
||||
pthread_mutex_lock(&tables_lock);
|
||||
vkb_srv_table *t = tables[i];
|
||||
int mine = t && t->proc == p && t->is_device == (pass == 0);
|
||||
if (mine) tables[i] = NULL;
|
||||
pthread_mutex_unlock(&tables_lock);
|
||||
if (!mine) continue;
|
||||
if (p->driver_crashed) {
|
||||
/* The driver faulted for this process: calling into it for its objects again could
|
||||
* fault again, outside any guard. They are left to the driver. */
|
||||
VKB_WARN("process %d: %s %u left as it is (the driver crashed serving it)", p->pid, t->is_device ? "device" : "instance", t->id);
|
||||
if (t->is_device) vkb_cbtrack_device_destroy(t);
|
||||
} else if (t->is_device) {
|
||||
VKB_INFO("process %d exited without destroying device %u; cleaning up", p->pid, t->id);
|
||||
vkb_cbtrack_device_destroy(t);
|
||||
if (t->real.vkDeviceWaitIdle) t->real.vkDeviceWaitIdle(t->device);
|
||||
vkb_spvfix_device_destroy(t);
|
||||
vkb_dsmap_device_destroy(t);
|
||||
vkb_pcache_device_destroy(t);
|
||||
vkb_emu_device_destroy(t);
|
||||
vkb_mem_free_all(t);
|
||||
t->real.vkDestroyDevice(t->device, NULL);
|
||||
} else {
|
||||
VKB_INFO("process %d exited without destroying instance %u; cleaning up", p->pid, t->id);
|
||||
t->real.vkDestroyInstance(t->instance, NULL);
|
||||
}
|
||||
pthread_mutex_destroy(&t->lock);
|
||||
free(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static vkb_srv_proc *proc_join(uint64_t token, int pid)
|
||||
{
|
||||
pthread_mutex_lock(&procs_lock);
|
||||
vkb_srv_proc *p = procs;
|
||||
while (p && p->token != token) p = p->next;
|
||||
if (!p) {
|
||||
p = calloc(1, sizeof(*p));
|
||||
p->token = token;
|
||||
p->pid = pid;
|
||||
pthread_mutex_init(&p->olock, NULL);
|
||||
pthread_cond_init(&p->ocond, NULL);
|
||||
p->next = procs;
|
||||
procs = p;
|
||||
VKB_INFO("client process %d connected", pid);
|
||||
}
|
||||
p->conns++;
|
||||
pthread_mutex_unlock(&procs_lock);
|
||||
return p;
|
||||
}
|
||||
|
||||
static void proc_leave(vkb_srv_proc *p)
|
||||
{
|
||||
pthread_mutex_lock(&procs_lock);
|
||||
int last = --p->conns == 0;
|
||||
if (last) {
|
||||
vkb_srv_proc **pp = &procs;
|
||||
while (*pp && *pp != p) pp = &(*pp)->next;
|
||||
if (*pp) *pp = p->next;
|
||||
}
|
||||
pthread_mutex_unlock(&procs_lock);
|
||||
if (last) {
|
||||
vkb_proc_cleanup(p);
|
||||
VKB_INFO("client process %d gone", p->pid);
|
||||
pthread_mutex_destroy(&p->olock);
|
||||
pthread_cond_destroy(&p->ocond);
|
||||
free(p);
|
||||
} else {
|
||||
pthread_mutex_lock(&p->olock);
|
||||
p->conn_closed = 1;
|
||||
pthread_cond_broadcast(&p->ocond);
|
||||
pthread_mutex_unlock(&p->olock);
|
||||
}
|
||||
}
|
||||
|
||||
/* Waits until every async request of the process up to `barrier` has run. */
|
||||
static void order_wait(vkb_srv_proc *p, uint64_t barrier)
|
||||
{
|
||||
if (!p || !barrier) return;
|
||||
pthread_mutex_lock(&p->olock);
|
||||
int waited = 0;
|
||||
while (p->watermark < barrier) {
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
ts.tv_sec += 1;
|
||||
if (pthread_cond_timedwait(&p->ocond, &p->olock, &ts) != 0 && ++waited >= 3 && p->conn_closed) {
|
||||
/* A connection of this process is gone with requests it never sent: go on. */
|
||||
VKB_WARN("process %d: async request %llu never arrived; continuing", p->pid, (unsigned long long)(p->watermark + 1));
|
||||
p->watermark = barrier;
|
||||
memset(p->done, 0, sizeof(p->done));
|
||||
break;
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&p->olock);
|
||||
}
|
||||
|
||||
static void order_done(vkb_srv_proc *p, uint64_t seq)
|
||||
{
|
||||
if (!p || !seq) return;
|
||||
pthread_mutex_lock(&p->olock);
|
||||
if (seq > p->watermark) {
|
||||
p->done[seq % VKB_SEQ_RING] = 1;
|
||||
while (p->done[(p->watermark + 1) % VKB_SEQ_RING]) {
|
||||
p->done[(p->watermark + 1) % VKB_SEQ_RING] = 0;
|
||||
p->watermark++;
|
||||
}
|
||||
pthread_cond_broadcast(&p->ocond);
|
||||
}
|
||||
pthread_mutex_unlock(&p->olock);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ command buffer replay */
|
||||
|
||||
static int is_stream_cmd(uint32_t id)
|
||||
{
|
||||
const char *n = vkb_cmd_names[id];
|
||||
return !strncmp(n, "vkCmd", 5) || id == VKB_CMD_vkBeginCommandBuffer || id == VKB_CMD_vkbPushDescRaw;
|
||||
}
|
||||
|
||||
void vkb_sv_vkEndCommandBuffer(vkb_srv_call *c)
|
||||
{
|
||||
VkCommandBuffer cb = (VkCommandBuffer)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
size_t len = 0;
|
||||
const uint8_t *s = vkb_dec_blob(&c->d, &len);
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
/* A command buffer the device never handed out (or has freed) is not replayed: the driver would
|
||||
* be given a pointer it does not own (server_cbtrack.c). */
|
||||
if (!vkb_cbtrack_known(c->table, cb, "vkEndCommandBuffer")) {
|
||||
vkb_enc_u32(&c->r, (uint32_t)VK_ERROR_DEVICE_LOST);
|
||||
return;
|
||||
}
|
||||
VkResult begin_r = VK_SUCCESS;
|
||||
size_t pos = 0;
|
||||
vkb_enc scratch;
|
||||
vkb_enc_init(&scratch);
|
||||
uint32_t ncmds = 0;
|
||||
while (s && pos + 8 <= len) {
|
||||
uint32_t id, n;
|
||||
memcpy(&id, s + pos, 4);
|
||||
memcpy(&n, s + pos + 4, 4);
|
||||
pos += 8;
|
||||
if (id >= VKB_CMD_COUNT || !is_stream_cmd(id) || n > len - pos) {
|
||||
VKB_ERR("command stream: bad entry (id %u, %u bytes) after %u commands", id, n, ncmds);
|
||||
c->status = VKB_ST_BAD_MESSAGE;
|
||||
vkb_enc_free(&scratch);
|
||||
return;
|
||||
}
|
||||
vkb_srv_call sub;
|
||||
memset(&sub, 0, sizeof(sub));
|
||||
vkb_dec_init(&sub.d, s + pos, n, c->d.arena, NULL, 0);
|
||||
sub.r = scratch;
|
||||
vkb_enc_reset(&sub.r);
|
||||
sub.dt = c->dt;
|
||||
sub.table = c->table;
|
||||
sub.conn = c->conn;
|
||||
sub.in_stream = 1;
|
||||
vkb_srv_current_cmd = vkb_cmd_names[id];
|
||||
vkb_srv_handlers[id](&sub);
|
||||
vkb_srv_current_cmd = vkb_cmd_names[VKB_CMD_vkEndCommandBuffer];
|
||||
scratch = sub.r;
|
||||
if (sub.status != VKB_ST_OK) {
|
||||
VKB_ERR("command stream: %s failed (status %u)", vkb_cmd_names[id], sub.status);
|
||||
}
|
||||
if (id == VKB_CMD_vkBeginCommandBuffer && scratch.len >= 4) memcpy(&begin_r, scratch.buf, 4);
|
||||
pos += (n + 7) & ~(size_t)7;
|
||||
ncmds++;
|
||||
}
|
||||
vkb_enc_free(&scratch);
|
||||
VkResult r = c->dt->vkEndCommandBuffer(cb);
|
||||
if (begin_r != VK_SUCCESS) r = begin_r;
|
||||
if (vkb_verbose) VKB_DBG("command buffer %p: %u commands, %zu bytes -> %d", (void *)cb, ncmds, len, r);
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ hello */
|
||||
|
||||
void vkb_sv_vkbHello(vkb_srv_call *c)
|
||||
{
|
||||
uint64_t hash = vkb_dec_u64(&c->d);
|
||||
uint64_t token = vkb_dec_u64(&c->d);
|
||||
uint32_t pid = vkb_dec_u32(&c->d);
|
||||
const char *comm = vkb_dec_str(&c->d);
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_enc_u64(&c->r, VKB_PROTOCOL_HASH);
|
||||
if (hash != VKB_PROTOCOL_HASH) {
|
||||
VKB_ERR("client %d (%s) speaks protocol %016llx, this server %016llx: refusing", pid,
|
||||
comm ? comm : "?", (unsigned long long)hash, (unsigned long long)VKB_PROTOCOL_HASH);
|
||||
vkb_enc_u32(&c->r, 0);
|
||||
return;
|
||||
}
|
||||
if (!c->conn->proc) {
|
||||
c->conn->proc = proc_join(token, (int)pid);
|
||||
if (c->conn->proc->conns == 1) VKB_INFO("process %u is %s", pid, comm ? comm : "?");
|
||||
}
|
||||
vkb_enc_u32(&c->r, 1);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ statistics */
|
||||
|
||||
/* VKBRIDGE_STATS=<seconds> on the server: time spent per command, waiting for order, idle. */
|
||||
static uint64_t st_ns[VKB_CMD_COUNT], st_n[VKB_CMD_COUNT], st_wait_ns, st_last;
|
||||
static int st_period = -1;
|
||||
|
||||
static uint64_t mono_ns(void)
|
||||
{
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
|
||||
static void stats_add(uint32_t cmd, uint64_t ns, uint64_t wait_ns)
|
||||
{
|
||||
if (st_period < 0) {
|
||||
const char *v = getenv("VKBRIDGE_STATS");
|
||||
st_period = v ? atoi(v) : 0;
|
||||
}
|
||||
if (!st_period) return;
|
||||
__atomic_add_fetch(&st_ns[cmd], ns, __ATOMIC_RELAXED);
|
||||
__atomic_add_fetch(&st_n[cmd], 1, __ATOMIC_RELAXED);
|
||||
__atomic_add_fetch(&st_wait_ns, wait_ns, __ATOMIC_RELAXED);
|
||||
uint64_t now = mono_ns(), last = __atomic_load_n(&st_last, __ATOMIC_RELAXED);
|
||||
if (!last) {
|
||||
__atomic_store_n(&st_last, now, __ATOMIC_RELAXED);
|
||||
return;
|
||||
}
|
||||
if (now - last < (uint64_t)st_period * 1000000000ull || !__atomic_compare_exchange_n(&st_last, &last, now, 0, __ATOMIC_RELAXED, __ATOMIC_RELAXED))
|
||||
return;
|
||||
uint64_t total = 0;
|
||||
for (uint32_t i = 0; i < VKB_CMD_COUNT; i++) total += st_ns[i];
|
||||
VKB_INFO("stats over %ds: %.1f ms in handlers, %.1f ms waiting for order", st_period, total / 1e6, st_wait_ns / 1e6);
|
||||
for (int k = 0; k < 8; k++) {
|
||||
uint64_t best = 0;
|
||||
uint32_t bi = 0;
|
||||
for (uint32_t i = 0; i < VKB_CMD_COUNT; i++)
|
||||
if (st_ns[i] > best) {
|
||||
best = st_ns[i];
|
||||
bi = i;
|
||||
}
|
||||
if (!best) break;
|
||||
VKB_INFO(" %-40s %8llu calls %9.2f ms (%.2f us each)", vkb_cmd_names[bi], (unsigned long long)st_n[bi], best / 1e6,
|
||||
best / 1e3 / (double)st_n[bi]);
|
||||
st_ns[bi] = 0;
|
||||
}
|
||||
memset(st_ns, 0, sizeof(st_ns));
|
||||
memset(st_n, 0, sizeof(st_n));
|
||||
st_wait_ns = 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ connection loop */
|
||||
|
||||
/* Reads the next request. Buffered: a burst of small asynchronous requests costs one recvmsg, not
|
||||
* two reads each. Descriptors arrive with the first bytes of their message, so they queue up in
|
||||
* order and each header takes its nfds from the front. The payload points into the buffer and
|
||||
* stays valid until the next call. */
|
||||
static int srv_recv(vkb_srv_conn *conn, vkb_msg_hdr *h, uint8_t **payload, int *fds, int *nfds)
|
||||
{
|
||||
*nfds = 0;
|
||||
if (conn->rpos == conn->rlen && conn->rcap > (16u << 20)) {
|
||||
free(conn->rb);
|
||||
conn->rb = NULL;
|
||||
conn->rcap = conn->rpos = conn->rlen = 0;
|
||||
}
|
||||
for (;;) {
|
||||
size_t avail = conn->rlen - conn->rpos;
|
||||
size_t need = sizeof(*h);
|
||||
if (avail >= sizeof(*h)) {
|
||||
memcpy(h, conn->rb + conn->rpos, sizeof(*h));
|
||||
if (h->magic != VKB_MAGIC) {
|
||||
VKB_ERR("transport: bad message magic 0x%08x", h->magic);
|
||||
return -1;
|
||||
}
|
||||
if (h->size > (1u << 30) || h->nfds > VKB_MAX_FDS) {
|
||||
VKB_ERR("transport: bad message (%u bytes, %u descriptors)", h->size, h->nfds);
|
||||
return -1;
|
||||
}
|
||||
need += h->size;
|
||||
if (avail >= need) {
|
||||
if ((int)h->nfds > conn->fdn) {
|
||||
VKB_ERR("transport: message arrived without its %u descriptors", h->nfds);
|
||||
return -1;
|
||||
}
|
||||
*nfds = (int)h->nfds;
|
||||
memcpy(fds, conn->fdq, sizeof(int) * h->nfds);
|
||||
conn->fdn -= (int)h->nfds;
|
||||
memmove(conn->fdq, conn->fdq + h->nfds, sizeof(int) * conn->fdn);
|
||||
*payload = conn->rb + conn->rpos + sizeof(*h);
|
||||
conn->rpos += need;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (conn->rpos) {
|
||||
memmove(conn->rb, conn->rb + conn->rpos, avail);
|
||||
conn->rpos = 0;
|
||||
conn->rlen = avail;
|
||||
}
|
||||
if (need < (256u << 10)) need = 256u << 10;
|
||||
if (need > conn->rcap) {
|
||||
size_t nc = conn->rcap ? conn->rcap : (256u << 10);
|
||||
while (nc < need) nc *= 2;
|
||||
uint8_t *nb = realloc(conn->rb, nc);
|
||||
if (!nb) return -1;
|
||||
conn->rb = nb;
|
||||
conn->rcap = nc;
|
||||
}
|
||||
union {
|
||||
char buf[CMSG_SPACE(sizeof(int) * VKB_MAX_FDS)];
|
||||
struct cmsghdr align;
|
||||
} cm;
|
||||
struct iovec iov = {conn->rb + conn->rlen, conn->rcap - conn->rlen};
|
||||
struct msghdr msg;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.msg_iov = &iov;
|
||||
msg.msg_iovlen = 1;
|
||||
msg.msg_control = cm.buf;
|
||||
msg.msg_controllen = sizeof(cm.buf);
|
||||
ssize_t r;
|
||||
do {
|
||||
r = recvmsg(conn->sock, &msg, MSG_CMSG_CLOEXEC);
|
||||
} while (r < 0 && errno == EINTR);
|
||||
if (r <= 0) return -1;
|
||||
for (struct cmsghdr *cmh = CMSG_FIRSTHDR(&msg); cmh; cmh = CMSG_NXTHDR(&msg, cmh)) {
|
||||
if (cmh->cmsg_level != SOL_SOCKET || cmh->cmsg_type != SCM_RIGHTS) continue;
|
||||
int n = (int)((cmh->cmsg_len - CMSG_LEN(0)) / sizeof(int));
|
||||
for (int i = 0; i < n; i++) {
|
||||
int fd;
|
||||
memcpy(&fd, CMSG_DATA(cmh) + i * sizeof(int), sizeof(int));
|
||||
if (conn->fdn < (int)(sizeof(conn->fdq) / sizeof(conn->fdq[0]))) conn->fdq[conn->fdn++] = fd;
|
||||
else close(fd);
|
||||
}
|
||||
}
|
||||
if (msg.msg_flags & MSG_CTRUNC) VKB_WARN("transport: descriptors truncated");
|
||||
conn->rlen += (size_t)r;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ driver fault guard */
|
||||
|
||||
/*
|
||||
* A fault inside the GPU driver while serving one client used to take the whole app down (the
|
||||
* server runs in its process). Each request runs under a guard: SIGSEGV/SIGBUS on that thread
|
||||
* jumps back here, the client is cut off (it sees the bridge gone and fails or falls back), and
|
||||
* the app and the other clients go on. Any other fault goes to the handler that was there before.
|
||||
*/
|
||||
static __thread sigjmp_buf *t_guard;
|
||||
static __thread volatile sig_atomic_t t_fault;
|
||||
static struct sigaction prev_segv, prev_bus;
|
||||
static pthread_once_t guard_once = PTHREAD_ONCE_INIT;
|
||||
|
||||
static void guard_handler(int sig, siginfo_t *si, void *uc)
|
||||
{
|
||||
sigjmp_buf *g = t_guard;
|
||||
if (g) {
|
||||
t_guard = NULL;
|
||||
t_fault = sig;
|
||||
siglongjmp(*g, 1);
|
||||
}
|
||||
struct sigaction *p = sig == SIGBUS ? &prev_bus : &prev_segv;
|
||||
if ((p->sa_flags & SA_SIGINFO) && p->sa_sigaction) {
|
||||
p->sa_sigaction(sig, si, uc);
|
||||
return;
|
||||
}
|
||||
if (!(p->sa_flags & SA_SIGINFO) && p->sa_handler == SIG_IGN) return;
|
||||
if (!(p->sa_flags & SA_SIGINFO) && p->sa_handler && p->sa_handler != SIG_DFL) {
|
||||
p->sa_handler(sig);
|
||||
return;
|
||||
}
|
||||
signal(sig, SIG_DFL);
|
||||
raise(sig);
|
||||
}
|
||||
|
||||
static void guard_install(void)
|
||||
{
|
||||
struct sigaction sa;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = guard_handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGSEGV, &sa, &prev_segv);
|
||||
sigaction(SIGBUS, &sa, &prev_bus);
|
||||
}
|
||||
|
||||
static void *conn_main(void *arg)
|
||||
{
|
||||
pthread_once(&guard_once, guard_install);
|
||||
vkb_srv_conn *conn = arg;
|
||||
vkb_srv_call c;
|
||||
vkb_enc_init(&c.r);
|
||||
int fds[VKB_MAX_FDS];
|
||||
for (;;) {
|
||||
vkb_msg_hdr h;
|
||||
int nfds = 0;
|
||||
uint8_t *payload;
|
||||
if (srv_recv(conn, &h, &payload, fds, &nfds) < 0) break;
|
||||
vkb_enc_reset(&c.r);
|
||||
vkb_dec_init(&c.d, payload, h.size, &conn->arena, fds, nfds);
|
||||
c.conn = conn;
|
||||
c.status = VKB_ST_OK;
|
||||
c.nclose = 0;
|
||||
c.in_stream = 0;
|
||||
c.table = NULL;
|
||||
c.dt = &vkb_global_dt;
|
||||
if (h.cmd >= VKB_CMD_COUNT) {
|
||||
VKB_ERR("unknown command id %u", h.cmd);
|
||||
c.status = VKB_ST_BAD_MESSAGE;
|
||||
} else if (!conn->proc && h.cmd != VKB_CMD_vkbHello) {
|
||||
VKB_ERR("%s before hello", vkb_cmd_names[h.cmd]);
|
||||
c.status = VKB_ST_BAD_MESSAGE;
|
||||
} else {
|
||||
if (h.table) {
|
||||
c.table = vkb_table_get(h.table);
|
||||
if (!c.table || c.table->proc != conn->proc) {
|
||||
VKB_ERR("%s: unknown dispatch table %u", vkb_cmd_names[h.cmd], h.table);
|
||||
c.status = VKB_ST_BAD_TABLE;
|
||||
} else {
|
||||
c.dt = &c.table->dt;
|
||||
}
|
||||
}
|
||||
if (c.status == VKB_ST_OK) {
|
||||
uint64_t t0 = st_period ? mono_ns() : 0;
|
||||
order_wait(conn->proc, h.barrier);
|
||||
uint64_t t1 = st_period ? mono_ns() : 0;
|
||||
vkb_srv_set_current_table(c.table);
|
||||
if (vkb_verbose) VKB_DBG("-> %s", vkb_cmd_names[h.cmd]);
|
||||
vkb_srv_current_cmd = vkb_cmd_names[h.cmd];
|
||||
sigjmp_buf jb;
|
||||
if (sigsetjmp(jb, 1)) {
|
||||
VKB_ERR("the GPU driver crashed (signal %d) in %s for process %d; that client is cut off, the app and "
|
||||
"the other clients carry on", (int)t_fault, vkb_cmd_names[h.cmd], conn->proc ? conn->proc->pid : -1);
|
||||
if (conn->proc) conn->proc->driver_crashed = 1;
|
||||
vkb_srv_current_cmd = NULL;
|
||||
vkb_srv_set_current_table(NULL);
|
||||
order_done(conn->proc, h.seq);
|
||||
break;
|
||||
}
|
||||
t_guard = &jb;
|
||||
vkb_srv_handlers[h.cmd](&c);
|
||||
t_guard = NULL;
|
||||
vkb_srv_current_cmd = NULL;
|
||||
vkb_srv_set_current_table(NULL);
|
||||
if (st_period) stats_add(h.cmd, mono_ns() - t1, t1 - t0);
|
||||
}
|
||||
}
|
||||
vkb_dec_close_untaken(&c.d);
|
||||
order_done(conn->proc, h.seq);
|
||||
if (!(h.flags & VKB_F_NOREPLY)) {
|
||||
vkb_msg_hdr rh = {VKB_MAGIC, c.status == VKB_ST_OK ? (uint32_t)c.r.len : 0, c.status, 0,
|
||||
c.status == VKB_ST_OK ? (uint32_t)c.r.nfds : 0, 0, 0, 0};
|
||||
if (c.r.oom) {
|
||||
rh.cmd = VKB_ST_BAD_MESSAGE;
|
||||
rh.size = 0;
|
||||
rh.nfds = 0;
|
||||
}
|
||||
if (vkb_send_msg(conn->sock, &rh, c.r.buf, c.r.fds, (int)rh.nfds) < 0) {
|
||||
for (int i = 0; i < c.nclose; i++) close(c.close_after[i]);
|
||||
break;
|
||||
}
|
||||
} else if (c.status != VKB_ST_OK) {
|
||||
VKB_ERR("asynchronous %s failed (status %u)", vkb_cmd_names[h.cmd], c.status);
|
||||
} else if (vkb_cmd_result[h.cmd] && c.r.len >= sizeof(int32_t)) {
|
||||
/* The client already told the app VK_SUCCESS; a failure can only be reported here. */
|
||||
int32_t vr;
|
||||
memcpy(&vr, c.r.buf, sizeof(vr));
|
||||
if (vr < 0) VKB_ERR("asynchronous %s returned %d", vkb_cmd_names[h.cmd], vr);
|
||||
}
|
||||
for (int i = 0; i < c.nclose; i++) close(c.close_after[i]);
|
||||
vkb_arena_reset(&conn->arena);
|
||||
}
|
||||
close(conn->sock);
|
||||
vkb_enc_free(&c.r);
|
||||
free(conn->rb);
|
||||
for (int i = 0; i < conn->fdn; i++) close(conn->fdq[i]);
|
||||
vkb_arena_free(&conn->arena);
|
||||
if (conn->proc) proc_leave(conn->proc);
|
||||
free(conn);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void vkb_srv_serve(int lfd)
|
||||
{
|
||||
stats_add(0, 0, 0);
|
||||
for (;;) {
|
||||
int s = accept4(lfd, NULL, NULL, SOCK_CLOEXEC);
|
||||
if (s < 0) {
|
||||
if (errno == EINTR || errno == ECONNABORTED) continue;
|
||||
VKB_ERR("accept: %s", strerror(errno));
|
||||
continue;
|
||||
}
|
||||
vkb_srv_conn *conn = calloc(1, sizeof(*conn));
|
||||
conn->sock = s;
|
||||
pthread_attr_t attr;
|
||||
pthread_attr_init(&attr);
|
||||
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
||||
/* Driver calls (pipeline compiles) can use a lot of stack. */
|
||||
pthread_attr_setstacksize(&attr, 4u << 20);
|
||||
if (pthread_create(&conn->thread, &attr, conn_main, conn) != 0) {
|
||||
VKB_ERR("cannot start a connection thread");
|
||||
close(s);
|
||||
free(conn);
|
||||
}
|
||||
pthread_attr_destroy(&attr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Descriptor sets named by the client. Where the client keeps a pool's books it knows an
|
||||
* allocation will succeed, so it names the sets itself (VKB_DS_TAG | n) and sends the allocation
|
||||
* without waiting (vkbAllocDescSets) - DXVK allocates a set or two per draw, and a round trip
|
||||
* each was most of the bridge's remaining cost per frame. Here those names map to the driver's
|
||||
* sets: wrappers in the device's dispatch table translate them wherever a set goes back to the
|
||||
* driver (updates, template updates, binds, frees), and a pool's reset or destruction forgets its
|
||||
* sets. Sets the server named itself (the synchronous path) pass through untouched.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define VKB_DS_TAG (1ull << 63)
|
||||
#define DS_BUCKETS 8192
|
||||
#define DS_LOCAL 64
|
||||
|
||||
typedef struct ds_ent {
|
||||
uint64_t id;
|
||||
VkDescriptorSet set;
|
||||
struct ds_ent *next; /* bucket chain */
|
||||
struct ds_ent *pool_next; /* the pool's sets */
|
||||
} ds_ent;
|
||||
|
||||
typedef struct ds_pool {
|
||||
VkDescriptorPool pool;
|
||||
ds_ent *sets;
|
||||
struct ds_pool *next;
|
||||
} ds_pool;
|
||||
|
||||
typedef struct vkb_dsmap {
|
||||
pthread_mutex_t lock;
|
||||
ds_ent *buckets[DS_BUCKETS];
|
||||
ds_pool *pools;
|
||||
int warned;
|
||||
PFN_vkAllocateDescriptorSets allocate;
|
||||
PFN_vkUpdateDescriptorSets update;
|
||||
PFN_vkUpdateDescriptorSetWithTemplate update_template;
|
||||
PFN_vkCmdBindDescriptorSets bind;
|
||||
PFN_vkCmdBindDescriptorSets2 bind2;
|
||||
PFN_vkFreeDescriptorSets free_sets;
|
||||
PFN_vkResetDescriptorPool reset_pool;
|
||||
PFN_vkDestroyDescriptorPool destroy_pool;
|
||||
} vkb_dsmap;
|
||||
|
||||
static unsigned bucket(uint64_t id)
|
||||
{
|
||||
id *= 0x9e3779b97f4a7c15ull;
|
||||
return (unsigned)(id >> 51) & (DS_BUCKETS - 1);
|
||||
}
|
||||
|
||||
static vkb_dsmap *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->dsmap : NULL;
|
||||
}
|
||||
|
||||
static int tagged(VkDescriptorSet s)
|
||||
{
|
||||
return ((uint64_t)s & VKB_DS_TAG) != 0;
|
||||
}
|
||||
|
||||
/* The driver's set for a client name; VK_NULL_HANDLE when its allocation failed. */
|
||||
static VkDescriptorSet lookup(vkb_dsmap *m, VkDescriptorSet s)
|
||||
{
|
||||
if (!tagged(s)) return s;
|
||||
uint64_t id = (uint64_t)s;
|
||||
pthread_mutex_lock(&m->lock);
|
||||
ds_ent *e = m->buckets[bucket(id)];
|
||||
while (e && e->id != id) e = e->next;
|
||||
VkDescriptorSet r = e ? e->set : VK_NULL_HANDLE;
|
||||
pthread_mutex_unlock(&m->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void missing(vkb_dsmap *m, const char *where)
|
||||
{
|
||||
if (__atomic_fetch_add(&m->warned, 1, __ATOMIC_RELAXED) < 20)
|
||||
VKB_ERR("%s: a descriptor set the client allocated ahead does not exist (its allocation failed); skipped", where);
|
||||
}
|
||||
|
||||
static ds_pool *pool_get(vkb_dsmap *m, VkDescriptorPool pool, int create)
|
||||
{
|
||||
for (ds_pool *p = m->pools; p; p = p->next)
|
||||
if (p->pool == pool) return p;
|
||||
if (!create) return NULL;
|
||||
ds_pool *p = calloc(1, sizeof(*p));
|
||||
if (!p) return NULL;
|
||||
p->pool = pool;
|
||||
p->next = m->pools;
|
||||
m->pools = p;
|
||||
return p;
|
||||
}
|
||||
|
||||
/* Forgets the pool's sets (a reset or destruction freed them); the record goes with destroy. */
|
||||
static void pool_forget(vkb_dsmap *m, VkDescriptorPool pool, int destroy)
|
||||
{
|
||||
pthread_mutex_lock(&m->lock);
|
||||
for (ds_pool **pp = &m->pools; *pp; pp = &(*pp)->next) {
|
||||
ds_pool *p = *pp;
|
||||
if (p->pool != pool) continue;
|
||||
while (p->sets) {
|
||||
ds_ent *e = p->sets;
|
||||
p->sets = e->pool_next;
|
||||
ds_ent **bp = &m->buckets[bucket(e->id)];
|
||||
while (*bp && *bp != e) bp = &(*bp)->next;
|
||||
if (*bp) *bp = e->next;
|
||||
free(e);
|
||||
}
|
||||
if (destroy) {
|
||||
*pp = p->next;
|
||||
free(p);
|
||||
}
|
||||
break;
|
||||
}
|
||||
pthread_mutex_unlock(&m->lock);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the allocation request */
|
||||
|
||||
/* vkbAllocDescSets: device, pool, count, then per set its layout and the client's name. */
|
||||
void vkb_sv_vkbAllocDescSets(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDescriptorPool pool;
|
||||
vkb_dec_bytes(&c->d, &pool, sizeof(pool));
|
||||
uint32_t n = vkb_dec_u32(&c->d);
|
||||
if (c->d.err || !c->table || !c->table->dsmap || n == 0 || n > 4096) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_dsmap *m = c->table->dsmap;
|
||||
VkDescriptorSetLayout layouts_local[DS_LOCAL], *layouts = n <= DS_LOCAL ? layouts_local : malloc(n * sizeof(*layouts));
|
||||
uint64_t ids_local[DS_LOCAL], *ids = n <= DS_LOCAL ? ids_local : malloc(n * sizeof(*ids));
|
||||
VkDescriptorSet sets_local[DS_LOCAL], *sets = n <= DS_LOCAL ? sets_local : malloc(n * sizeof(*sets));
|
||||
if (!layouts || !ids || !sets) goto out;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
vkb_dec_bytes(&c->d, &layouts[i], sizeof(layouts[i]));
|
||||
ids[i] = vkb_dec_u64(&c->d);
|
||||
}
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
goto out;
|
||||
}
|
||||
VkDescriptorSetAllocateInfo ai = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, pool, n, layouts};
|
||||
VkResult r = m->allocate(dev, &ai, sets);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_ERR("allocating %u descriptor sets the client named ahead failed: %d (the client's pool books disagree "
|
||||
"with the driver)", n, r);
|
||||
goto out;
|
||||
}
|
||||
pthread_mutex_lock(&m->lock);
|
||||
ds_pool *p = pool_get(m, pool, 1);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
ds_ent *e = malloc(sizeof(*e));
|
||||
if (!e || !p) {
|
||||
free(e);
|
||||
break;
|
||||
}
|
||||
e->id = ids[i];
|
||||
e->set = sets[i];
|
||||
unsigned b = bucket(e->id);
|
||||
e->next = m->buckets[b];
|
||||
m->buckets[b] = e;
|
||||
e->pool_next = p->sets;
|
||||
p->sets = e;
|
||||
}
|
||||
pthread_mutex_unlock(&m->lock);
|
||||
out:
|
||||
if (layouts != layouts_local) free(layouts);
|
||||
if (ids != ids_local) free(ids);
|
||||
if (sets != sets_local) free(sets);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ wrappers */
|
||||
|
||||
static void VKAPI_CALL ds_UpdateDescriptorSets(VkDevice device, uint32_t nw, const VkWriteDescriptorSet *w, uint32_t nc,
|
||||
const VkCopyDescriptorSet *cp)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
int any = 0;
|
||||
for (uint32_t i = 0; i < nw && !any; i++) any = tagged(w[i].dstSet);
|
||||
for (uint32_t i = 0; i < nc && !any; i++) any = tagged(cp[i].srcSet) || tagged(cp[i].dstSet);
|
||||
if (!any) {
|
||||
m->update(device, nw, w, nc, cp);
|
||||
return;
|
||||
}
|
||||
VkWriteDescriptorSet w_local[DS_LOCAL], *w2 = nw <= DS_LOCAL ? w_local : malloc(nw * sizeof(*w2));
|
||||
VkCopyDescriptorSet c_local[DS_LOCAL], *c2 = nc <= DS_LOCAL ? c_local : malloc(nc * sizeof(*c2));
|
||||
if ((nw && !w2) || (nc && !c2)) goto out;
|
||||
uint32_t kw = 0, kc = 0;
|
||||
for (uint32_t i = 0; i < nw; i++) {
|
||||
w2[kw] = w[i];
|
||||
w2[kw].dstSet = lookup(m, w[i].dstSet);
|
||||
if (w2[kw].dstSet) kw++;
|
||||
else missing(m, "vkUpdateDescriptorSets");
|
||||
}
|
||||
for (uint32_t i = 0; i < nc; i++) {
|
||||
c2[kc] = cp[i];
|
||||
c2[kc].srcSet = lookup(m, cp[i].srcSet);
|
||||
c2[kc].dstSet = lookup(m, cp[i].dstSet);
|
||||
if (c2[kc].srcSet && c2[kc].dstSet) kc++;
|
||||
else missing(m, "vkUpdateDescriptorSets (copy)");
|
||||
}
|
||||
if (kw || kc) m->update(device, kw, w2, kc, c2);
|
||||
out:
|
||||
if (w2 != w_local) free(w2);
|
||||
if (c2 != c_local) free(c2);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_UpdateDescriptorSetWithTemplate(VkDevice device, VkDescriptorSet set, VkDescriptorUpdateTemplate tmpl,
|
||||
const void *data)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
VkDescriptorSet s = lookup(m, set);
|
||||
if (!s) {
|
||||
missing(m, "vkUpdateDescriptorSetWithTemplate");
|
||||
return;
|
||||
}
|
||||
m->update_template(device, s, tmpl, data);
|
||||
}
|
||||
|
||||
/* Translates n sets into out; 0 when one of them does not exist. */
|
||||
static int translate(vkb_dsmap *m, uint32_t n, const VkDescriptorSet *in, VkDescriptorSet *out)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
/* VK_NULL_HANDLE is allowed in binds (graphicsPipelineLibrary) and stays so. */
|
||||
out[i] = in[i] ? lookup(m, in[i]) : VK_NULL_HANDLE;
|
||||
if (in[i] && !out[i]) return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_CmdBindDescriptorSets(VkCommandBuffer cb, VkPipelineBindPoint bp, VkPipelineLayout layout, uint32_t first,
|
||||
uint32_t n, const VkDescriptorSet *sets, uint32_t ndyn, const uint32_t *dyn)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
VkDescriptorSet local[DS_LOCAL], *s = n <= DS_LOCAL ? local : malloc(n * sizeof(*s));
|
||||
if (!s) return;
|
||||
if (translate(m, n, sets, s)) m->bind(cb, bp, layout, first, n, s, ndyn, dyn);
|
||||
else missing(m, "vkCmdBindDescriptorSets");
|
||||
if (s != local) free(s);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_CmdBindDescriptorSets2(VkCommandBuffer cb, const VkBindDescriptorSetsInfo *info)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
uint32_t n = info->descriptorSetCount;
|
||||
VkDescriptorSet local[DS_LOCAL], *s = n <= DS_LOCAL ? local : malloc(n * sizeof(*s));
|
||||
if (!s) return;
|
||||
VkBindDescriptorSetsInfo i2 = *info;
|
||||
i2.pDescriptorSets = s;
|
||||
if (translate(m, n, info->pDescriptorSets, s)) m->bind2(cb, &i2);
|
||||
else missing(m, "vkCmdBindDescriptorSets2");
|
||||
if (s != local) free(s);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL ds_FreeDescriptorSets(VkDevice device, VkDescriptorPool pool, uint32_t n, const VkDescriptorSet *sets)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
VkDescriptorSet local[DS_LOCAL], *s = n <= DS_LOCAL ? local : malloc(n * sizeof(*s));
|
||||
if (!s) return VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
/* Named sets come only from pools without FREE_DESCRIPTOR_SET (the client keeps no books on
|
||||
* those), so this is an app error at worst: what does not exist is left out. */
|
||||
uint32_t k = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkDescriptorSet t = sets[i] ? lookup(m, sets[i]) : VK_NULL_HANDLE;
|
||||
if (t || !sets[i]) s[k++] = t;
|
||||
}
|
||||
VkResult r = k ? m->free_sets(device, pool, k, s) : VK_SUCCESS;
|
||||
if (s != local) free(s);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL ds_ResetDescriptorPool(VkDevice device, VkDescriptorPool pool, VkDescriptorPoolResetFlags flags)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
pool_forget(m, pool, 0);
|
||||
return m->reset_pool(device, pool, flags);
|
||||
}
|
||||
|
||||
static void VKAPI_CALL ds_DestroyDescriptorPool(VkDevice device, VkDescriptorPool pool, const VkAllocationCallbacks *a)
|
||||
{
|
||||
vkb_dsmap *m = cur();
|
||||
if (pool) pool_forget(m, pool, 1);
|
||||
m->destroy_pool(device, pool, a);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ device hooks */
|
||||
|
||||
void vkb_dsmap_device_init(vkb_srv_table *t)
|
||||
{
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
if (!dt->vkAllocateDescriptorSets || !dt->vkUpdateDescriptorSets || !dt->vkCmdBindDescriptorSets ||
|
||||
!dt->vkResetDescriptorPool || !dt->vkDestroyDescriptorPool || !dt->vkFreeDescriptorSets)
|
||||
return;
|
||||
vkb_dsmap *m = calloc(1, sizeof(*m));
|
||||
if (!m) return;
|
||||
pthread_mutex_init(&m->lock, NULL);
|
||||
m->allocate = dt->vkAllocateDescriptorSets;
|
||||
m->update = dt->vkUpdateDescriptorSets;
|
||||
m->update_template = dt->vkUpdateDescriptorSetWithTemplate;
|
||||
m->bind = dt->vkCmdBindDescriptorSets;
|
||||
m->bind2 = dt->vkCmdBindDescriptorSets2;
|
||||
m->free_sets = dt->vkFreeDescriptorSets;
|
||||
m->reset_pool = dt->vkResetDescriptorPool;
|
||||
m->destroy_pool = dt->vkDestroyDescriptorPool;
|
||||
dt->vkUpdateDescriptorSets = ds_UpdateDescriptorSets;
|
||||
if (m->update_template) dt->vkUpdateDescriptorSetWithTemplate = ds_UpdateDescriptorSetWithTemplate;
|
||||
dt->vkCmdBindDescriptorSets = ds_CmdBindDescriptorSets;
|
||||
if (m->bind2) dt->vkCmdBindDescriptorSets2 = ds_CmdBindDescriptorSets2;
|
||||
dt->vkFreeDescriptorSets = ds_FreeDescriptorSets;
|
||||
dt->vkResetDescriptorPool = ds_ResetDescriptorPool;
|
||||
dt->vkDestroyDescriptorPool = ds_DestroyDescriptorPool;
|
||||
t->dsmap = m;
|
||||
}
|
||||
|
||||
void vkb_dsmap_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_dsmap *m = t->dsmap;
|
||||
if (!m) return;
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
dt->vkUpdateDescriptorSets = m->update;
|
||||
if (m->update_template) dt->vkUpdateDescriptorSetWithTemplate = m->update_template;
|
||||
dt->vkCmdBindDescriptorSets = m->bind;
|
||||
if (m->bind2) dt->vkCmdBindDescriptorSets2 = m->bind2;
|
||||
dt->vkFreeDescriptorSets = m->free_sets;
|
||||
dt->vkResetDescriptorPool = m->reset_pool;
|
||||
dt->vkDestroyDescriptorPool = m->destroy_pool;
|
||||
while (m->pools) pool_forget(m, m->pools->pool, 1);
|
||||
pthread_mutex_destroy(&m->lock);
|
||||
free(m);
|
||||
t->dsmap = NULL;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Feature emulation: entry point. What the GPU lacks and the bridge can make up for is decided
|
||||
* here per physical device; the client reports those features as present, the server strips
|
||||
* them from vkCreateDevice and installs wrappers in the device's dispatch table.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
static int token(const char *list, const char *t)
|
||||
{
|
||||
size_t n = strlen(t);
|
||||
for (const char *p = list; p && (p = strstr(p, t)); p += n)
|
||||
if ((p == list || p[-1] == ',') && (p[n] == ',' || p[n] == 0)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int env_off(const char *name)
|
||||
{
|
||||
const char *v = getenv(name);
|
||||
return v && !strcmp(v, "0");
|
||||
}
|
||||
|
||||
uint32_t vkb_emu_detect(const vkb_dispatch *idt, VkPhysicalDevice pd, uint32_t *missing)
|
||||
{
|
||||
VkPhysicalDeviceFeatures f;
|
||||
idt->vkGetPhysicalDeviceFeatures(pd, &f);
|
||||
uint32_t n = 0;
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, e);
|
||||
int divisor = 0, depth_clip = 0, maint5 = 0, robust2 = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
if (!strcmp(e[i].extensionName, "VK_EXT_vertex_attribute_divisor") ||
|
||||
!strcmp(e[i].extensionName, "VK_KHR_vertex_attribute_divisor"))
|
||||
divisor = 1;
|
||||
if (!strcmp(e[i].extensionName, "VK_EXT_depth_clip_enable")) depth_clip = 1;
|
||||
if (!strcmp(e[i].extensionName, "VK_KHR_maintenance5")) maint5 = 1;
|
||||
if (!strcmp(e[i].extensionName, "VK_EXT_robustness2") || !strcmp(e[i].extensionName, "VK_KHR_robustness2")) robust2 = 1;
|
||||
}
|
||||
free(e);
|
||||
/* VKBRIDGE_FAKE_MISSING=bc,divisor,clip,cull,depthclip pretends the GPU lacks them (host tests). */
|
||||
const char *fake = getenv("VKBRIDGE_FAKE_MISSING");
|
||||
if (fake) {
|
||||
if (token(fake, "bc")) f.textureCompressionBC = VK_FALSE;
|
||||
if (token(fake, "divisor")) divisor = 0;
|
||||
if (token(fake, "clip")) f.shaderClipDistance = VK_FALSE;
|
||||
if (token(fake, "cull")) f.shaderCullDistance = VK_FALSE;
|
||||
if (token(fake, "depthclip")) depth_clip = 0;
|
||||
if (token(fake, "maint5")) maint5 = 0;
|
||||
if (token(fake, "robustness2")) robust2 = 0;
|
||||
}
|
||||
uint32_t emu = 0;
|
||||
VkPhysicalDeviceProperties props;
|
||||
idt->vkGetPhysicalDeviceProperties(pd, &props);
|
||||
/* Vulkan 1.4 has maintenance5 in core. */
|
||||
if (!maint5 && (props.apiVersion < VK_API_VERSION_1_4 || (fake && token(fake, "maint5"))) && !env_off("VKBRIDGE_EMU_MAINT5"))
|
||||
emu |= VKB_EMU_MAINT5;
|
||||
if (!f.textureCompressionBC && vkb_emu_bcn_supported(idt, pd) && !env_off("VKBRIDGE_EMU_BCN")) emu |= VKB_EMU_BCN;
|
||||
if (!divisor && !env_off("VKBRIDGE_EMU_DIVISOR")) emu |= VKB_EMU_DIVISOR;
|
||||
if (!f.shaderClipDistance && !env_off("VKBRIDGE_EMU_CLIP")) emu |= VKB_EMU_CLIP_DISTANCE;
|
||||
if (!f.shaderCullDistance && !env_off("VKBRIDGE_EMU_CULL")) emu |= VKB_EMU_CULL_DISTANCE;
|
||||
if (!depth_clip && f.depthClamp && !env_off("VKBRIDGE_EMU_DEPTHCLIP")) emu |= VKB_EMU_DEPTH_CLIP;
|
||||
/* DXVK will not start without robustness2. Mali r44 lacks it; GameNative's wrapper reports it
|
||||
* (robustBufferAccess2, robustImageAccess2, nullDescriptor) without enforcing it, and DXVK
|
||||
* games run - out-of-bounds reads and null descriptors are then up to the driver. */
|
||||
if (!robust2 && f.robustBufferAccess && !env_off("VKBRIDGE_EMU_ROBUSTNESS2")) emu |= VKB_EMU_ROBUSTNESS2;
|
||||
/* PointSize in geometry/tessellation stages: stripped when the feature is missing. */
|
||||
if (!f.shaderTessellationAndGeometryPointSize && (f.geometryShader || f.tessellationShader)) emu |= VKB_EMU_POINT_SIZE;
|
||||
uint32_t miss = 0;
|
||||
if (!f.textureCompressionBC) miss |= VKB_EMU_BCN;
|
||||
if (!divisor) miss |= VKB_EMU_DIVISOR;
|
||||
if (!f.shaderClipDistance) miss |= VKB_EMU_CLIP_DISTANCE;
|
||||
if (!f.shaderCullDistance) miss |= VKB_EMU_CULL_DISTANCE;
|
||||
if (!depth_clip) miss |= VKB_EMU_DEPTH_CLIP;
|
||||
if (emu & VKB_EMU_MAINT5) miss |= VKB_EMU_MAINT5;
|
||||
if (!robust2) miss |= VKB_EMU_ROBUSTNESS2;
|
||||
*missing = miss;
|
||||
return emu & VKB_EMU_IMPLEMENTED;
|
||||
}
|
||||
|
||||
/* Remove a structure from a pNext chain (the chain lives in the request's arena). */
|
||||
static void chain_remove(VkDeviceCreateInfo *ci, VkStructureType t)
|
||||
{
|
||||
VkBaseOutStructure *prev = (VkBaseOutStructure *)ci;
|
||||
while (prev->pNext) {
|
||||
if (prev->pNext->sType == t) prev->pNext = prev->pNext->pNext;
|
||||
else prev = prev->pNext;
|
||||
}
|
||||
}
|
||||
|
||||
static VkPhysicalDeviceFeatures *find_features(VkDeviceCreateInfo *ci)
|
||||
{
|
||||
if (ci->pEnabledFeatures) return (VkPhysicalDeviceFeatures *)ci->pEnabledFeatures;
|
||||
for (VkBaseOutStructure *b = (VkBaseOutStructure *)ci->pNext; b; b = b->pNext)
|
||||
if (b->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2) return &((VkPhysicalDeviceFeatures2 *)b)->features;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void vkb_emu_device_create_info(vkb_srv_table *inst, VkPhysicalDevice pd, uint32_t emu, VkDeviceCreateInfo *ci, vkb_arena *a)
|
||||
{
|
||||
VkPhysicalDeviceFeatures real;
|
||||
inst->real.vkGetPhysicalDeviceFeatures(pd, &real);
|
||||
VkPhysicalDeviceFeatures *f = find_features(ci);
|
||||
if ((emu & (VKB_EMU_BCN | VKB_EMU_DEPTH_CLIP)) && !f) {
|
||||
/* The BC decoder writes R8/RG8 storage images: it needs this feature on, so the request
|
||||
* gets a features structure if it had none. */
|
||||
f = vkb_arena_alloc(a, sizeof(*f));
|
||||
ci->pEnabledFeatures = f;
|
||||
}
|
||||
if (f) {
|
||||
/* pEnabledFeatures came from the request: it is ours to change. Anything the client asked
|
||||
* for that the GPU does not have is either emulated or would fail the call. */
|
||||
VkBool32 *want = (VkBool32 *)f;
|
||||
const VkBool32 *have = (const VkBool32 *)ℜ
|
||||
for (size_t i = 0; i < sizeof(*f) / sizeof(VkBool32); i++) {
|
||||
if (want[i] && !have[i]) want[i] = VK_FALSE;
|
||||
}
|
||||
if (emu & VKB_EMU_BCN) f->shaderStorageImageExtendedFormats = VK_TRUE;
|
||||
if (emu & VKB_EMU_DEPTH_CLIP) f->depthClamp = VK_TRUE;
|
||||
}
|
||||
if (emu & VKB_EMU_DIVISOR) chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VERTEX_ATTRIBUTE_DIVISOR_FEATURES_EXT);
|
||||
if (emu & VKB_EMU_DEPTH_CLIP) chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DEPTH_CLIP_ENABLE_FEATURES_EXT);
|
||||
if (emu & VKB_EMU_MAINT5) chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES);
|
||||
if (emu & VKB_EMU_ROBUSTNESS2) {
|
||||
chain_remove(ci, VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT);
|
||||
/* What robustness the GPU has stays on; robustBufferAccess2 asks for at least that. */
|
||||
VkPhysicalDeviceFeatures *rf = find_features(ci);
|
||||
if (rf) rf->robustBufferAccess = VK_TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_device_init(vkb_srv_table *dev, uint32_t emu)
|
||||
{
|
||||
if (!emu) return;
|
||||
vkb_emu_device *e = calloc(1, sizeof(*e));
|
||||
e->flags = emu;
|
||||
e->dev = dev;
|
||||
pthread_mutex_init(&e->lock, NULL);
|
||||
dev->emu = e;
|
||||
vkb_emu_install(dev);
|
||||
}
|
||||
|
||||
void vkb_emu_device_destroy(vkb_srv_table *dev)
|
||||
{
|
||||
if (!dev->emu) return;
|
||||
vkb_emu_uninstall(dev);
|
||||
pthread_mutex_destroy(&dev->emu->lock);
|
||||
free(dev->emu);
|
||||
dev->emu = NULL;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
#ifndef VKB_SERVER_EMU_H
|
||||
#define VKB_SERVER_EMU_H
|
||||
|
||||
#include "vkb_server.h"
|
||||
|
||||
/* Emulations that are implemented (the rest are never offered to the client). */
|
||||
#define VKB_EMU_IMPLEMENTED (VKB_EMU_MAINT5 | VKB_EMU_CLIP_DISTANCE | VKB_EMU_CULL_DISTANCE | VKB_EMU_POINT_SIZE | VKB_EMU_BCN | \
|
||||
VKB_EMU_DIVISOR | VKB_EMU_DEPTH_CLIP | VKB_EMU_ROBUSTNESS2)
|
||||
|
||||
#define VKB_EMU_BUCKETS 1024
|
||||
|
||||
typedef struct vkb_emu_image {
|
||||
VkImage image;
|
||||
VkImageType type;
|
||||
VkFormat format; /* what the driver holds */
|
||||
VkFormat client_format; /* what the app asked for (differs for emulated formats) */
|
||||
VkExtent3D extent;
|
||||
uint32_t mips, layers;
|
||||
void *emu; /* per-emulation state (BCn: decode resources) */
|
||||
struct vkb_emu_image *next;
|
||||
} vkb_emu_image;
|
||||
|
||||
typedef struct vkb_emu_buffer {
|
||||
VkBuffer buffer;
|
||||
VkDeviceSize size;
|
||||
struct vkb_emu_buffer *next;
|
||||
} vkb_emu_buffer;
|
||||
|
||||
typedef struct vkb_emu_device {
|
||||
uint32_t flags;
|
||||
vkb_srv_table *dev;
|
||||
pthread_mutex_t lock;
|
||||
vkb_emu_image *images[VKB_EMU_BUCKETS];
|
||||
vkb_emu_buffer *buffers[VKB_EMU_BUCKETS];
|
||||
void *bcn; /* server_emu_bcn.c */
|
||||
void *cmdstate; /* server_emu_cmdstate.c */
|
||||
void *divisor; /* server_emu_divisor.c */
|
||||
void *shaders; /* server_emu_shader.c */
|
||||
} vkb_emu_device;
|
||||
|
||||
/* command buffer state (server_emu_cmdstate.c) */
|
||||
void vkb_emu_cmdstate_install(vkb_srv_table *dev);
|
||||
void vkb_emu_cmdstate_uninstall(vkb_srv_table *dev);
|
||||
void vkb_emu_restore_compute(vkb_emu_device *e, VkCommandBuffer cb);
|
||||
void *vkb_emu_cb_gfx(vkb_emu_device *e, VkCommandBuffer cb, size_t size);
|
||||
VkDescriptorSet vkb_emu_cb_scratch_set(vkb_emu_device *e, VkCommandBuffer cb, VkDescriptorSetLayout dsl);
|
||||
/* vertex attribute divisor (server_emu_divisor.c) */
|
||||
typedef struct div_info div_info;
|
||||
size_t vkb_emu_divisor_info_size(void);
|
||||
void vkb_emu_divisor_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, div_info *out);
|
||||
void vkb_emu_divisor_created(vkb_emu_device *e, VkDevice device, VkPipelineCache cache, const VkGraphicsPipelineCreateInfo *ci,
|
||||
VkPipeline p, div_info *info);
|
||||
void vkb_emu_divisor_install(vkb_srv_table *dev);
|
||||
void vkb_emu_divisor_uninstall(vkb_srv_table *dev);
|
||||
void vkb_emu_gfx_bind_pipeline(vkb_emu_device *e, VkCommandBuffer cb, VkPipeline p);
|
||||
void vkb_emu_gfx_reset(void *gfx);
|
||||
void vkb_emu_gfx_free(void *gfx);
|
||||
/* BCn (server_emu_bcn.c) */
|
||||
void vkb_emu_bcn_install(vkb_srv_table *dev);
|
||||
void vkb_emu_bcn_uninstall(vkb_srv_table *dev);
|
||||
VkFormat vkb_emu_bcn_view_format(vkb_emu_device *e, VkImage image, VkFormat requested);
|
||||
void vkb_emu_bcn_buffer_usage(vkb_emu_device *e, VkBufferCreateInfo *ci);
|
||||
int vkb_emu_bcn_blocks_readback(vkb_emu_device *e, VkImage img);
|
||||
|
||||
/* layer (server_emu_layer.c) */
|
||||
void vkb_emu_depth_clip_pipeline(vkb_emu_device *e, VkGraphicsPipelineCreateInfo *ci);
|
||||
void vkb_emu_depth_clip_install(vkb_srv_table *dev);
|
||||
vkb_emu_device *vkb_emu_cur(void);
|
||||
const vkb_dispatch *vkb_emu_real(void);
|
||||
void *vkb_emu_chain_take(const void *head, VkStructureType t);
|
||||
vkb_emu_image *vkb_emu_find_image(vkb_emu_device *e, VkImage img);
|
||||
void vkb_emu_track_image(vkb_emu_device *e, VkImage img, const VkImageCreateInfo *ci, VkFormat client_format);
|
||||
|
||||
/* feature hooks (server_emu_features.c and friends) */
|
||||
int vkb_emu_bcn_supported(const vkb_dispatch *idt, VkPhysicalDevice pd);
|
||||
void vkb_emu_install(vkb_srv_table *dev);
|
||||
void vkb_emu_uninstall(vkb_srv_table *dev);
|
||||
void vkb_emu_install_features(vkb_srv_table *dev);
|
||||
void vkb_emu_uninstall_features(vkb_srv_table *dev);
|
||||
void vkb_emu_image_create_info(vkb_emu_device *e, VkImageCreateInfo *ci);
|
||||
void vkb_emu_image_release(vkb_emu_device *e, vkb_emu_image *img);
|
||||
/* Rewrites a graphics pipeline's shaders; temporary modules are appended to mods. */
|
||||
void vkb_emu_shader_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, VkShaderModule *mods,
|
||||
uint32_t *nmods, uint32_t cap);
|
||||
void vkb_emu_shader_install(vkb_srv_table *dev);
|
||||
VkShaderModule vkb_emu_shader_zero_base_instance(vkb_emu_device *e, VkDevice device, const VkPipelineShaderStageCreateInfo *vs);
|
||||
void vkb_emu_shader_uninstall(vkb_srv_table *dev);
|
||||
/* 1 = handled (the emulation recorded its own commands instead). */
|
||||
int vkb_emu_copy_image(vkb_emu_device *e, VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageCopy *regions);
|
||||
int vkb_emu_copy_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyImageInfo2 *info);
|
||||
int vkb_emu_copy_buffer_to_image(vkb_emu_device *e, VkCommandBuffer cb, VkBuffer src, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkBufferImageCopy *regions);
|
||||
int vkb_emu_copy_buffer_to_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyBufferToImageInfo2 *info);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,432 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* BC1-BC7 textures on a GPU without them (textureCompressionBC missing; DXVK and vkd3d-proton
|
||||
* refuse such a device). The image the app creates in a BC format is created decoded instead
|
||||
* (RGBA8 / R8 / RG8 / RGBA16F, see vkb_emu_formats.h), mutable so sRGB/SNORM views work, and
|
||||
* every upload - vkCmdCopyBufferToImage(2), how all BC data arrives - becomes a compute dispatch
|
||||
* that decodes the blocks from the source buffer straight into it (shaders/bc_decode.comp). The
|
||||
* app's compute bindings are restored afterwards (server_emu_cmdstate.c).
|
||||
*
|
||||
* Not emulated (logged once): reading a BC image back to a buffer, and copies between BC and
|
||||
* uncompressed images (they would need an encoder).
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
#include "vkb_emu_formats.h"
|
||||
#include "bc_spv.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
enum { FAM_BC1, FAM_BC2, FAM_BC3, FAM_BC4, FAM_BC5, FAM_BC6H, FAM_BC7, FAM_COUNT };
|
||||
|
||||
typedef struct bcn_state {
|
||||
VkDescriptorSetLayout dsl;
|
||||
VkPipelineLayout layout;
|
||||
VkPipeline pipes[FAM_COUNT];
|
||||
VkDeviceSize ssbo_align;
|
||||
int push; /* VK_KHR_push_descriptor; else per-command-buffer sets */
|
||||
pthread_mutex_t lock;
|
||||
} bcn_state;
|
||||
|
||||
typedef struct bcn_image {
|
||||
VkImageView views[16]; /* per mip: 2D array storage view of every layer */
|
||||
} bcn_image;
|
||||
|
||||
typedef struct pc_t {
|
||||
uint32_t src_word, row_blocks, layer_blocks, flags;
|
||||
int32_t dst_off[2];
|
||||
uint32_t extent[2];
|
||||
} pc_t;
|
||||
|
||||
static int family(VkFormat f)
|
||||
{
|
||||
switch (f) {
|
||||
case VK_FORMAT_BC1_RGB_UNORM_BLOCK: case VK_FORMAT_BC1_RGB_SRGB_BLOCK:
|
||||
case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: return FAM_BC1;
|
||||
case VK_FORMAT_BC2_UNORM_BLOCK: case VK_FORMAT_BC2_SRGB_BLOCK: return FAM_BC2;
|
||||
case VK_FORMAT_BC3_UNORM_BLOCK: case VK_FORMAT_BC3_SRGB_BLOCK: return FAM_BC3;
|
||||
case VK_FORMAT_BC4_UNORM_BLOCK: case VK_FORMAT_BC4_SNORM_BLOCK: return FAM_BC4;
|
||||
case VK_FORMAT_BC5_UNORM_BLOCK: case VK_FORMAT_BC5_SNORM_BLOCK: return FAM_BC5;
|
||||
case VK_FORMAT_BC6H_UFLOAT_BLOCK: case VK_FORMAT_BC6H_SFLOAT_BLOCK: return FAM_BC6H;
|
||||
default: return FAM_BC7;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t family_flags(VkFormat f)
|
||||
{
|
||||
uint32_t fl = 0;
|
||||
if (f == VK_FORMAT_BC1_RGB_UNORM_BLOCK || f == VK_FORMAT_BC1_RGB_SRGB_BLOCK) fl |= 1;
|
||||
if (f == VK_FORMAT_BC4_SNORM_BLOCK || f == VK_FORMAT_BC5_SNORM_BLOCK || f == VK_FORMAT_BC6H_SFLOAT_BLOCK) fl |= 2;
|
||||
return fl;
|
||||
}
|
||||
|
||||
int vkb_emu_bcn_supported(const vkb_dispatch *idt, VkPhysicalDevice pd)
|
||||
{
|
||||
VkPhysicalDeviceFeatures f;
|
||||
idt->vkGetPhysicalDeviceFeatures(pd, &f);
|
||||
if (!f.shaderStorageImageExtendedFormats) {
|
||||
VKB_WARN("BC emulation: the GPU lacks shaderStorageImageExtendedFormats");
|
||||
return 0;
|
||||
}
|
||||
static const VkFormat need[] = {VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8_UNORM, VK_FORMAT_R8G8_UNORM, VK_FORMAT_R16G16B16A16_SFLOAT};
|
||||
for (size_t i = 0; i < sizeof(need) / sizeof(need[0]); i++) {
|
||||
VkFormatProperties fp;
|
||||
idt->vkGetPhysicalDeviceFormatProperties(pd, need[i], &fp);
|
||||
if (!(fp.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) {
|
||||
VKB_WARN("BC emulation: format %d cannot be a storage image", need[i]);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
VkPhysicalDeviceProperties p;
|
||||
idt->vkGetPhysicalDeviceProperties(pd, &p);
|
||||
if (p.apiVersion >= VK_API_VERSION_1_4) return 1;
|
||||
uint32_t n = 0;
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, e);
|
||||
free(e);
|
||||
/* Without VK_KHR_push_descriptor (Mali-G720 on driver 44.1) the decoder binds ordinary sets. */
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Push descriptors for the decoder; without them, sets from the command buffer's scratch pools.
|
||||
* VKBRIDGE_FAKE_MISSING=...,push takes the second way on a GPU that has them (host tests). */
|
||||
static int has_push(vkb_srv_table *dev)
|
||||
{
|
||||
const char *fake = getenv("VKBRIDGE_FAKE_MISSING");
|
||||
if (fake && strstr(fake, "push")) return 0;
|
||||
VkPhysicalDeviceProperties p;
|
||||
dev->real.vkGetPhysicalDeviceProperties(dev->physical, &p);
|
||||
if (p.apiVersion >= VK_API_VERSION_1_4 && dev->api_version >= VK_API_VERSION_1_4) return dev->real.vkCmdPushDescriptorSet != NULL;
|
||||
uint32_t n = 0;
|
||||
dev->real.vkEnumerateDeviceExtensionProperties(dev->physical, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
dev->real.vkEnumerateDeviceExtensionProperties(dev->physical, NULL, &n, e);
|
||||
int ok = 0;
|
||||
for (uint32_t i = 0; i < n; i++) ok |= !strcmp(e[i].extensionName, "VK_KHR_push_descriptor");
|
||||
free(e);
|
||||
return ok && dev->real.vkCmdPushDescriptorSet != NULL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ images */
|
||||
|
||||
void vkb_emu_image_create_info(vkb_emu_device *e, VkImageCreateInfo *ci)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_BCN) || !vkb_is_bc(ci->format)) return;
|
||||
/* The image keeps the meaning of the app's format (sRGB, SNORM) so blits and copies convert as
|
||||
* they would; the decoder writes it through a view in the storage format (EXTENDED_USAGE lets
|
||||
* the image carry STORAGE although sRGB/SNORM formats cannot be stored to). */
|
||||
static __thread VkFormat list[2];
|
||||
VkFormat view = vkb_bc_view_format(ci->format), st = vkb_bc_storage_format(ci->format);
|
||||
list[0] = view;
|
||||
list[1] = st;
|
||||
ci->format = view;
|
||||
ci->flags &= ~(VkImageCreateFlags)VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT;
|
||||
ci->flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT;
|
||||
ci->usage |= VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
for (VkBaseOutStructure *b = (VkBaseOutStructure *)ci->pNext; b; b = b->pNext) {
|
||||
if (b->sType == VK_STRUCTURE_TYPE_IMAGE_FORMAT_LIST_CREATE_INFO) {
|
||||
VkImageFormatListCreateInfo *fl = (VkImageFormatListCreateInfo *)b;
|
||||
fl->viewFormatCount = view == st ? 1 : 2;
|
||||
fl->pViewFormats = list;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_image_release(vkb_emu_device *e, vkb_emu_image *img)
|
||||
{
|
||||
bcn_image *bi = img->emu;
|
||||
if (!bi) return;
|
||||
for (int i = 0; i < 16; i++)
|
||||
if (bi->views[i]) e->dev->real.vkDestroyImageView(e->dev->device, bi->views[i], NULL);
|
||||
free(bi);
|
||||
img->emu = NULL;
|
||||
}
|
||||
|
||||
VkFormat vkb_emu_bcn_view_format(vkb_emu_device *e, VkImage image, VkFormat requested)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_BCN)) return requested;
|
||||
if (vkb_is_bc(requested)) return vkb_bc_view_format(requested);
|
||||
vkb_emu_image *r = vkb_emu_find_image(e, image);
|
||||
if (r && vkb_is_bc(r->client_format)) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: an uncompressed view (format %d) of a BC image shows decoded texels (logged once)", requested);
|
||||
return vkb_bc_view_format(r->client_format);
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateImageView(VkDevice device, const VkImageViewCreateInfo *ci,
|
||||
const VkAllocationCallbacks *pAllocator, VkImageView *pView)
|
||||
{
|
||||
VkImageViewCreateInfo *v = (VkImageViewCreateInfo *)ci;
|
||||
v->format = vkb_emu_bcn_view_format(vkb_emu_cur(), ci->image, ci->format);
|
||||
return vkb_emu_real()->vkCreateImageView(device, v, pAllocator, pView);
|
||||
}
|
||||
|
||||
void vkb_emu_bcn_buffer_usage(vkb_emu_device *e, VkBufferCreateInfo *ci)
|
||||
{
|
||||
/* The decoder reads uploads as a storage buffer. */
|
||||
if ((e->flags & VKB_EMU_BCN) && (ci->usage & VK_BUFFER_USAGE_TRANSFER_SRC_BIT)) ci->usage |= VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ decoder */
|
||||
|
||||
static VkPipeline pipeline(vkb_emu_device *e, int fam)
|
||||
{
|
||||
bcn_state *s = e->bcn;
|
||||
if (s->pipes[fam]) return s->pipes[fam];
|
||||
pthread_mutex_lock(&s->lock);
|
||||
if (!s->pipes[fam]) {
|
||||
static const uint32_t *const code[FAM_COUNT] = {spv_bc1, spv_bc2, spv_bc3, spv_bc4, spv_bc5, spv_bc6h, spv_bc7};
|
||||
static const size_t size[FAM_COUNT] = {sizeof(spv_bc1), sizeof(spv_bc2), sizeof(spv_bc3), sizeof(spv_bc4),
|
||||
sizeof(spv_bc5), sizeof(spv_bc6h), sizeof(spv_bc7)};
|
||||
const vkb_dispatch *r = &e->dev->real;
|
||||
VkDevice d = e->dev->device;
|
||||
VkShaderModuleCreateInfo mci = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size[fam], code[fam]};
|
||||
VkShaderModule m;
|
||||
if (r->vkCreateShaderModule(d, &mci, NULL, &m) == VK_SUCCESS) {
|
||||
VkComputePipelineCreateInfo pci = {VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO};
|
||||
pci.stage = (VkPipelineShaderStageCreateInfo){VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0,
|
||||
VK_SHADER_STAGE_COMPUTE_BIT, m, "main", NULL};
|
||||
pci.layout = s->layout;
|
||||
if (r->vkCreateComputePipelines(d, VK_NULL_HANDLE, 1, &pci, NULL, &s->pipes[fam]) != VK_SUCCESS) {
|
||||
VKB_ERR("BC emulation: decoder pipeline %d failed to build", fam);
|
||||
s->pipes[fam] = VK_NULL_HANDLE;
|
||||
}
|
||||
r->vkDestroyShaderModule(d, m, NULL);
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return s->pipes[fam];
|
||||
}
|
||||
|
||||
static VkImageView storage_view(vkb_emu_device *e, vkb_emu_image *img, uint32_t mip)
|
||||
{
|
||||
if (mip >= 16) return VK_NULL_HANDLE;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
if (!img->emu) img->emu = calloc(1, sizeof(bcn_image));
|
||||
bcn_image *bi = img->emu;
|
||||
VkImageView v = bi->views[mip];
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
if (v) return v;
|
||||
VkImageViewUsageCreateInfo usage = {VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO, NULL, VK_IMAGE_USAGE_STORAGE_BIT};
|
||||
VkImageViewCreateInfo ci = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, &usage, 0, img->image, VK_IMAGE_VIEW_TYPE_2D_ARRAY,
|
||||
vkb_bc_storage_format(img->client_format),
|
||||
{0}, {VK_IMAGE_ASPECT_COLOR_BIT, mip, 1, 0, img->layers}};
|
||||
if (e->dev->real.vkCreateImageView(e->dev->device, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
if (bi->views[mip]) {
|
||||
e->dev->real.vkDestroyImageView(e->dev->device, v, NULL);
|
||||
v = bi->views[mip];
|
||||
} else {
|
||||
bi->views[mip] = v;
|
||||
}
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
return v;
|
||||
}
|
||||
|
||||
typedef struct region {
|
||||
VkDeviceSize offset;
|
||||
uint32_t row_length, image_height;
|
||||
VkImageSubresourceLayers sub;
|
||||
VkOffset3D ioff;
|
||||
VkExtent3D iext;
|
||||
} region;
|
||||
|
||||
static void decode(vkb_emu_device *e, VkCommandBuffer cb, VkBuffer src, vkb_emu_image *img, VkImageLayout layout,
|
||||
uint32_t n, const region *regs)
|
||||
{
|
||||
bcn_state *s = e->bcn;
|
||||
const vkb_dispatch *r = &e->dev->real;
|
||||
if (img->type != VK_IMAGE_TYPE_2D) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: uploads to 1D/3D BC images are not decoded (logged once)");
|
||||
return;
|
||||
}
|
||||
VkPipeline pipe = pipeline(e, family(img->client_format));
|
||||
if (!pipe) return;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
const region *g = ®s[i];
|
||||
VkImageView view = storage_view(e, img, g->sub.mipLevel);
|
||||
if (!view) continue;
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, g->sub.mipLevel, 1, g->sub.baseArrayLayer, g->sub.layerCount};
|
||||
VkMemoryBarrier mb = {VK_STRUCTURE_TYPE_MEMORY_BARRIER, NULL, VK_ACCESS_MEMORY_WRITE_BIT,
|
||||
VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT};
|
||||
VkImageMemoryBarrier ib = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT,
|
||||
layout, VK_IMAGE_LAYOUT_GENERAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, img->image, range};
|
||||
r->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
|
||||
0, 1, &mb, 0, NULL, 1, &ib);
|
||||
VkDeviceSize aligned = g->offset & ~(s->ssbo_align - 1);
|
||||
VkDescriptorBufferInfo bi = {src, aligned, VK_WHOLE_SIZE};
|
||||
VkDescriptorImageInfo ii = {VK_NULL_HANDLE, view, VK_IMAGE_LAYOUT_GENERAL};
|
||||
VkWriteDescriptorSet w[2] = {
|
||||
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, VK_NULL_HANDLE, 0, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, NULL, &bi, NULL},
|
||||
{VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, VK_NULL_HANDLE, 1, 0, 1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &ii, NULL, NULL}};
|
||||
r->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pipe);
|
||||
if (s->push) {
|
||||
r->vkCmdPushDescriptorSet(cb, VK_PIPELINE_BIND_POINT_COMPUTE, s->layout, 0, 2, w);
|
||||
} else {
|
||||
VkDescriptorSet set = vkb_emu_cb_scratch_set(e, cb, s->dsl);
|
||||
if (!set) {
|
||||
VKB_ONCE(VKB_LOG_ERROR, "BC emulation: no descriptor set for the decoder (logged once)");
|
||||
continue;
|
||||
}
|
||||
w[0].dstSet = w[1].dstSet = set;
|
||||
r->vkUpdateDescriptorSets(e->dev->device, 2, w, 0, NULL);
|
||||
r->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, s->layout, 0, 1, &set, 0, NULL);
|
||||
}
|
||||
uint32_t w_tex = g->row_length ? g->row_length : g->iext.width;
|
||||
uint32_t h_tex = g->image_height ? g->image_height : g->iext.height;
|
||||
pc_t pc;
|
||||
pc.src_word = (uint32_t)((g->offset - aligned) / 4);
|
||||
pc.row_blocks = (w_tex + 3) / 4;
|
||||
pc.layer_blocks = pc.row_blocks * ((h_tex + 3) / 4);
|
||||
pc.flags = family_flags(img->client_format) | (g->sub.baseArrayLayer << 8);
|
||||
pc.dst_off[0] = g->ioff.x;
|
||||
pc.dst_off[1] = g->ioff.y;
|
||||
pc.extent[0] = g->iext.width;
|
||||
pc.extent[1] = g->iext.height;
|
||||
r->vkCmdPushConstants(cb, s->layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc), &pc);
|
||||
uint32_t bw = (g->iext.width + 3) / 4, bh = (g->iext.height + 3) / 4;
|
||||
r->vkCmdDispatch(cb, (bw + 7) / 8, (bh + 7) / 8, g->sub.layerCount);
|
||||
ib.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT;
|
||||
ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT;
|
||||
ib.oldLayout = VK_IMAGE_LAYOUT_GENERAL;
|
||||
ib.newLayout = layout;
|
||||
r->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &ib);
|
||||
}
|
||||
vkb_emu_restore_compute(e, cb);
|
||||
}
|
||||
|
||||
static vkb_emu_image *bc_image(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_BCN)) return NULL;
|
||||
vkb_emu_image *r = vkb_emu_find_image(e, img);
|
||||
return r && vkb_is_bc(r->client_format) ? r : NULL;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_buffer_to_image(vkb_emu_device *e, VkCommandBuffer cb, VkBuffer src, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkBufferImageCopy *regions)
|
||||
{
|
||||
vkb_emu_image *img = bc_image(e, dst);
|
||||
if (!img) return 0;
|
||||
region *g = malloc((n ? n : 1) * sizeof(*g));
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
g[i] = (region){regions[i].bufferOffset, regions[i].bufferRowLength, regions[i].bufferImageHeight, regions[i].imageSubresource,
|
||||
regions[i].imageOffset, regions[i].imageExtent};
|
||||
decode(e, cb, src, img, dl, n, g);
|
||||
free(g);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_buffer_to_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyBufferToImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_image *img = bc_image(e, info->dstImage);
|
||||
if (!img) return 0;
|
||||
region *g = malloc((info->regionCount ? info->regionCount : 1) * sizeof(*g));
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
const VkBufferImageCopy2 *r = &info->pRegions[i];
|
||||
g[i] = (region){r->bufferOffset, r->bufferRowLength, r->bufferImageHeight, r->imageSubresource, r->imageOffset, r->imageExtent};
|
||||
}
|
||||
decode(e, cb, info->srcBuffer, img, info->dstImageLayout, info->regionCount, g);
|
||||
free(g);
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Copies between BC images copy decoded texels; a region may run past a small mip's edge (whole
|
||||
* blocks), which the decoded image does not have. */
|
||||
static void clamp_region(const vkb_emu_image *s, const vkb_emu_image *d, const VkImageSubresourceLayers *ss,
|
||||
const VkImageSubresourceLayers *ds, const VkOffset3D *so, const VkOffset3D *dof, VkExtent3D *ext)
|
||||
{
|
||||
uint32_t sw = s->extent.width >> ss->mipLevel, sh = s->extent.height >> ss->mipLevel;
|
||||
uint32_t dw = d->extent.width >> ds->mipLevel, dh = d->extent.height >> ds->mipLevel;
|
||||
if (!sw) sw = 1;
|
||||
if (!sh) sh = 1;
|
||||
if (!dw) dw = 1;
|
||||
if (!dh) dh = 1;
|
||||
if ((uint32_t)so->x + ext->width > sw) ext->width = sw > (uint32_t)so->x ? sw - (uint32_t)so->x : 0;
|
||||
if ((uint32_t)so->y + ext->height > sh) ext->height = sh > (uint32_t)so->y ? sh - (uint32_t)so->y : 0;
|
||||
if ((uint32_t)dof->x + ext->width > dw) ext->width = dw > (uint32_t)dof->x ? dw - (uint32_t)dof->x : 0;
|
||||
if ((uint32_t)dof->y + ext->height > dh) ext->height = dh > (uint32_t)dof->y ? dh - (uint32_t)dof->y : 0;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_image(vkb_emu_device *e, VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkImageCopy *regions)
|
||||
{
|
||||
vkb_emu_image *s = bc_image(e, src), *d = bc_image(e, dst);
|
||||
if (!s && !d) return 0;
|
||||
if (!s || !d || vkb_bc_storage_format(s->client_format) != vkb_bc_storage_format(d->client_format)) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: a copy between a BC image and another format is skipped (logged once)");
|
||||
return 1;
|
||||
}
|
||||
VkImageCopy *c = (VkImageCopy *)regions;
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
clamp_region(s, d, &c[i].srcSubresource, &c[i].dstSubresource, &c[i].srcOffset, &c[i].dstOffset, &c[i].extent);
|
||||
e->dev->real.vkCmdCopyImage(cb, src, sl, dst, dl, n, regions);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int vkb_emu_copy_image2(vkb_emu_device *e, VkCommandBuffer cb, const VkCopyImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_image *s = bc_image(e, info->srcImage), *d = bc_image(e, info->dstImage);
|
||||
if (!s && !d) return 0;
|
||||
if (!s || !d || vkb_bc_storage_format(s->client_format) != vkb_bc_storage_format(d->client_format)) {
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: a copy between a BC image and another format is skipped (logged once)");
|
||||
return 1;
|
||||
}
|
||||
VkImageCopy2 *c = (VkImageCopy2 *)info->pRegions;
|
||||
for (uint32_t i = 0; i < info->regionCount; i++)
|
||||
clamp_region(s, d, &c[i].srcSubresource, &c[i].dstSubresource, &c[i].srcOffset, &c[i].dstOffset, &c[i].extent);
|
||||
e->dev->real.vkCmdCopyImage2(cb, info);
|
||||
return 1;
|
||||
}
|
||||
|
||||
int vkb_emu_bcn_blocks_readback(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
if (!bc_image(e, img)) return 0;
|
||||
VKB_ONCE(VKB_LOG_WARN, "BC emulation: reading a BC image back to a buffer is not supported (logged once)");
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ install */
|
||||
|
||||
void vkb_emu_bcn_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
if (!(e->flags & VKB_EMU_BCN)) return;
|
||||
bcn_state *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
VkPhysicalDeviceProperties p;
|
||||
dev->real.vkGetPhysicalDeviceProperties(dev->physical, &p);
|
||||
s->ssbo_align = p.limits.minStorageBufferOffsetAlignment ? p.limits.minStorageBufferOffsetAlignment : 4;
|
||||
VkDescriptorSetLayoutBinding b[2] = {{0, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL},
|
||||
{1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL}};
|
||||
s->push = has_push(dev);
|
||||
VKB_INFO("BC emulation: decoder binds with %s", s->push ? "push descriptors" : "descriptor sets (no VK_KHR_push_descriptor)");
|
||||
VkDescriptorSetLayoutCreateInfo dci = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL,
|
||||
s->push ? VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT : 0, 2, b};
|
||||
VkPushConstantRange pr = {VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(pc_t)};
|
||||
if (dev->real.vkCreateDescriptorSetLayout(dev->device, &dci, NULL, &s->dsl) != VK_SUCCESS) {
|
||||
VKB_ERR("BC emulation: cannot create the decoder's descriptor layout");
|
||||
free(s);
|
||||
e->flags &= ~VKB_EMU_BCN;
|
||||
return;
|
||||
}
|
||||
VkPipelineLayoutCreateInfo plci = {VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 1, &s->dsl, 1, &pr};
|
||||
dev->real.vkCreatePipelineLayout(dev->device, &plci, NULL, &s->layout);
|
||||
e->bcn = s;
|
||||
dev->dt.vkCreateImageView = emu_CreateImageView;
|
||||
}
|
||||
|
||||
void vkb_emu_bcn_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
bcn_state *s = dev->emu->bcn;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < FAM_COUNT; i++)
|
||||
if (s->pipes[i]) dev->real.vkDestroyPipeline(dev->device, s->pipes[i], NULL);
|
||||
dev->real.vkDestroyPipelineLayout(dev->device, s->layout, NULL);
|
||||
dev->real.vkDestroyDescriptorSetLayout(dev->device, s->dsl, NULL);
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->bcn = NULL;
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* What an app has bound in a command buffer, for emulations that record commands of their own
|
||||
* into it (the BCn decoder's dispatches) and must leave the app's state as it was: the compute
|
||||
* pipeline, compute descriptor sets, push constants and push descriptors. Bind calls are kept as
|
||||
* they were made (a later call that covers an earlier one replaces it) and replayed in order.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct bind_sets {
|
||||
VkPipelineLayout layout;
|
||||
uint32_t first, count, ndyn;
|
||||
VkDescriptorSet sets[32];
|
||||
uint32_t dyn[64];
|
||||
} bind_sets;
|
||||
|
||||
typedef struct push_consts {
|
||||
VkPipelineLayout layout;
|
||||
VkShaderStageFlags stages;
|
||||
uint32_t offset, size;
|
||||
uint8_t data[256];
|
||||
} push_consts;
|
||||
|
||||
typedef struct push_tmpl {
|
||||
VkDescriptorUpdateTemplate tmpl;
|
||||
VkPipelineLayout layout;
|
||||
uint32_t set;
|
||||
void *data;
|
||||
size_t size;
|
||||
} push_tmpl;
|
||||
|
||||
typedef struct cb_state {
|
||||
VkCommandBuffer cb;
|
||||
VkPipeline compute_pipeline;
|
||||
bind_sets *sets;
|
||||
uint32_t nsets, capsets;
|
||||
push_consts *pcs;
|
||||
uint32_t npcs, cappcs;
|
||||
push_tmpl *pts;
|
||||
uint32_t npts, cappts;
|
||||
void *gfx; /* graphics-side state (divisor emulation) */
|
||||
/* Descriptor sets emulations record with (no push descriptors), alive until the next begin. */
|
||||
VkDescriptorPool *scratch;
|
||||
uint32_t nscratch, cur_scratch, used_scratch;
|
||||
struct cb_state *next;
|
||||
} cb_state;
|
||||
|
||||
#define CB_BUCKETS 512
|
||||
#define SCRATCH_SETS 64
|
||||
typedef struct cmdstate {
|
||||
pthread_mutex_t lock;
|
||||
cb_state *b[CB_BUCKETS];
|
||||
} cmdstate;
|
||||
|
||||
/* Packed size of the template data being pushed (set by the raw push handler, server_misc.c). */
|
||||
__thread size_t vkb_emu_push_size;
|
||||
|
||||
static cmdstate *g_states_for(vkb_emu_device *e) { return (cmdstate *)e->cmdstate; }
|
||||
|
||||
static unsigned ch(VkCommandBuffer cb)
|
||||
{
|
||||
uint64_t k = (uint64_t)(uintptr_t)cb;
|
||||
k ^= k >> 30;
|
||||
k *= 0xbf58476d1ce4e5b9ull;
|
||||
return (unsigned)(k >> 55) & (CB_BUCKETS - 1);
|
||||
}
|
||||
|
||||
static cb_state *get(vkb_emu_device *e, VkCommandBuffer cb)
|
||||
{
|
||||
cmdstate *s = g_states_for(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
cb_state *c = s->b[ch(cb)];
|
||||
while (c && c->cb != cb) c = c->next;
|
||||
if (!c) {
|
||||
c = calloc(1, sizeof(*c));
|
||||
c->cb = cb;
|
||||
c->next = s->b[ch(cb)];
|
||||
s->b[ch(cb)] = c;
|
||||
}
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return c;
|
||||
}
|
||||
|
||||
/* A descriptor set of layout `dsl` (storage buffers and images only) for a command the emulation
|
||||
* records into cb; it lives until cb is begun again, when the app has seen the work finish. */
|
||||
VkDescriptorSet vkb_emu_cb_scratch_set(vkb_emu_device *e, VkCommandBuffer cb, VkDescriptorSetLayout dsl)
|
||||
{
|
||||
cb_state *c = get(e, cb);
|
||||
const vkb_dispatch *r = &e->dev->real;
|
||||
for (;;) {
|
||||
if (c->cur_scratch >= c->nscratch) {
|
||||
VkDescriptorPoolSize sizes[2] = {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, SCRATCH_SETS * 2},
|
||||
{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, SCRATCH_SETS * 2}};
|
||||
VkDescriptorPoolCreateInfo pci = {VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, NULL, 0, SCRATCH_SETS, 2, sizes};
|
||||
VkDescriptorPool pool;
|
||||
VkDescriptorPool *np = realloc(c->scratch, (c->nscratch + 1) * sizeof(*np));
|
||||
if (!np) return VK_NULL_HANDLE;
|
||||
c->scratch = np;
|
||||
if (r->vkCreateDescriptorPool(e->dev->device, &pci, NULL, &pool) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
c->scratch[c->nscratch++] = pool;
|
||||
}
|
||||
if (c->used_scratch < SCRATCH_SETS) {
|
||||
VkDescriptorSetAllocateInfo ai = {VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, c->scratch[c->cur_scratch], 1, &dsl};
|
||||
VkDescriptorSet set;
|
||||
if (r->vkAllocateDescriptorSets(e->dev->device, &ai, &set) == VK_SUCCESS) {
|
||||
c->used_scratch++;
|
||||
return set;
|
||||
}
|
||||
}
|
||||
c->cur_scratch++;
|
||||
c->used_scratch = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void *vkb_emu_cb_gfx(vkb_emu_device *e, VkCommandBuffer cb, size_t size)
|
||||
{
|
||||
cb_state *c = get(e, cb);
|
||||
if (!c->gfx) c->gfx = calloc(1, size);
|
||||
return c->gfx;
|
||||
}
|
||||
|
||||
static void reset(vkb_emu_device *e, cb_state *c)
|
||||
{
|
||||
for (uint32_t i = 0; i < c->nscratch && i <= c->cur_scratch; i++)
|
||||
e->dev->real.vkResetDescriptorPool(e->dev->device, c->scratch[i], 0);
|
||||
c->cur_scratch = 0;
|
||||
c->used_scratch = 0;
|
||||
c->compute_pipeline = VK_NULL_HANDLE;
|
||||
c->nsets = 0;
|
||||
c->npcs = 0;
|
||||
for (uint32_t i = 0; i < c->npts; i++) free(c->pts[i].data);
|
||||
c->npts = 0;
|
||||
vkb_emu_gfx_reset(c->gfx);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ wrappers */
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_BeginCommandBuffer(VkCommandBuffer cb, const VkCommandBufferBeginInfo *info)
|
||||
{
|
||||
reset(vkb_emu_cur(), get(vkb_emu_cur(), cb));
|
||||
return vkb_emu_real()->vkBeginCommandBuffer(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindPipeline(VkCommandBuffer cb, VkPipelineBindPoint bp, VkPipeline p)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
if (bp == VK_PIPELINE_BIND_POINT_COMPUTE) get(e, cb)->compute_pipeline = p;
|
||||
if (bp == VK_PIPELINE_BIND_POINT_GRAPHICS) vkb_emu_gfx_bind_pipeline(e, cb, p);
|
||||
vkb_emu_real()->vkCmdBindPipeline(cb, bp, p);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindDescriptorSets(VkCommandBuffer cb, VkPipelineBindPoint bp, VkPipelineLayout layout,
|
||||
uint32_t first, uint32_t count, const VkDescriptorSet *sets,
|
||||
uint32_t ndyn, const uint32_t *dyn)
|
||||
{
|
||||
if (bp == VK_PIPELINE_BIND_POINT_COMPUTE && count <= 32 && ndyn <= 64) {
|
||||
cb_state *c = get(vkb_emu_cur(), cb);
|
||||
/* Drop earlier calls this one covers completely. */
|
||||
uint32_t k = 0;
|
||||
for (uint32_t i = 0; i < c->nsets; i++) {
|
||||
bind_sets *b = &c->sets[i];
|
||||
if (b->first >= first && b->first + b->count <= first + count) continue;
|
||||
c->sets[k++] = *b;
|
||||
}
|
||||
c->nsets = k;
|
||||
if (c->nsets == c->capsets) {
|
||||
c->capsets = c->capsets ? c->capsets * 2 : 8;
|
||||
c->sets = realloc(c->sets, c->capsets * sizeof(*c->sets));
|
||||
}
|
||||
bind_sets *b = &c->sets[c->nsets++];
|
||||
b->layout = layout;
|
||||
b->first = first;
|
||||
b->count = count;
|
||||
b->ndyn = ndyn;
|
||||
memcpy(b->sets, sets, count * sizeof(*sets));
|
||||
if (ndyn) memcpy(b->dyn, dyn, ndyn * sizeof(*dyn));
|
||||
}
|
||||
vkb_emu_real()->vkCmdBindDescriptorSets(cb, bp, layout, first, count, sets, ndyn, dyn);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdPushConstants(VkCommandBuffer cb, VkPipelineLayout layout, VkShaderStageFlags stages,
|
||||
uint32_t offset, uint32_t size, const void *data)
|
||||
{
|
||||
if ((stages & VK_SHADER_STAGE_COMPUTE_BIT) && offset + size <= 256) {
|
||||
cb_state *c = get(vkb_emu_cur(), cb);
|
||||
uint32_t k = 0;
|
||||
for (uint32_t i = 0; i < c->npcs; i++) {
|
||||
push_consts *p = &c->pcs[i];
|
||||
if (p->offset >= offset && p->offset + p->size <= offset + size && p->stages == stages) continue;
|
||||
c->pcs[k++] = *p;
|
||||
}
|
||||
c->npcs = k;
|
||||
if (c->npcs == c->cappcs) {
|
||||
c->cappcs = c->cappcs ? c->cappcs * 2 : 8;
|
||||
c->pcs = realloc(c->pcs, c->cappcs * sizeof(*c->pcs));
|
||||
}
|
||||
push_consts *p = &c->pcs[c->npcs++];
|
||||
p->layout = layout;
|
||||
p->stages = stages;
|
||||
p->offset = offset;
|
||||
p->size = size;
|
||||
memcpy(p->data + offset, data, size);
|
||||
}
|
||||
vkb_emu_real()->vkCmdPushConstants(cb, layout, stages, offset, size, data);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdPushDescriptorSetWithTemplate(VkCommandBuffer cb, VkDescriptorUpdateTemplate tmpl,
|
||||
VkPipelineLayout layout, uint32_t set, const void *data)
|
||||
{
|
||||
/* Only the template's bind point decides; recording it for both costs nothing when replayed
|
||||
* into the same bind point it was made for. Sizes are unknown here: the bridge's raw template
|
||||
* path hands over the packed size (vkb_emu_push_size). */
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
cb_state *c = get(e, cb);
|
||||
size_t size = vkb_emu_push_size;
|
||||
if (size && size < (1u << 20)) {
|
||||
if (c->npts == c->cappts) {
|
||||
c->cappts = c->cappts ? c->cappts * 2 : 4;
|
||||
c->pts = realloc(c->pts, c->cappts * sizeof(*c->pts));
|
||||
}
|
||||
push_tmpl *p = &c->pts[c->npts++];
|
||||
p->tmpl = tmpl;
|
||||
p->layout = layout;
|
||||
p->set = set;
|
||||
p->size = size;
|
||||
p->data = malloc(size);
|
||||
memcpy(p->data, data, size);
|
||||
}
|
||||
vkb_emu_real()->vkCmdPushDescriptorSetWithTemplate(cb, tmpl, layout, set, data);
|
||||
}
|
||||
|
||||
/* Puts back what the app had bound for compute after an emulation recorded its own dispatch. */
|
||||
void vkb_emu_restore_compute(vkb_emu_device *e, VkCommandBuffer cb)
|
||||
{
|
||||
cb_state *c = get(e, cb);
|
||||
const vkb_dispatch *r = vkb_emu_real();
|
||||
if (c->compute_pipeline) r->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, c->compute_pipeline);
|
||||
for (uint32_t i = 0; i < c->nsets; i++) {
|
||||
bind_sets *b = &c->sets[i];
|
||||
r->vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, b->layout, b->first, b->count, b->sets, b->ndyn, b->dyn);
|
||||
}
|
||||
for (uint32_t i = 0; i < c->npts; i++) {
|
||||
push_tmpl *p = &c->pts[i];
|
||||
r->vkCmdPushDescriptorSetWithTemplate(cb, p->tmpl, p->layout, p->set, p->data);
|
||||
}
|
||||
for (uint32_t i = 0; i < c->npcs; i++) {
|
||||
push_consts *p = &c->pcs[i];
|
||||
r->vkCmdPushConstants(cb, p->layout, p->stages, p->offset, p->size, p->data + p->offset);
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_cmdstate_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
cmdstate *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
e->cmdstate = s;
|
||||
dev->dt.vkBeginCommandBuffer = emu_BeginCommandBuffer;
|
||||
dev->dt.vkCmdBindPipeline = emu_CmdBindPipeline;
|
||||
dev->dt.vkCmdBindDescriptorSets = emu_CmdBindDescriptorSets;
|
||||
dev->dt.vkCmdPushConstants = emu_CmdPushConstants;
|
||||
if (dev->real.vkCmdPushDescriptorSetWithTemplate) dev->dt.vkCmdPushDescriptorSetWithTemplate = emu_CmdPushDescriptorSetWithTemplate;
|
||||
}
|
||||
|
||||
void vkb_emu_cmdstate_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
cmdstate *s = dev->emu->cmdstate;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < CB_BUCKETS; i++) {
|
||||
while (s->b[i]) {
|
||||
cb_state *c = s->b[i];
|
||||
s->b[i] = c->next;
|
||||
reset(dev->emu, c);
|
||||
for (uint32_t j = 0; j < c->nscratch; j++) dev->real.vkDestroyDescriptorPool(dev->device, c->scratch[j], NULL);
|
||||
free(c->scratch);
|
||||
free(c->sets);
|
||||
free(c->pcs);
|
||||
free(c->pts);
|
||||
vkb_emu_gfx_free(c->gfx);
|
||||
free(c);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->cmdstate = NULL;
|
||||
}
|
||||
@@ -0,0 +1,454 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Vertex attribute divisor (VK_EXT/KHR_vertex_attribute_divisor) on a GPU without it.
|
||||
*
|
||||
* A binding with divisor d != 1 fetches element firstInstance + i / d for instance i (d = 0: always
|
||||
* firstInstance). Emulated by giving such bindings a stride of 0 - every instance reads the same
|
||||
* element - and rebinding the buffer at that element before each draw. With d > 1 the draw is
|
||||
* split into runs of instances that share elements; each run keeps its own firstInstance, so
|
||||
* gl_InstanceIndex and every ordinary instance-rate attribute stay exactly as they were.
|
||||
* Indirect draws cannot be split on the CPU: divisor-0 bindings use element 0 there, d > 1 is
|
||||
* approximated the same way (logged once).
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define MAX_BIND 32
|
||||
|
||||
typedef struct div_info {
|
||||
uint32_t mask; /* bindings emulated */
|
||||
uint32_t divisor[MAX_BIND];
|
||||
uint32_t stride[MAX_BIND]; /* the app's stride (baked pipelines) */
|
||||
int dynamic_stride; /* the pipeline takes strides at bind time */
|
||||
int dynamic_input; /* the pipeline takes vertex input at record time */
|
||||
int split; /* some divisor > 1: draws are split */
|
||||
VkPipeline zero_base; /* variant whose vertex shader reads BaseInstance as 0 */
|
||||
VkShaderModule zero_vs; /* its vertex shader, between creation steps */
|
||||
uint32_t vs_stage;
|
||||
} div_info;
|
||||
|
||||
typedef struct pipe_rec {
|
||||
VkPipeline p;
|
||||
div_info info;
|
||||
struct pipe_rec *next;
|
||||
} pipe_rec;
|
||||
|
||||
typedef struct gfx_state {
|
||||
VkPipeline pipeline; /* bound graphics pipeline */
|
||||
div_info pipe; /* the bound pipeline's */
|
||||
div_info dyn; /* from vkCmdSetVertexInputEXT */
|
||||
int use_dyn;
|
||||
VkBuffer buf[MAX_BIND];
|
||||
VkDeviceSize off[MAX_BIND], size[MAX_BIND], stride[MAX_BIND];
|
||||
uint32_t bound; /* slots the app bound */
|
||||
uint32_t tampered; /* slots we rebound */
|
||||
} gfx_state;
|
||||
|
||||
typedef struct div_state {
|
||||
pthread_mutex_t lock;
|
||||
pipe_rec *b[256];
|
||||
} div_state;
|
||||
|
||||
static div_state *dstate(vkb_emu_device *e) { return e->divisor; }
|
||||
|
||||
static unsigned ph(VkPipeline p)
|
||||
{
|
||||
uint64_t k = (uint64_t)p;
|
||||
k ^= k >> 33;
|
||||
k *= 0xff51afd7ed558ccdull;
|
||||
return (unsigned)(k >> 56);
|
||||
}
|
||||
|
||||
static const div_info *find_pipe(vkb_emu_device *e, VkPipeline p)
|
||||
{
|
||||
div_state *s = dstate(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
pipe_rec *r = s->b[ph(p)];
|
||||
while (r && r->p != p) r = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return r ? &r->info : NULL;
|
||||
}
|
||||
|
||||
static void store_pipe(vkb_emu_device *e, VkPipeline p, const div_info *info)
|
||||
{
|
||||
div_state *s = dstate(e);
|
||||
pipe_rec *r = calloc(1, sizeof(*r));
|
||||
r->p = p;
|
||||
r->info = *info;
|
||||
pthread_mutex_lock(&s->lock);
|
||||
r->next = s->b[ph(p)];
|
||||
s->b[ph(p)] = r;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
}
|
||||
|
||||
static void drop_pipe(vkb_emu_device *e, VkPipeline p)
|
||||
{
|
||||
div_state *s = dstate(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
pipe_rec **pp = &s->b[ph(p)];
|
||||
while (*pp && (*pp)->p != p) pp = &(*pp)->next;
|
||||
pipe_rec *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
if (r && r->info.zero_base) e->dev->real.vkDestroyPipeline(e->dev->device, r->info.zero_base, NULL);
|
||||
free(r);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pipelines */
|
||||
|
||||
static int has_dynamic(const VkGraphicsPipelineCreateInfo *ci, VkDynamicState d)
|
||||
{
|
||||
if (!ci->pDynamicState) return 0;
|
||||
for (uint32_t i = 0; i < ci->pDynamicState->dynamicStateCount; i++)
|
||||
if (ci->pDynamicState->pDynamicStates[i] == d) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Strips the divisor state of one create info; returns what the pipeline needs at draw time. */
|
||||
void vkb_emu_divisor_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, div_info *out)
|
||||
{
|
||||
memset(out, 0, sizeof(*out));
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
out->dynamic_stride = has_dynamic(ci, VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE);
|
||||
out->dynamic_input = has_dynamic(ci, VK_DYNAMIC_STATE_VERTEX_INPUT_EXT);
|
||||
/* Pieces linked from libraries bring their own records. */
|
||||
for (const VkBaseInStructure *b = ci->pNext; b; b = b->pNext) {
|
||||
if (b->sType != VK_STRUCTURE_TYPE_PIPELINE_LIBRARY_CREATE_INFO_KHR) continue;
|
||||
const VkPipelineLibraryCreateInfoKHR *l = (const void *)b;
|
||||
for (uint32_t i = 0; i < l->libraryCount; i++) {
|
||||
const div_info *li = find_pipe(e, l->pLibraries[i]);
|
||||
if (!li || !li->mask) continue;
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++)
|
||||
if (li->mask & (1u << k)) {
|
||||
out->mask |= 1u << k;
|
||||
out->divisor[k] = li->divisor[k];
|
||||
out->stride[k] = li->stride[k];
|
||||
if (li->divisor[k] > 1) out->split = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
VkPipelineVertexInputStateCreateInfo *vi = (VkPipelineVertexInputStateCreateInfo *)ci->pVertexInputState;
|
||||
if (!vi || out->dynamic_input) return;
|
||||
VkPipelineVertexInputDivisorStateCreateInfo *d =
|
||||
vkb_emu_chain_take(vi, VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_DIVISOR_STATE_CREATE_INFO);
|
||||
if (!d) return;
|
||||
VkVertexInputBindingDescription *bd = (VkVertexInputBindingDescription *)vi->pVertexBindingDescriptions;
|
||||
for (uint32_t i = 0; i < d->vertexBindingDivisorCount; i++) {
|
||||
uint32_t b = d->pVertexBindingDivisors[i].binding, div = d->pVertexBindingDivisors[i].divisor;
|
||||
if (div == 1 || b >= MAX_BIND) continue;
|
||||
for (uint32_t k = 0; k < vi->vertexBindingDescriptionCount; k++) {
|
||||
if (bd[k].binding != b) continue;
|
||||
out->mask |= 1u << b;
|
||||
out->divisor[b] = div;
|
||||
out->stride[b] = bd[k].stride;
|
||||
if (div > 1) out->split = 1;
|
||||
bd[k].stride = 0;
|
||||
}
|
||||
}
|
||||
/* The vertex shader's SPIR-V is still at hand here (it may be inline). */
|
||||
if (out->split && ci->pStages) {
|
||||
for (uint32_t st = 0; st < ci->stageCount; st++) {
|
||||
if (ci->pStages[st].stage != VK_SHADER_STAGE_VERTEX_BIT) continue;
|
||||
out->zero_vs = vkb_emu_shader_zero_base_instance(e, device, &ci->pStages[st]);
|
||||
out->vs_stage = st;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_emu_divisor_created(vkb_emu_device *e, VkDevice device, VkPipelineCache cache, const VkGraphicsPipelineCreateInfo *ci,
|
||||
VkPipeline p, div_info *info)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
if (!p) {
|
||||
if (info->zero_vs) vkb_emu_real()->vkDestroyShaderModule(device, info->zero_vs, NULL);
|
||||
return;
|
||||
}
|
||||
if (info->zero_vs) {
|
||||
/* Split draws move BaseInstance: a variant that reads it as 0 serves the usual
|
||||
* firstInstance = 0 draws exactly. */
|
||||
VkPipelineShaderStageCreateInfo *st = malloc(ci->stageCount * sizeof(*st));
|
||||
memcpy(st, ci->pStages, ci->stageCount * sizeof(*st));
|
||||
st[info->vs_stage].module = info->zero_vs;
|
||||
st[info->vs_stage].pNext = NULL;
|
||||
VkGraphicsPipelineCreateInfo v = *ci;
|
||||
v.pStages = st;
|
||||
if (vkb_emu_real()->vkCreateGraphicsPipelines(device, cache, 1, &v, NULL, &info->zero_base) != VK_SUCCESS)
|
||||
info->zero_base = VK_NULL_HANDLE;
|
||||
vkb_emu_real()->vkDestroyShaderModule(device, info->zero_vs, NULL);
|
||||
info->zero_vs = VK_NULL_HANDLE;
|
||||
free(st);
|
||||
}
|
||||
if (info->mask || info->dynamic_input || info->dynamic_stride) store_pipe(e, p, info);
|
||||
if (info->mask)
|
||||
VKB_DBG("divisor: pipeline %p emulates bindings 0x%x (dynamic stride %d, dynamic input %d, split %d, variant %p)", (void *)p,
|
||||
info->mask, info->dynamic_stride, info->dynamic_input, info->split, (void *)info->zero_base);
|
||||
}
|
||||
|
||||
size_t vkb_emu_divisor_info_size(void) { return sizeof(div_info); }
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyPipeline(VkDevice device, VkPipeline p, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
if (p) drop_pipe(vkb_emu_cur(), p);
|
||||
vkb_emu_real()->vkDestroyPipeline(device, p, pAllocator);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ command buffers */
|
||||
|
||||
static gfx_state *gfx(vkb_emu_device *e, VkCommandBuffer cb) { return vkb_emu_cb_gfx(e, cb, sizeof(gfx_state)); }
|
||||
|
||||
void vkb_emu_gfx_reset(void *g)
|
||||
{
|
||||
if (g) memset(g, 0, sizeof(gfx_state));
|
||||
}
|
||||
|
||||
void vkb_emu_gfx_free(void *g) { free(g); }
|
||||
|
||||
void vkb_emu_gfx_bind_pipeline(vkb_emu_device *e, VkCommandBuffer cb, VkPipeline p)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
gfx_state *g = gfx(e, cb);
|
||||
g->pipeline = p;
|
||||
const div_info *i = find_pipe(e, p);
|
||||
if (i) g->pipe = *i;
|
||||
else memset(&g->pipe, 0, sizeof(g->pipe));
|
||||
g->use_dyn = g->pipe.dynamic_input;
|
||||
}
|
||||
|
||||
static void record_bind(gfx_state *g, uint32_t first, uint32_t n, const VkBuffer *b, const VkDeviceSize *o, const VkDeviceSize *s,
|
||||
const VkDeviceSize *st)
|
||||
{
|
||||
for (uint32_t i = 0; i < n && first + i < MAX_BIND; i++) {
|
||||
uint32_t k = first + i;
|
||||
g->buf[k] = b[i];
|
||||
g->off[k] = o[i];
|
||||
g->size[k] = s ? s[i] : VK_WHOLE_SIZE;
|
||||
if (st) g->stride[k] = st[i];
|
||||
g->bound |= 1u << k;
|
||||
g->tampered &= ~(1u << k);
|
||||
}
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindVertexBuffers(VkCommandBuffer cb, uint32_t first, uint32_t n, const VkBuffer *b,
|
||||
const VkDeviceSize *o)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
record_bind(gfx(e, cb), first, n, b, o, NULL, NULL);
|
||||
vkb_emu_real()->vkCmdBindVertexBuffers(cb, first, n, b, o);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindVertexBuffers2(VkCommandBuffer cb, uint32_t first, uint32_t n, const VkBuffer *b,
|
||||
const VkDeviceSize *o, const VkDeviceSize *s, const VkDeviceSize *st)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
record_bind(gfx(e, cb), first, n, b, o, s, st);
|
||||
vkb_emu_real()->vkCmdBindVertexBuffers2(cb, first, n, b, o, s, st);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdSetVertexInputEXT(VkCommandBuffer cb, uint32_t nb, const VkVertexInputBindingDescription2EXT *bd,
|
||||
uint32_t na, const VkVertexInputAttributeDescription2EXT *ad)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
gfx_state *g = gfx(e, cb);
|
||||
memset(&g->dyn, 0, sizeof(g->dyn));
|
||||
g->dyn.dynamic_stride = 1;
|
||||
g->dyn.dynamic_input = 1;
|
||||
VkVertexInputBindingDescription2EXT *w = (VkVertexInputBindingDescription2EXT *)bd;
|
||||
for (uint32_t i = 0; i < nb; i++) {
|
||||
uint32_t b = w[i].binding;
|
||||
if (w[i].inputRate != VK_VERTEX_INPUT_RATE_INSTANCE || w[i].divisor == 1 || b >= MAX_BIND) continue;
|
||||
g->dyn.mask |= 1u << b;
|
||||
g->dyn.divisor[b] = w[i].divisor;
|
||||
g->dyn.stride[b] = w[i].stride;
|
||||
g->stride[b] = w[i].stride;
|
||||
w[i].stride = 0;
|
||||
w[i].divisor = 1;
|
||||
}
|
||||
vkb_emu_real()->vkCmdSetVertexInputEXT(cb, nb, bd, na, ad);
|
||||
}
|
||||
|
||||
/* Rebinds the emulated bindings for instances starting at `inst` (relative to the draw), and puts
|
||||
* back any slot we changed that the current pipeline does not emulate. */
|
||||
static void prepare(vkb_emu_device *e, VkCommandBuffer cb, gfx_state *g, const div_info *di, uint32_t first_instance, uint32_t inst)
|
||||
{
|
||||
const vkb_dispatch *r = vkb_emu_real();
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++) {
|
||||
uint32_t bit = 1u << k;
|
||||
if (!(g->bound & bit)) continue;
|
||||
if (di->mask & bit) {
|
||||
uint32_t d = di->divisor[k];
|
||||
VkDeviceSize stride = di->dynamic_input ? g->dyn.stride[k] : (di->dynamic_stride ? g->stride[k] : di->stride[k]);
|
||||
VkDeviceSize elem = (VkDeviceSize)first_instance + (d ? inst / d : 0);
|
||||
VkDeviceSize off = g->off[k] + elem * stride;
|
||||
if (di->dynamic_stride || di->dynamic_input) {
|
||||
VkDeviceSize size = g->size[k] == VK_WHOLE_SIZE ? VK_WHOLE_SIZE : (g->size[k] > elem * stride ? g->size[k] - elem * stride : 0);
|
||||
VkDeviceSize zero = 0;
|
||||
r->vkCmdBindVertexBuffers2(cb, k, 1, &g->buf[k], &off, size == VK_WHOLE_SIZE ? NULL : &size, &zero);
|
||||
} else {
|
||||
r->vkCmdBindVertexBuffers(cb, k, 1, &g->buf[k], &off);
|
||||
}
|
||||
g->tampered |= bit;
|
||||
} else if (g->tampered & bit) {
|
||||
if (di->dynamic_stride) {
|
||||
VkDeviceSize size = g->size[k];
|
||||
r->vkCmdBindVertexBuffers2(cb, k, 1, &g->buf[k], &g->off[k], size == VK_WHOLE_SIZE ? NULL : &size, &g->stride[k]);
|
||||
} else {
|
||||
r->vkCmdBindVertexBuffers(cb, k, 1, &g->buf[k], &g->off[k]);
|
||||
}
|
||||
g->tampered &= ~bit;
|
||||
}
|
||||
}
|
||||
(void)e;
|
||||
}
|
||||
|
||||
static const div_info *active(gfx_state *g)
|
||||
{
|
||||
return g->use_dyn ? &g->dyn : &g->pipe;
|
||||
}
|
||||
|
||||
/* The next instance where some emulated binding moves to its next element. */
|
||||
static uint32_t next_boundary(const div_info *di, uint32_t i, uint32_t count)
|
||||
{
|
||||
uint32_t next = count;
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++) {
|
||||
if (!(di->mask & (1u << k)) || di->divisor[k] <= 1) continue;
|
||||
uint32_t d = di->divisor[k], nb = (i / d + 1) * d;
|
||||
if (nb < next) next = nb;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/* A split draw binds the BaseInstance-as-0 variant when that keeps it exact. */
|
||||
static int split_begin(vkb_emu_device *e, VkCommandBuffer cb, gfx_state *g, const div_info *di, uint32_t fi, uint32_t ic)
|
||||
{
|
||||
(void)e;
|
||||
if (!di->split || next_boundary(di, 0, ic) >= ic) return 0;
|
||||
if (fi == 0 && di->zero_base) {
|
||||
vkb_emu_real()->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, di->zero_base);
|
||||
return 1;
|
||||
}
|
||||
if (fi != 0) VKB_ONCE(VKB_LOG_WARN, "divisor emulation: a split draw with firstInstance > 0 may see SV_InstanceID offset (logged once)");
|
||||
(void)g;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void split_end(VkCommandBuffer cb, gfx_state *g, int variant)
|
||||
{
|
||||
if (variant) vkb_emu_real()->vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, g->pipeline);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDraw(VkCommandBuffer cb, uint32_t vc, uint32_t ic, uint32_t fv, uint32_t fi)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
gfx_state *g = gfx(e, cb);
|
||||
const div_info *di = active(g);
|
||||
if (!di->mask && !g->tampered) {
|
||||
vkb_emu_real()->vkCmdDraw(cb, vc, ic, fv, fi);
|
||||
return;
|
||||
}
|
||||
VKB_DBG("divisor: draw %u instances from %u, bindings 0x%x (dyn %d), bound 0x%x", ic, fi, di->mask, g->use_dyn, g->bound);
|
||||
int variant = split_begin(e, cb, g, di, fi, ic);
|
||||
for (uint32_t i = 0; i < ic || (ic == 0 && i == 0);) {
|
||||
uint32_t end = next_boundary(di, i, ic);
|
||||
prepare(e, cb, g, di, fi, i);
|
||||
if (ic) vkb_emu_real()->vkCmdDraw(cb, vc, end - i, fv, fi + i);
|
||||
if (!ic) break;
|
||||
i = end;
|
||||
}
|
||||
split_end(cb, g, variant);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndexed(VkCommandBuffer cb, uint32_t xc, uint32_t ic, uint32_t fx, int32_t vo, uint32_t fi)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
gfx_state *g = gfx(e, cb);
|
||||
const div_info *di = active(g);
|
||||
if (!di->mask && !g->tampered) {
|
||||
vkb_emu_real()->vkCmdDrawIndexed(cb, xc, ic, fx, vo, fi);
|
||||
return;
|
||||
}
|
||||
int variant = split_begin(e, cb, g, di, fi, ic);
|
||||
for (uint32_t i = 0; i < ic || (ic == 0 && i == 0);) {
|
||||
uint32_t end = next_boundary(di, i, ic);
|
||||
prepare(e, cb, g, di, fi, i);
|
||||
if (ic) vkb_emu_real()->vkCmdDrawIndexed(cb, xc, end - i, fx, vo, fi + i);
|
||||
if (!ic) break;
|
||||
i = end;
|
||||
}
|
||||
split_end(cb, g, variant);
|
||||
}
|
||||
|
||||
static void indirect_prepare(vkb_emu_device *e, VkCommandBuffer cb)
|
||||
{
|
||||
gfx_state *g = gfx(e, cb);
|
||||
const div_info *di = active(g);
|
||||
if (!di->mask && !g->tampered) return;
|
||||
for (uint32_t k = 0; k < MAX_BIND; k++)
|
||||
if ((di->mask & (1u << k)) && di->divisor[k] > 1)
|
||||
VKB_ONCE(VKB_LOG_WARN, "divisor emulation: an indirect draw with an instance divisor > 1 is approximated (logged once)");
|
||||
prepare(e, cb, g, di, 0, 0);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndirect(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, uint32_t n, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndirect(cb, b, o, n, s);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndexedIndirect(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, uint32_t n, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndexedIndirect(cb, b, o, n, s);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndirectCount(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, VkBuffer cbuf, VkDeviceSize co,
|
||||
uint32_t max, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndirectCount(cb, b, o, cbuf, co, max, s);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdDrawIndexedIndirectCount(VkCommandBuffer cb, VkBuffer b, VkDeviceSize o, VkBuffer cbuf,
|
||||
VkDeviceSize co, uint32_t max, uint32_t s)
|
||||
{
|
||||
indirect_prepare(vkb_emu_cur(), cb);
|
||||
vkb_emu_real()->vkCmdDrawIndexedIndirectCount(cb, b, o, cbuf, co, max, s);
|
||||
}
|
||||
|
||||
void vkb_emu_divisor_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
if (!(e->flags & VKB_EMU_DIVISOR)) return;
|
||||
div_state *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
e->divisor = s;
|
||||
vkb_dispatch *dt = &dev->dt;
|
||||
dt->vkDestroyPipeline = emu_DestroyPipeline;
|
||||
dt->vkCmdBindVertexBuffers = emu_CmdBindVertexBuffers;
|
||||
if (dev->real.vkCmdBindVertexBuffers2) dt->vkCmdBindVertexBuffers2 = emu_CmdBindVertexBuffers2;
|
||||
if (dev->real.vkCmdSetVertexInputEXT) dt->vkCmdSetVertexInputEXT = emu_CmdSetVertexInputEXT;
|
||||
dt->vkCmdDraw = emu_CmdDraw;
|
||||
dt->vkCmdDrawIndexed = emu_CmdDrawIndexed;
|
||||
dt->vkCmdDrawIndirect = emu_CmdDrawIndirect;
|
||||
dt->vkCmdDrawIndexedIndirect = emu_CmdDrawIndexedIndirect;
|
||||
if (dev->real.vkCmdDrawIndirectCount) dt->vkCmdDrawIndirectCount = emu_CmdDrawIndirectCount;
|
||||
if (dev->real.vkCmdDrawIndexedIndirectCount) dt->vkCmdDrawIndexedIndirectCount = emu_CmdDrawIndexedIndirectCount;
|
||||
}
|
||||
|
||||
void vkb_emu_divisor_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
div_state *s = dev->emu->divisor;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < 256; i++) {
|
||||
while (s->b[i]) {
|
||||
pipe_rec *r = s->b[i];
|
||||
s->b[i] = r->next;
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->divisor = NULL;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Installs the feature emulations into a device.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
void vkb_emu_install_features(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_cmdstate_install(dev);
|
||||
vkb_emu_shader_install(dev);
|
||||
vkb_emu_bcn_install(dev);
|
||||
vkb_emu_divisor_install(dev);
|
||||
}
|
||||
|
||||
void vkb_emu_uninstall_features(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_divisor_uninstall(dev);
|
||||
vkb_emu_bcn_uninstall(dev);
|
||||
vkb_emu_shader_uninstall(dev);
|
||||
vkb_emu_cmdstate_uninstall(dev);
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Emulation wrappers installed into a device's dispatch table, like a Vulkan layer: the generated
|
||||
* handlers call c->dt, which for an emulating device points here first. The device is found
|
||||
* through the per-call table the connection loop sets (vkb_srv_current_table).
|
||||
*
|
||||
* VK_KHR_maintenance5 (Zink and DXVK 2.7 refuse a Vulkan 1.3 device without it):
|
||||
* - 64-bit flags structures (pipeline create flags 2, buffer usage 2) folded into the 32-bit
|
||||
* fields, which hold every bit a 1.3 driver knows;
|
||||
* - shader modules given inline (VkShaderModuleCreateInfo chained to a stage) created and
|
||||
* destroyed around the pipeline;
|
||||
* - vkCmdBindIndexBuffer2, vkGetRenderingAreaGranularity, vkGetImageSubresourceLayout2 and
|
||||
* vkGetDeviceImageSubresourceLayout on their 1.0 equivalents;
|
||||
* - VK_REMAINING_ARRAY_LAYERS in copy regions and VK_WHOLE_SIZE in vertex buffer sizes, resolved
|
||||
* from the image/buffer the server keeps a record of.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* ------------------------------------------------------------------ resource records */
|
||||
|
||||
static unsigned rh(uint64_t k)
|
||||
{
|
||||
k ^= k >> 29;
|
||||
k *= 0xbf58476d1ce4e5b9ull;
|
||||
return (unsigned)(k >> 52) & (VKB_EMU_BUCKETS - 1);
|
||||
}
|
||||
|
||||
void vkb_emu_track_image(vkb_emu_device *e, VkImage img, const VkImageCreateInfo *ci, VkFormat client_format)
|
||||
{
|
||||
vkb_emu_image *r = calloc(1, sizeof(*r));
|
||||
r->image = img;
|
||||
r->type = ci->imageType;
|
||||
r->format = ci->format;
|
||||
r->client_format = client_format;
|
||||
r->extent = ci->extent;
|
||||
r->mips = ci->mipLevels;
|
||||
r->layers = ci->arrayLayers;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
unsigned h = rh((uint64_t)img);
|
||||
r->next = e->images[h];
|
||||
e->images[h] = r;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
}
|
||||
|
||||
vkb_emu_image *vkb_emu_find_image(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_image *r = e->images[rh((uint64_t)img)];
|
||||
while (r && r->image != img) r = r->next;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void untrack_image(vkb_emu_device *e, VkImage img)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_image **pp = &e->images[rh((uint64_t)img)];
|
||||
while (*pp && (*pp)->image != img) pp = &(*pp)->next;
|
||||
vkb_emu_image *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
if (r) {
|
||||
vkb_emu_image_release(e, r);
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
|
||||
static void track_buffer(vkb_emu_device *e, VkBuffer b, VkDeviceSize size)
|
||||
{
|
||||
vkb_emu_buffer *r = calloc(1, sizeof(*r));
|
||||
r->buffer = b;
|
||||
r->size = size;
|
||||
pthread_mutex_lock(&e->lock);
|
||||
unsigned h = rh((uint64_t)b);
|
||||
r->next = e->buffers[h];
|
||||
e->buffers[h] = r;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
}
|
||||
|
||||
static VkDeviceSize buffer_size(vkb_emu_device *e, VkBuffer b)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_buffer *r = e->buffers[rh((uint64_t)b)];
|
||||
while (r && r->buffer != b) r = r->next;
|
||||
VkDeviceSize s = r ? r->size : 0;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
return s;
|
||||
}
|
||||
|
||||
static void untrack_buffer(vkb_emu_device *e, VkBuffer b)
|
||||
{
|
||||
pthread_mutex_lock(&e->lock);
|
||||
vkb_emu_buffer **pp = &e->buffers[rh((uint64_t)b)];
|
||||
while (*pp && (*pp)->buffer != b) pp = &(*pp)->next;
|
||||
vkb_emu_buffer *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&e->lock);
|
||||
free(r);
|
||||
}
|
||||
|
||||
vkb_emu_device *vkb_emu_cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->emu : NULL;
|
||||
}
|
||||
|
||||
const vkb_dispatch *vkb_emu_real(void)
|
||||
{
|
||||
return &vkb_srv_current_table()->real;
|
||||
}
|
||||
|
||||
/* Removes the first structure of type t from a chain we own (decoded into the call's arena). */
|
||||
void *vkb_emu_chain_take(const void *head_const, VkStructureType t)
|
||||
{
|
||||
VkBaseOutStructure *prev = (VkBaseOutStructure *)head_const;
|
||||
while (prev->pNext) {
|
||||
if (prev->pNext->sType == t) {
|
||||
VkBaseOutStructure *found = prev->pNext;
|
||||
prev->pNext = found->pNext;
|
||||
return found;
|
||||
}
|
||||
prev = prev->pNext;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ resources */
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo,
|
||||
const VkAllocationCallbacks *pAllocator, VkBuffer *pBuffer)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkBufferCreateInfo *ci = (VkBufferCreateInfo *)pCreateInfo;
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
VkBufferUsageFlags2CreateInfo *u = vkb_emu_chain_take(ci, VK_STRUCTURE_TYPE_BUFFER_USAGE_FLAGS_2_CREATE_INFO);
|
||||
if (u) ci->usage = (VkBufferUsageFlags)u->usage;
|
||||
}
|
||||
vkb_emu_bcn_buffer_usage(e, ci);
|
||||
VkResult r = vkb_emu_real()->vkCreateBuffer(device, ci, pAllocator, pBuffer);
|
||||
if (r == VK_SUCCESS) track_buffer(e, *pBuffer, ci->size);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyBuffer(VkDevice device, VkBuffer buffer, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
if (buffer) untrack_buffer(vkb_emu_cur(), buffer);
|
||||
vkb_emu_real()->vkDestroyBuffer(device, buffer, pAllocator);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateBufferView(VkDevice device, const VkBufferViewCreateInfo *pCreateInfo,
|
||||
const VkAllocationCallbacks *pAllocator, VkBufferView *pView)
|
||||
{
|
||||
if (vkb_emu_cur()->flags & VKB_EMU_MAINT5) vkb_emu_chain_take(pCreateInfo, VK_STRUCTURE_TYPE_BUFFER_USAGE_FLAGS_2_CREATE_INFO);
|
||||
return vkb_emu_real()->vkCreateBufferView(device, pCreateInfo, pAllocator, pView);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateImage(VkDevice device, const VkImageCreateInfo *pCreateInfo,
|
||||
const VkAllocationCallbacks *pAllocator, VkImage *pImage)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkImageCreateInfo *ci = (VkImageCreateInfo *)pCreateInfo;
|
||||
VkFormat client_format = ci->format;
|
||||
vkb_emu_image_create_info(e, ci);
|
||||
VkResult r = vkb_emu_real()->vkCreateImage(device, ci, pAllocator, pImage);
|
||||
if (r == VK_SUCCESS) vkb_emu_track_image(e, *pImage, ci, client_format);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyImage(VkDevice device, VkImage image, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
if (image) untrack_image(vkb_emu_cur(), image);
|
||||
vkb_emu_real()->vkDestroyImage(device, image, pAllocator);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ pipelines */
|
||||
|
||||
/* Fold flags2 and create inline shader modules; temporaries are recorded in mods[]. */
|
||||
static void prep_stage(VkDevice device, VkPipelineShaderStageCreateInfo *st, VkShaderModule *mods, uint32_t *nmods, uint32_t cap)
|
||||
{
|
||||
if (st->module) return;
|
||||
VkShaderModuleCreateInfo *smci = vkb_emu_chain_take(st, VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
|
||||
if (!smci) return;
|
||||
VkShaderModule m = VK_NULL_HANDLE;
|
||||
smci->pNext = NULL;
|
||||
if (vkb_emu_real()->vkCreateShaderModule(device, smci, NULL, &m) == VK_SUCCESS) {
|
||||
st->module = m;
|
||||
if (*nmods < cap) mods[(*nmods)++] = m;
|
||||
}
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkGraphicsPipelineCreateInfo *infos,
|
||||
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkShaderModule mods[64];
|
||||
uint32_t nmods = 0;
|
||||
size_t dsz = vkb_emu_divisor_info_size();
|
||||
uint8_t *divs = calloc(n ? n : 1, dsz);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkGraphicsPipelineCreateInfo *ci = (VkGraphicsPipelineCreateInfo *)&infos[i];
|
||||
vkb_emu_divisor_pipeline(e, device, ci, (div_info *)(divs + i * dsz));
|
||||
vkb_emu_depth_clip_pipeline(e, ci);
|
||||
/* Shader rewrites first: they read inline SPIR-V before it becomes a module. */
|
||||
vkb_emu_shader_pipeline(e, device, ci, mods, &nmods, 64);
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
VkPipelineCreateFlags2CreateInfo *f2 = vkb_emu_chain_take(ci, VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO);
|
||||
if (f2) ci->flags = (VkPipelineCreateFlags)f2->flags;
|
||||
for (uint32_t s = 0; s < ci->stageCount; s++)
|
||||
prep_stage(device, (VkPipelineShaderStageCreateInfo *)&ci->pStages[s], mods, &nmods, 64);
|
||||
}
|
||||
}
|
||||
VkResult r = vkb_emu_real()->vkCreateGraphicsPipelines(device, cache, n, infos, pAllocator, pPipelines);
|
||||
/* Before the temporary modules go: a divisor variant is built from the same stages. */
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
vkb_emu_divisor_created(e, device, cache, &infos[i], r >= 0 ? pPipelines[i] : VK_NULL_HANDLE, (div_info *)(divs + i * dsz));
|
||||
for (uint32_t i = 0; i < nmods; i++) vkb_emu_real()->vkDestroyShaderModule(device, mods[i], NULL);
|
||||
free(divs);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkComputePipelineCreateInfo *infos,
|
||||
const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
VkShaderModule mods[64];
|
||||
uint32_t nmods = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkComputePipelineCreateInfo *ci = (VkComputePipelineCreateInfo *)&infos[i];
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
VkPipelineCreateFlags2CreateInfo *f2 = vkb_emu_chain_take(ci, VK_STRUCTURE_TYPE_PIPELINE_CREATE_FLAGS_2_CREATE_INFO);
|
||||
if (f2) ci->flags = (VkPipelineCreateFlags)f2->flags;
|
||||
prep_stage(device, &ci->stage, mods, &nmods, 64);
|
||||
}
|
||||
}
|
||||
VkResult r = vkb_emu_real()->vkCreateComputePipelines(device, cache, n, infos, pAllocator, pPipelines);
|
||||
for (uint32_t i = 0; i < nmods; i++) vkb_emu_real()->vkDestroyShaderModule(device, mods[i], NULL);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ maintenance5 entry points */
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindIndexBuffer2(VkCommandBuffer cb, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size,
|
||||
VkIndexType type)
|
||||
{
|
||||
(void)size;
|
||||
vkb_emu_real()->vkCmdBindIndexBuffer(cb, buffer, offset, type);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_GetRenderingAreaGranularity(VkDevice device, const VkRenderingAreaInfo *info, VkExtent2D *g)
|
||||
{
|
||||
(void)device;
|
||||
(void)info;
|
||||
g->width = 1;
|
||||
g->height = 1;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_GetImageSubresourceLayout2(VkDevice device, VkImage image, const VkImageSubresource2 *sub,
|
||||
VkSubresourceLayout2 *layout)
|
||||
{
|
||||
vkb_emu_real()->vkGetImageSubresourceLayout(device, image, &sub->imageSubresource, &layout->subresourceLayout);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_GetDeviceImageSubresourceLayout(VkDevice device, const VkDeviceImageSubresourceInfo *info,
|
||||
VkSubresourceLayout2 *layout)
|
||||
{
|
||||
VkImage img;
|
||||
memset(&layout->subresourceLayout, 0, sizeof(layout->subresourceLayout));
|
||||
if (vkb_emu_real()->vkCreateImage(device, info->pCreateInfo, NULL, &img) != VK_SUCCESS) return;
|
||||
vkb_emu_real()->vkGetImageSubresourceLayout(device, img, &info->pSubresource->imageSubresource, &layout->subresourceLayout);
|
||||
vkb_emu_real()->vkDestroyImage(device, img, NULL);
|
||||
}
|
||||
|
||||
/* VK_REMAINING_ARRAY_LAYERS in a copy region, resolved against the image. */
|
||||
static void fix_layers(vkb_emu_device *e, VkImage img, VkImageSubresourceLayers *l)
|
||||
{
|
||||
if (l->layerCount != VK_REMAINING_ARRAY_LAYERS) return;
|
||||
vkb_emu_image *r = vkb_emu_find_image(e, img);
|
||||
l->layerCount = r && r->layers > l->baseArrayLayer ? r->layers - l->baseArrayLayer : 1;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImage(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageCopy *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].srcSubresource);
|
||||
fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].dstSubresource);
|
||||
}
|
||||
if (vkb_emu_copy_image(e, cb, src, sl, dst, dl, n, regions)) return;
|
||||
vkb_emu_real()->vkCmdCopyImage(cb, src, sl, dst, dl, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImage2(VkCommandBuffer cb, const VkCopyImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].srcSubresource);
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].dstSubresource);
|
||||
}
|
||||
if (vkb_emu_copy_image2(e, cb, info)) return;
|
||||
vkb_emu_real()->vkCmdCopyImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBlitImage(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageBlit *regions, VkFilter filter)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].srcSubresource);
|
||||
fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdBlitImage(cb, src, sl, dst, dl, n, regions, filter);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBlitImage2(VkCommandBuffer cb, const VkBlitImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].srcSubresource);
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdBlitImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdResolveImage(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkImage dst, VkImageLayout dl,
|
||||
uint32_t n, const VkImageResolve *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].srcSubresource);
|
||||
fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdResolveImage(cb, src, sl, dst, dl, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdResolveImage2(VkCommandBuffer cb, const VkResolveImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++) {
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].srcSubresource);
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].dstSubresource);
|
||||
}
|
||||
vkb_emu_real()->vkCmdResolveImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyBufferToImage(VkCommandBuffer cb, VkBuffer src, VkImage dst, VkImageLayout dl, uint32_t n,
|
||||
const VkBufferImageCopy *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_layers(e, dst, (VkImageSubresourceLayers *)®ions[i].imageSubresource);
|
||||
if (vkb_emu_copy_buffer_to_image(e, cb, src, dst, dl, n, regions)) return;
|
||||
vkb_emu_real()->vkCmdCopyBufferToImage(cb, src, dst, dl, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyBufferToImage2(VkCommandBuffer cb, const VkCopyBufferToImageInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++)
|
||||
fix_layers(e, info->dstImage, (VkImageSubresourceLayers *)&info->pRegions[i].imageSubresource);
|
||||
if (vkb_emu_copy_buffer_to_image2(e, cb, info)) return;
|
||||
vkb_emu_real()->vkCmdCopyBufferToImage2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImageToBuffer(VkCommandBuffer cb, VkImage src, VkImageLayout sl, VkBuffer dst, uint32_t n,
|
||||
const VkBufferImageCopy *regions)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_layers(e, src, (VkImageSubresourceLayers *)®ions[i].imageSubresource);
|
||||
if (vkb_emu_bcn_blocks_readback(e, src)) return;
|
||||
vkb_emu_real()->vkCmdCopyImageToBuffer(cb, src, sl, dst, n, regions);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdCopyImageToBuffer2(VkCommandBuffer cb, const VkCopyImageToBufferInfo2 *info)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
for (uint32_t i = 0; i < info->regionCount; i++)
|
||||
fix_layers(e, info->srcImage, (VkImageSubresourceLayers *)&info->pRegions[i].imageSubresource);
|
||||
if (vkb_emu_bcn_blocks_readback(e, info->srcImage)) return;
|
||||
vkb_emu_real()->vkCmdCopyImageToBuffer2(cb, info);
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_CmdBindVertexBuffers2(VkCommandBuffer cb, uint32_t first, uint32_t n, const VkBuffer *buffers,
|
||||
const VkDeviceSize *offsets, const VkDeviceSize *sizes,
|
||||
const VkDeviceSize *strides)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
if (sizes) {
|
||||
VkDeviceSize *s = (VkDeviceSize *)sizes;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
if (s[i] != VK_WHOLE_SIZE || !buffers[i]) continue;
|
||||
VkDeviceSize total = buffer_size(e, buffers[i]);
|
||||
s[i] = total > offsets[i] ? total - offsets[i] : 0;
|
||||
}
|
||||
}
|
||||
vkb_emu_real()->vkCmdBindVertexBuffers2(cb, first, n, buffers, offsets, sizes, strides);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ install */
|
||||
|
||||
void vkb_emu_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
vkb_dispatch *dt = &dev->dt;
|
||||
/* Resource records are needed by every emulation. */
|
||||
dt->vkCreateBuffer = emu_CreateBuffer;
|
||||
dt->vkDestroyBuffer = emu_DestroyBuffer;
|
||||
dt->vkCreateImage = emu_CreateImage;
|
||||
dt->vkDestroyImage = emu_DestroyImage;
|
||||
dt->vkCreateGraphicsPipelines = emu_CreateGraphicsPipelines;
|
||||
dt->vkCreateComputePipelines = emu_CreateComputePipelines;
|
||||
dt->vkCmdCopyImage = emu_CmdCopyImage;
|
||||
dt->vkCmdCopyBufferToImage = emu_CmdCopyBufferToImage;
|
||||
if (dev->real.vkCmdCopyImage2) dt->vkCmdCopyImage2 = emu_CmdCopyImage2;
|
||||
if (dev->real.vkCmdCopyBufferToImage2) dt->vkCmdCopyBufferToImage2 = emu_CmdCopyBufferToImage2;
|
||||
dt->vkCmdCopyImageToBuffer = emu_CmdCopyImageToBuffer;
|
||||
if (dev->real.vkCmdCopyImageToBuffer2) dt->vkCmdCopyImageToBuffer2 = emu_CmdCopyImageToBuffer2;
|
||||
if (e->flags & VKB_EMU_MAINT5) {
|
||||
dt->vkCreateBufferView = emu_CreateBufferView;
|
||||
dt->vkCmdBindIndexBuffer2 = emu_CmdBindIndexBuffer2;
|
||||
dt->vkGetRenderingAreaGranularity = emu_GetRenderingAreaGranularity;
|
||||
dt->vkGetImageSubresourceLayout2 = emu_GetImageSubresourceLayout2;
|
||||
dt->vkGetDeviceImageSubresourceLayout = emu_GetDeviceImageSubresourceLayout;
|
||||
dt->vkCmdBlitImage = emu_CmdBlitImage;
|
||||
dt->vkCmdResolveImage = emu_CmdResolveImage;
|
||||
if (dev->real.vkCmdBlitImage2) dt->vkCmdBlitImage2 = emu_CmdBlitImage2;
|
||||
if (dev->real.vkCmdResolveImage2) dt->vkCmdResolveImage2 = emu_CmdResolveImage2;
|
||||
if (dev->real.vkCmdBindVertexBuffers2) dt->vkCmdBindVertexBuffers2 = emu_CmdBindVertexBuffers2;
|
||||
}
|
||||
vkb_emu_install_features(dev);
|
||||
vkb_emu_depth_clip_install(dev);
|
||||
VKB_INFO("device %u: emulation 0x%x installed", dev->id, e->flags);
|
||||
}
|
||||
|
||||
void vkb_emu_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
vkb_emu_uninstall_features(dev);
|
||||
for (int i = 0; i < VKB_EMU_BUCKETS; i++) {
|
||||
while (e->images[i]) {
|
||||
vkb_emu_image *r = e->images[i];
|
||||
e->images[i] = r->next;
|
||||
vkb_emu_image_release(e, r);
|
||||
free(r);
|
||||
}
|
||||
while (e->buffers[i]) {
|
||||
vkb_emu_buffer *r = e->buffers[i];
|
||||
e->buffers[i] = r->next;
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ depth clip enable */
|
||||
|
||||
/* VK_EXT_depth_clip_enable on a GPU without it. Without the extension Vulkan clips exactly when
|
||||
* depth clamp is off, so a pipeline's clamp becomes "not clip" (D3D's DepthClipEnable = FALSE is
|
||||
* clamping; clip + clamp only differs for fragments the clip removes anyway). The client hides
|
||||
* dynamic depth clip/clamp while this is emulated, so both are static pipeline state here. */
|
||||
void vkb_emu_depth_clip_pipeline(vkb_emu_device *e, VkGraphicsPipelineCreateInfo *ci)
|
||||
{
|
||||
if (!(e->flags & VKB_EMU_DEPTH_CLIP)) return;
|
||||
VkPipelineRasterizationStateCreateInfo *rs = (VkPipelineRasterizationStateCreateInfo *)ci->pRasterizationState;
|
||||
if (!rs) return;
|
||||
VkPipelineRasterizationDepthClipStateCreateInfoEXT *dc =
|
||||
vkb_emu_chain_take(rs, VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_DEPTH_CLIP_STATE_CREATE_INFO_EXT);
|
||||
if (dc) rs->depthClampEnable = dc->depthClipEnable ? VK_FALSE : VK_TRUE;
|
||||
}
|
||||
|
||||
void vkb_emu_depth_clip_install(vkb_srv_table *dev)
|
||||
{
|
||||
(void)dev;
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Shader-side emulations, done when a graphics pipeline is created (both ends of the vertex ->
|
||||
* fragment interface are known then):
|
||||
*
|
||||
* clip distance (shaderClipDistance missing): the last pre-rasterization stage's ClipDistance
|
||||
* output becomes an ordinary varying at a free location; the fragment shader reads it and
|
||||
* discards the fragment when any distance is negative. For planar clip distances this is the
|
||||
* same set of pixels the hardware clipper would keep.
|
||||
* cull distance (shaderCullDistance missing): the output becomes an unread varying - nothing is
|
||||
* culled, which costs fragments but never drops geometry that should be visible.
|
||||
* point size in geometry/tessellation (shaderTessellationAndGeometryPointSize missing): same.
|
||||
*
|
||||
* Shader modules are kept as SPIR-V so a pipeline can build rewritten variants; the driver's own
|
||||
* module is created from a variant that needs none of the missing features.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "server_emu.h"
|
||||
#include "spirv_edit.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
typedef struct shader_rec {
|
||||
VkShaderModule module;
|
||||
uint32_t *code;
|
||||
size_t size;
|
||||
struct shader_rec *next;
|
||||
} shader_rec;
|
||||
|
||||
typedef struct shader_state {
|
||||
pthread_mutex_t lock;
|
||||
shader_rec *mods[1024];
|
||||
} shader_state;
|
||||
|
||||
#define SHADER_EMU (VKB_EMU_CLIP_DISTANCE | VKB_EMU_CULL_DISTANCE | VKB_EMU_POINT_SIZE)
|
||||
/* Emulations that need the shader modules' SPIR-V kept. */
|
||||
#define SHADER_STORE (SHADER_EMU | VKB_EMU_DIVISOR)
|
||||
|
||||
static unsigned mh(VkShaderModule m)
|
||||
{
|
||||
uint64_t k = (uint64_t)m;
|
||||
k ^= k >> 31;
|
||||
k *= 0x94d049bb133111ebull;
|
||||
return (unsigned)(k >> 54);
|
||||
}
|
||||
|
||||
static shader_state *state(vkb_emu_device *e) { return e->shaders; }
|
||||
|
||||
static const shader_rec *find_module(vkb_emu_device *e, VkShaderModule m)
|
||||
{
|
||||
shader_state *s = state(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
shader_rec *r = s->mods[mh(m)];
|
||||
while (r && r->module != m) r = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rewrites */
|
||||
|
||||
/* Finds a standalone Output/Input variable decorated with a builtin; 0 if none. 2 = in a block. */
|
||||
static uint32_t builtin_var(const spv_mod *m, uint32_t builtin, uint32_t storage, int *in_block)
|
||||
{
|
||||
*in_block = 0;
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op == SpvOpDecorate && in->w[1] == SpvDecorationBuiltIn && in->w[2] == builtin) {
|
||||
int d = spv_find_def(m, in->w[0]);
|
||||
if (d >= 0 && m->ins[d].op == SpvOpVariable && m->ins[d].w[2] == storage) return in->w[0];
|
||||
}
|
||||
if (in->op == SpvOpMemberDecorate && in->w[2] == SpvDecorationBuiltIn && in->w[3] == builtin) *in_block = 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static uint32_t var_pointee(const spv_mod *m, uint32_t var)
|
||||
{
|
||||
int d = spv_find_def(m, var);
|
||||
if (d < 0) return 0;
|
||||
int p = spv_find_def(m, m->ins[d].w[0]);
|
||||
return p < 0 ? 0 : m->ins[p].w[2];
|
||||
}
|
||||
|
||||
static void add_decoration(spv_mod *m, uint32_t id, uint32_t dec, uint32_t value)
|
||||
{
|
||||
uint32_t ops[3] = {id, dec, value};
|
||||
spv_insert(m, spv_annotations_end(m), SpvOpDecorate, ops, 3);
|
||||
}
|
||||
|
||||
/* Builtin output -> plain varying at *loc (advanced). Returns the element count, 0 if absent. */
|
||||
static uint32_t demote_builtin(spv_mod *m, uint32_t builtin, uint32_t *loc, int *unsupported)
|
||||
{
|
||||
int in_block;
|
||||
uint32_t var = builtin_var(m, builtin, SpvStorageClassOutput, &in_block);
|
||||
if (!var) {
|
||||
if (in_block) *unsupported = 1;
|
||||
return 0;
|
||||
}
|
||||
uint32_t pointee = var_pointee(m, var);
|
||||
uint32_t n = spv_array_length(m, pointee);
|
||||
if (!n) n = 1;
|
||||
spv_remove_decoration(m, var, SpvDecorationBuiltIn);
|
||||
add_decoration(m, var, SpvDecorationLocation, *loc);
|
||||
*loc += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* The pre-rasterization side. Returns the clip distance count (0: none), -1 if it cannot. */
|
||||
static int rewrite_pre_raster(spv_mod *m, uint32_t emu, uint32_t clip_loc, int last_stage)
|
||||
{
|
||||
int unsupported = 0;
|
||||
uint32_t loc = clip_loc;
|
||||
int clip = 0;
|
||||
if ((emu & VKB_EMU_CLIP_DISTANCE) && spv_has_capability(m, SpvCapabilityClipDistance)) {
|
||||
clip = (int)demote_builtin(m, SpvBuiltInClipDistance, &loc, &unsupported);
|
||||
spv_remove_capability(m, SpvCapabilityClipDistance);
|
||||
}
|
||||
if ((emu & VKB_EMU_CULL_DISTANCE) && spv_has_capability(m, SpvCapabilityCullDistance)) {
|
||||
demote_builtin(m, SpvBuiltInCullDistance, &loc, &unsupported);
|
||||
spv_remove_capability(m, SpvCapabilityCullDistance);
|
||||
}
|
||||
int model = spv_execution_model(m);
|
||||
if ((emu & VKB_EMU_POINT_SIZE) && (model == SpvExecutionModelGeometry || model == SpvExecutionModelTessellationEvaluation) &&
|
||||
(spv_has_capability(m, SpvCapabilityGeometryPointSize) || spv_has_capability(m, SpvCapabilityTessellationPointSize))) {
|
||||
demote_builtin(m, SpvBuiltInPointSize, &loc, &unsupported);
|
||||
spv_remove_capability(m, SpvCapabilityGeometryPointSize);
|
||||
spv_remove_capability(m, SpvCapabilityTessellationPointSize);
|
||||
}
|
||||
(void)last_stage;
|
||||
if (unsupported) VKB_ONCE(VKB_LOG_WARN, "emulation: clip/cull distance inside an output block is not handled (logged once)");
|
||||
return unsupported && !clip ? -1 : clip;
|
||||
}
|
||||
|
||||
/* The fragment side: read the distances at `loc` and discard when any is negative. */
|
||||
static int rewrite_fragment(spv_mod *m, uint32_t loc, uint32_t n)
|
||||
{
|
||||
uint32_t f32 = spv_type_float(m, 32);
|
||||
uint32_t len = spv_const_u32(m, n);
|
||||
uint32_t arr = spv_type_array(m, f32, len);
|
||||
uint32_t parr = spv_type_pointer(m, SpvStorageClassInput, arr);
|
||||
uint32_t pf = spv_type_pointer(m, SpvStorageClassInput, f32);
|
||||
uint32_t tbool = spv_type_bool(m);
|
||||
uint32_t zero = spv_const_f32(m, 0.0f);
|
||||
uint32_t idx[16];
|
||||
for (uint32_t i = 0; i < n && i < 16; i++) idx[i] = spv_const_u32(m, i);
|
||||
uint32_t var = spv_new_id(m);
|
||||
uint32_t vops[3] = {parr, var, SpvStorageClassInput};
|
||||
spv_insert(m, spv_types_end(m), SpvOpVariable, vops, 3);
|
||||
add_decoration(m, var, SpvDecorationLocation, loc);
|
||||
spv_add_interface(m, var);
|
||||
|
||||
int ep = spv_find_op(m, SpvOpEntryPoint, 0);
|
||||
if (ep < 0) return -1;
|
||||
uint32_t fn = m->ins[ep].w[1];
|
||||
int fi = -1;
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpFunction && m->ins[i].w[1] == fn) fi = (int)i;
|
||||
if (fi < 0) return -1;
|
||||
int li = spv_find_op(m, SpvOpLabel, (uint32_t)fi);
|
||||
if (li < 0) return -1;
|
||||
uint32_t first_label = m->ins[li].w[0];
|
||||
uint32_t at = (uint32_t)li + 1;
|
||||
while (at < m->count && (m->ins[at].op == SpvOpVariable || m->ins[at].op == SpvOpLine || m->ins[at].op == SpvOpNoLine)) at++;
|
||||
|
||||
uint32_t any = 0;
|
||||
for (uint32_t i = 0; i < n && i < 16; i++) {
|
||||
uint32_t p = spv_new_id(m), v = spv_new_id(m), lt = spv_new_id(m);
|
||||
uint32_t ac[4] = {pf, p, var, idx[i]};
|
||||
at = spv_insert(m, at, SpvOpAccessChain, ac, 4) + 1;
|
||||
uint32_t ld[3] = {f32, v, p};
|
||||
at = spv_insert(m, at, SpvOpLoad, ld, 3) + 1;
|
||||
uint32_t cmp[4] = {tbool, lt, v, zero};
|
||||
at = spv_insert(m, at, SpvOpFOrdLessThan, cmp, 4) + 1;
|
||||
if (any) {
|
||||
uint32_t o = spv_new_id(m), orr[4] = {tbool, o, any, lt};
|
||||
at = spv_insert(m, at, SpvOpLogicalOr, orr, 4) + 1;
|
||||
any = o;
|
||||
} else {
|
||||
any = lt;
|
||||
}
|
||||
}
|
||||
uint32_t kill = spv_new_id(m), merge = spv_new_id(m);
|
||||
uint32_t sm[2] = {merge, 0};
|
||||
at = spv_insert(m, at, SpvOpSelectionMerge, sm, 2) + 1;
|
||||
uint32_t bc[3] = {any, kill, merge};
|
||||
at = spv_insert(m, at, SpvOpBranchConditional, bc, 3) + 1;
|
||||
at = spv_insert(m, at, SpvOpLabel, &kill, 1) + 1;
|
||||
at = spv_insert(m, at, spv_version(m) >= 0x00010600 ? SpvOpTerminateInvocation : SpvOpKill, NULL, 0) + 1;
|
||||
at = spv_insert(m, at, SpvOpLabel, &merge, 1) + 1;
|
||||
/* Phis that named the old entry block as a predecessor now come from the merge block. */
|
||||
for (uint32_t i = at; i < m->count; i++) {
|
||||
spv_inst *in = &m->ins[i];
|
||||
if (in->op != 245 /* OpPhi */) continue;
|
||||
for (uint32_t k = 3; k < (uint32_t)in->n - 1; k += 2)
|
||||
if (in->w[k] == first_label) in->w[k] = merge;
|
||||
}
|
||||
return m->err ? -1 : 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ module store */
|
||||
|
||||
static VkResult make_module(VkDevice device, const spv_mod *m, VkShaderModule *out)
|
||||
{
|
||||
uint32_t *code;
|
||||
size_t size = spv_write(m, &code);
|
||||
if (!size) return VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
const char *dump = getenv("VKBRIDGE_DUMP_SPIRV");
|
||||
if (dump && *dump) {
|
||||
static int seq;
|
||||
char path[512];
|
||||
snprintf(path, sizeof(path), "%s/vkbridge-%d-%d.spv", dump, (int)getpid(), __atomic_fetch_add(&seq, 1, __ATOMIC_RELAXED));
|
||||
FILE *f = fopen(path, "wb");
|
||||
if (f) {
|
||||
fwrite(code, 1, size, f);
|
||||
fclose(f);
|
||||
}
|
||||
}
|
||||
VkShaderModuleCreateInfo ci = {VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size, code};
|
||||
VkResult r = vkb_emu_real()->vkCreateShaderModule(device, &ci, NULL, out);
|
||||
free(code);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR VkResult VKAPI_CALL emu_CreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *ci,
|
||||
const VkAllocationCallbacks *pAllocator, VkShaderModule *pModule)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
spv_mod m;
|
||||
VkResult r;
|
||||
int needs = 0;
|
||||
if (spv_parse(&m, ci->pCode, ci->codeSize) == 0) {
|
||||
needs = spv_has_capability(&m, SpvCapabilityClipDistance) || spv_has_capability(&m, SpvCapabilityCullDistance) ||
|
||||
spv_has_capability(&m, SpvCapabilityGeometryPointSize) || spv_has_capability(&m, SpvCapabilityTessellationPointSize);
|
||||
}
|
||||
if (needs) {
|
||||
/* The driver's module must not ask for what it lacks; pipelines use rewritten variants. */
|
||||
int maxo = spv_max_location(&m, SpvStorageClassOutput);
|
||||
rewrite_pre_raster(&m, e->flags, (uint32_t)(maxo + 1), 1);
|
||||
r = make_module(device, &m, pModule);
|
||||
} else {
|
||||
r = vkb_emu_real()->vkCreateShaderModule(device, ci, pAllocator, pModule);
|
||||
}
|
||||
spv_free(&m);
|
||||
if (r != VK_SUCCESS) return r;
|
||||
shader_rec *rec = calloc(1, sizeof(*rec));
|
||||
rec->module = *pModule;
|
||||
rec->size = ci->codeSize;
|
||||
rec->code = malloc(ci->codeSize);
|
||||
memcpy(rec->code, ci->pCode, ci->codeSize);
|
||||
shader_state *s = state(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
unsigned h = mh(*pModule);
|
||||
rec->next = s->mods[h];
|
||||
s->mods[h] = rec;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static VKAPI_ATTR void VKAPI_CALL emu_DestroyShaderModule(VkDevice device, VkShaderModule module, const VkAllocationCallbacks *pAllocator)
|
||||
{
|
||||
vkb_emu_device *e = vkb_emu_cur();
|
||||
if (module) {
|
||||
shader_state *s = state(e);
|
||||
pthread_mutex_lock(&s->lock);
|
||||
shader_rec **pp = &s->mods[mh(module)];
|
||||
while (*pp && (*pp)->module != module) pp = &(*pp)->next;
|
||||
shader_rec *r = *pp;
|
||||
if (r) *pp = r->next;
|
||||
pthread_mutex_unlock(&s->lock);
|
||||
if (r) {
|
||||
free(r->code);
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
vkb_emu_real()->vkDestroyShaderModule(device, module, pAllocator);
|
||||
}
|
||||
|
||||
/* The SPIR-V of a stage: its module's (kept here) or the inline VkShaderModuleCreateInfo's. */
|
||||
static int stage_code(vkb_emu_device *e, const VkPipelineShaderStageCreateInfo *st, const uint32_t **code, size_t *size)
|
||||
{
|
||||
if (st->module) {
|
||||
const shader_rec *r = find_module(e, st->module);
|
||||
if (!r) return 0;
|
||||
*code = r->code;
|
||||
*size = r->size;
|
||||
return 1;
|
||||
}
|
||||
for (const VkBaseInStructure *b = st->pNext; b; b = b->pNext) {
|
||||
if (b->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) {
|
||||
*code = ((const VkShaderModuleCreateInfo *)b)->pCode;
|
||||
*size = ((const VkShaderModuleCreateInfo *)b)->codeSize;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Replace a stage's shader by a rewritten module (recorded for destruction after the call). */
|
||||
static void set_stage_module(VkDevice device, VkPipelineShaderStageCreateInfo *st, const spv_mod *m, VkShaderModule *mods,
|
||||
uint32_t *nmods, uint32_t cap)
|
||||
{
|
||||
VkShaderModule mod;
|
||||
if (*nmods >= cap || make_module(device, m, &mod) != VK_SUCCESS) return;
|
||||
mods[(*nmods)++] = mod;
|
||||
st->module = mod;
|
||||
vkb_emu_chain_take(st, VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO);
|
||||
}
|
||||
|
||||
void vkb_emu_shader_pipeline(vkb_emu_device *e, VkDevice device, VkGraphicsPipelineCreateInfo *ci, VkShaderModule *mods,
|
||||
uint32_t *nmods, uint32_t cap)
|
||||
{
|
||||
if (!(e->flags & SHADER_EMU) || !ci->pStages) return;
|
||||
VkPipelineShaderStageCreateInfo *pre = NULL, *frag = NULL;
|
||||
int pre_rank = -1;
|
||||
for (uint32_t s = 0; s < ci->stageCount; s++) {
|
||||
VkPipelineShaderStageCreateInfo *st = (VkPipelineShaderStageCreateInfo *)&ci->pStages[s];
|
||||
int rank = st->stage == VK_SHADER_STAGE_VERTEX_BIT ? 0 : st->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT ? 1
|
||||
: st->stage == VK_SHADER_STAGE_GEOMETRY_BIT ? 2 : -1;
|
||||
if (rank > pre_rank) {
|
||||
pre_rank = rank;
|
||||
pre = st;
|
||||
}
|
||||
if (st->stage == VK_SHADER_STAGE_FRAGMENT_BIT) frag = st;
|
||||
}
|
||||
if (!pre) return;
|
||||
const uint32_t *code;
|
||||
size_t size;
|
||||
if (!stage_code(e, pre, &code, &size)) return;
|
||||
spv_mod pm;
|
||||
if (spv_parse(&pm, code, size) != 0) return;
|
||||
if (!spv_has_capability(&pm, SpvCapabilityClipDistance) && !spv_has_capability(&pm, SpvCapabilityCullDistance) &&
|
||||
!spv_has_capability(&pm, SpvCapabilityGeometryPointSize) && !spv_has_capability(&pm, SpvCapabilityTessellationPointSize)) {
|
||||
spv_free(&pm);
|
||||
return;
|
||||
}
|
||||
spv_mod fm;
|
||||
int have_frag = 0;
|
||||
const uint32_t *fcode;
|
||||
size_t fsize;
|
||||
if (frag && stage_code(e, frag, &fcode, &fsize) && spv_parse(&fm, fcode, fsize) == 0) have_frag = 1;
|
||||
int loc = spv_max_location(&pm, SpvStorageClassOutput);
|
||||
if (have_frag) {
|
||||
int fl = spv_max_location(&fm, SpvStorageClassInput);
|
||||
if (fl > loc) loc = fl;
|
||||
}
|
||||
int clip = rewrite_pre_raster(&pm, e->flags, (uint32_t)(loc + 1), 1);
|
||||
if (clip >= 0) set_stage_module(device, pre, &pm, mods, nmods, cap);
|
||||
if (clip > 0) {
|
||||
if (have_frag) {
|
||||
if (rewrite_fragment(&fm, (uint32_t)(loc + 1), (uint32_t)clip) == 0) set_stage_module(device, frag, &fm, mods, nmods, cap);
|
||||
} else {
|
||||
VKB_ONCE(VKB_LOG_WARN, "emulation: clip distances in a pipeline without a fragment shader are not applied (logged once)");
|
||||
}
|
||||
}
|
||||
VKB_DBG("emulation: pipeline with %d clip distance(s) rewritten at location %d", clip, loc + 1);
|
||||
spv_free(&pm);
|
||||
if (have_frag) spv_free(&fm);
|
||||
}
|
||||
|
||||
/* A vertex shader that reads BaseInstance as 0 (divisor emulation splits draws, which moves
|
||||
* BaseInstance; DXVK derives SV_InstanceID from it). VK_NULL_HANDLE when the shader never reads it. */
|
||||
VkShaderModule vkb_emu_shader_zero_base_instance(vkb_emu_device *e, VkDevice device, const VkPipelineShaderStageCreateInfo *vs)
|
||||
{
|
||||
const uint32_t *code;
|
||||
size_t size;
|
||||
if (!e->shaders || !stage_code(e, vs, &code, &size)) return VK_NULL_HANDLE;
|
||||
spv_mod m;
|
||||
if (spv_parse(&m, code, size) != 0) return VK_NULL_HANDLE;
|
||||
int in_block;
|
||||
uint32_t var = builtin_var(&m, SpvBuiltInBaseInstance, SpvStorageClassInput, &in_block);
|
||||
VkShaderModule out = VK_NULL_HANDLE;
|
||||
if (var) {
|
||||
int d = spv_find_def(&m, var);
|
||||
int p = d >= 0 ? spv_find_def(&m, m.ins[d].w[0]) : -1;
|
||||
uint32_t type = p >= 0 ? m.ins[p].w[2] : 0;
|
||||
int td = spv_find_def(&m, type);
|
||||
uint32_t zero = 0;
|
||||
if (td >= 0 && m.ins[td].op == SpvOpTypeInt) {
|
||||
zero = spv_new_id(&m);
|
||||
uint32_t ops[3] = {type, zero, 0};
|
||||
spv_insert(&m, spv_types_end(&m), SpvOpConstant, ops, 3);
|
||||
}
|
||||
int changed = 0;
|
||||
for (uint32_t i = 0; zero && i < m.count; i++) {
|
||||
spv_inst *in = &m.ins[i];
|
||||
if (in->op == SpvOpLoad && in->w[2] == var) {
|
||||
/* %r = OpLoad %int %BaseInstance -> %r = OpCopyObject %int %zero */
|
||||
in->op = 83; /* OpCopyObject */
|
||||
in->w[2] = zero;
|
||||
in->n = 4;
|
||||
changed = 1;
|
||||
}
|
||||
}
|
||||
if (changed) make_module(device, &m, &out);
|
||||
}
|
||||
spv_free(&m);
|
||||
return out;
|
||||
}
|
||||
|
||||
void vkb_emu_shader_install(vkb_srv_table *dev)
|
||||
{
|
||||
vkb_emu_device *e = dev->emu;
|
||||
if (!(e->flags & SHADER_STORE)) return;
|
||||
shader_state *s = calloc(1, sizeof(*s));
|
||||
pthread_mutex_init(&s->lock, NULL);
|
||||
e->shaders = s;
|
||||
dev->dt.vkCreateShaderModule = emu_CreateShaderModule;
|
||||
dev->dt.vkDestroyShaderModule = emu_DestroyShaderModule;
|
||||
}
|
||||
|
||||
void vkb_emu_shader_uninstall(vkb_srv_table *dev)
|
||||
{
|
||||
shader_state *s = dev->emu->shaders;
|
||||
if (!s) return;
|
||||
for (int i = 0; i < 1024; i++) {
|
||||
while (s->mods[i]) {
|
||||
shader_rec *r = s->mods[i];
|
||||
s->mods[i] = r->next;
|
||||
free(r->code);
|
||||
free(r);
|
||||
}
|
||||
}
|
||||
pthread_mutex_destroy(&s->lock);
|
||||
free(s);
|
||||
dev->emu->shaders = NULL;
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Instances, devices and the startup self-test.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
vkb_pd_knowledge vkb_pds[VKB_MAX_PDS];
|
||||
int vkb_npds;
|
||||
|
||||
static int has_ext(const VkExtensionProperties *e, uint32_t n, const char *name)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (!strcmp(e[i].extensionName, name)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
const vkb_pd_knowledge *vkb_pd_lookup(const vkb_dispatch *dt, VkPhysicalDevice pd)
|
||||
{
|
||||
VkPhysicalDeviceIDProperties id = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
|
||||
VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
|
||||
if (!dt->vkGetPhysicalDeviceProperties2) return NULL;
|
||||
dt->vkGetPhysicalDeviceProperties2(pd, &p2);
|
||||
for (int i = 0; i < vkb_npds; i++)
|
||||
if (vkb_pds[i].valid && !memcmp(vkb_pds[i].uuid, id.deviceUUID, VK_UUID_SIZE)) return &vkb_pds[i];
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* What the self-test found, for a later session's log (the in-app server tests once). */
|
||||
void vkb_log_summary(void)
|
||||
{
|
||||
for (int i = 0; i < vkb_npds; i++) {
|
||||
const vkb_pd_knowledge *k = &vkb_pds[i];
|
||||
if (k->valid)
|
||||
VKB_INFO("%s: memory sharing = %s, missing 0x%x, emulating 0x%x (from the first session's self-test)", k->name,
|
||||
vkb_mem_strategy_name(k->info.strategy), k->info.missing, k->info.emu);
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ startup self-test */
|
||||
|
||||
static void log_device(const vkb_dispatch *dt, VkPhysicalDevice pd, const VkPhysicalDeviceProperties *p)
|
||||
{
|
||||
VKB_INFO("GPU: %s (vendor 0x%04x device 0x%04x, Vulkan %u.%u.%u, driver 0x%08x)", p->deviceName,
|
||||
p->vendorID, p->deviceID, VK_API_VERSION_MAJOR(p->apiVersion), VK_API_VERSION_MINOR(p->apiVersion),
|
||||
VK_API_VERSION_PATCH(p->apiVersion), p->driverVersion);
|
||||
VkPhysicalDeviceFeatures f;
|
||||
dt->vkGetPhysicalDeviceFeatures(pd, &f);
|
||||
#define F(x) #x, f.x
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(textureCompressionBC), F(shaderClipDistance),
|
||||
F(shaderCullDistance), F(geometryShader), F(tessellationShader), F(depthClamp), F(shaderFloat64), F(shaderInt64));
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(multiViewport), F(independentBlend), F(logicOp),
|
||||
F(fillModeNonSolid), F(dualSrcBlend), F(sampleRateShading), F(depthBiasClamp), F(wideLines));
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(drawIndirectFirstInstance), F(multiDrawIndirect),
|
||||
F(occlusionQueryPrecise), F(pipelineStatisticsQuery), F(vertexPipelineStoresAndAtomics),
|
||||
F(fragmentStoresAndAtomics), F(shaderStorageImageWriteWithoutFormat), F(imageCubeArray));
|
||||
VKB_INFO("features: %s=%u %s=%u %s=%u %s=%u %s=%u %s=%u", F(robustBufferAccess), F(fullDrawIndexUint32), F(samplerAnisotropy),
|
||||
F(depthBounds), F(largePoints), F(shaderStorageImageExtendedFormats));
|
||||
#undef F
|
||||
uint32_t n = 0;
|
||||
dt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, NULL);
|
||||
VkExtensionProperties *e = calloc(n ? n : 1, sizeof(*e));
|
||||
dt->vkEnumerateDeviceExtensionProperties(pd, NULL, &n, e);
|
||||
static const char *const watch[] = {
|
||||
"VK_EXT_depth_clip_enable", "VK_EXT_vertex_attribute_divisor", "VK_KHR_vertex_attribute_divisor",
|
||||
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier", "VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_host", "VK_ANDROID_external_memory_android_hardware_buffer",
|
||||
"VK_KHR_external_semaphore_fd", "VK_KHR_external_fence_fd", "VK_EXT_queue_family_foreign",
|
||||
"VK_EXT_robustness2", "VK_EXT_transform_feedback", "VK_EXT_custom_border_color",
|
||||
"VK_EXT_mutable_descriptor_type", "VK_VALVE_mutable_descriptor_type", "VK_EXT_extended_dynamic_state3",
|
||||
"VK_EXT_graphics_pipeline_library", "VK_EXT_physical_device_drm", "VK_KHR_push_descriptor",
|
||||
"VK_EXT_descriptor_indexing", "VK_KHR_timeline_semaphore", "VK_EXT_memory_budget",
|
||||
"VK_KHR_maintenance5", "VK_EXT_line_rasterization", "VK_EXT_provoking_vertex",
|
||||
};
|
||||
char line[1024];
|
||||
size_t len = 0;
|
||||
line[0] = 0;
|
||||
for (size_t i = 0; i < sizeof(watch) / sizeof(watch[0]); i++) {
|
||||
int ok = has_ext(e, n, watch[i]);
|
||||
len += (size_t)snprintf(line + len, sizeof(line) - len, "%s%s%s", len ? " " : "", ok ? "+" : "-", watch[i] + 3);
|
||||
if (len > 700 || i + 1 == sizeof(watch) / sizeof(watch[0])) {
|
||||
VKB_INFO("extensions: %s", line);
|
||||
len = 0;
|
||||
line[0] = 0;
|
||||
}
|
||||
}
|
||||
VKB_INFO("%u device extensions in total", n);
|
||||
/* All of them, until the device runs show which ones the server's process sees (it is not an
|
||||
* app process, and saw fewer than the capability viewer on the same tablet). */
|
||||
len = 0;
|
||||
line[0] = 0;
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
len += (size_t)snprintf(line + len, sizeof(line) - len, "%s%s:%u", len ? " " : "", e[i].extensionName + 3, e[i].specVersion);
|
||||
if (len > 700 || i + 1 == n) {
|
||||
VKB_INFO(" all: %s", line);
|
||||
len = 0;
|
||||
line[0] = 0;
|
||||
}
|
||||
}
|
||||
free(e);
|
||||
VkPhysicalDeviceMemoryProperties mp;
|
||||
dt->vkGetPhysicalDeviceMemoryProperties(pd, &mp);
|
||||
for (uint32_t i = 0; i < mp.memoryHeapCount; i++)
|
||||
VKB_INFO("memory heap %u: %llu MB flags 0x%x", i, (unsigned long long)(mp.memoryHeaps[i].size >> 20), mp.memoryHeaps[i].flags);
|
||||
for (uint32_t i = 0; i < mp.memoryTypeCount; i++)
|
||||
VKB_INFO("memory type %u: heap %u flags 0x%x", i, mp.memoryTypes[i].heapIndex, mp.memoryTypes[i].propertyFlags);
|
||||
}
|
||||
|
||||
void vkb_selftest_all(void)
|
||||
{
|
||||
uint32_t api = VK_API_VERSION_1_0;
|
||||
if (vkb_global_dt.vkEnumerateInstanceVersion) vkb_global_dt.vkEnumerateInstanceVersion(&api);
|
||||
if (api > VK_API_VERSION_1_3) api = VK_API_VERSION_1_3;
|
||||
VkApplicationInfo app = {VK_STRUCTURE_TYPE_APPLICATION_INFO, NULL, "vkbridge-selftest", 1, "vkbridge", 1, api};
|
||||
VkInstanceCreateInfo ci = {VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, NULL, 0, &app, 0, NULL, 0, NULL};
|
||||
VkInstance inst;
|
||||
VkResult r = vkb_global_dt.vkCreateInstance(&ci, NULL, &inst);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_ERR("self-test: vkCreateInstance failed (%d); the driver is unusable", r);
|
||||
return;
|
||||
}
|
||||
vkb_dispatch dt;
|
||||
vkb_dispatch_load_instance(&dt, vkb_gipa, inst);
|
||||
uint32_t n = 0;
|
||||
dt.vkEnumeratePhysicalDevices(inst, &n, NULL);
|
||||
if (n > VKB_MAX_PDS) n = VKB_MAX_PDS;
|
||||
VkPhysicalDevice pds[VKB_MAX_PDS];
|
||||
dt.vkEnumeratePhysicalDevices(inst, &n, pds);
|
||||
VKB_INFO("self-test: loader Vulkan %u.%u, %u physical device(s)", VK_API_VERSION_MAJOR(api), VK_API_VERSION_MINOR(api), n);
|
||||
for (uint32_t i = 0; i < n; i++) {
|
||||
VkPhysicalDeviceIDProperties id = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES};
|
||||
VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &id};
|
||||
dt.vkGetPhysicalDeviceProperties2(pds[i], &p2);
|
||||
log_device(&dt, pds[i], &p2.properties);
|
||||
vkb_pd_knowledge *k = &vkb_pds[vkb_npds++];
|
||||
memcpy(k->uuid, id.deviceUUID, VK_UUID_SIZE);
|
||||
snprintf(k->name, sizeof(k->name), "%s", p2.properties.deviceName);
|
||||
k->info.real_api_version = p2.properties.apiVersion;
|
||||
vkb_mem_selftest(k, inst, &dt, pds[i]);
|
||||
k->info.emu_available = vkb_emu_detect(&dt, pds[i], &k->info.missing);
|
||||
k->info.emu = k->info.emu_available;
|
||||
const char *emu_env = getenv("VKBRIDGE_EMULATE");
|
||||
if (emu_env && !strcmp(emu_env, "0")) k->info.emu = 0;
|
||||
k->valid = 1;
|
||||
VKB_INFO("%s: memory sharing = %s, missing 0x%x, emulating 0x%x", k->name, vkb_mem_strategy_name(k->info.strategy),
|
||||
k->info.missing, k->info.emu);
|
||||
}
|
||||
dt.vkDestroyInstance(inst, NULL);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ instance */
|
||||
|
||||
void vkb_sv_vkCreateInstance(vkb_srv_call *c)
|
||||
{
|
||||
VkInstanceCreateInfo *ci = NULL;
|
||||
if (vkb_dec_u8(&c->d)) {
|
||||
ci = vkb_dec_alloc(&c->d, sizeof(*ci));
|
||||
if (ci) vkb_dec_VkInstanceCreateInfo(&c->d, ci);
|
||||
}
|
||||
uint8_t want_out = vkb_dec_u8(&c->d);
|
||||
if (c->d.err || !ci || !want_out) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkInstance inst = VK_NULL_HANDLE;
|
||||
VkResult r = vkb_global_dt.vkCreateInstance(ci, NULL, &inst);
|
||||
uint32_t id = 0;
|
||||
if (r == VK_SUCCESS) {
|
||||
vkb_srv_table *t = calloc(1, sizeof(*t));
|
||||
pthread_mutex_init(&t->lock, NULL);
|
||||
t->instance = inst;
|
||||
t->proc = c->conn->proc;
|
||||
t->api_version = ci->pApplicationInfo ? ci->pApplicationInfo->apiVersion : VK_API_VERSION_1_0;
|
||||
vkb_dispatch_load_instance(&t->real, vkb_gipa, inst);
|
||||
t->dt = t->real;
|
||||
id = vkb_table_register(t);
|
||||
if (!id) {
|
||||
t->real.vkDestroyInstance(inst, NULL);
|
||||
free(t);
|
||||
r = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
inst = VK_NULL_HANDLE;
|
||||
} else {
|
||||
VKB_INFO("instance %u created (app \"%s\", engine \"%s\", Vulkan %u.%u)", id,
|
||||
ci->pApplicationInfo && ci->pApplicationInfo->pApplicationName ? ci->pApplicationInfo->pApplicationName : "",
|
||||
ci->pApplicationInfo && ci->pApplicationInfo->pEngineName ? ci->pApplicationInfo->pEngineName : "",
|
||||
VK_API_VERSION_MAJOR(t->api_version), VK_API_VERSION_MINOR(t->api_version));
|
||||
}
|
||||
} else {
|
||||
VKB_ERR("vkCreateInstance failed: %d", r);
|
||||
}
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
vkb_enc_u64(&c->r, (uint64_t)(uintptr_t)inst);
|
||||
vkb_enc_u32(&c->r, id);
|
||||
}
|
||||
|
||||
void vkb_sv_vkDestroyInstance(vkb_srv_call *c)
|
||||
{
|
||||
VkInstance inst = (VkInstance)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (!t || t->is_device || t->instance != inst) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_table_unregister(t);
|
||||
t->real.vkDestroyInstance(inst, NULL);
|
||||
pthread_mutex_destroy(&t->lock);
|
||||
free(t);
|
||||
c->table = NULL;
|
||||
}
|
||||
|
||||
void vkb_sv_vkbQueryServer(vkb_srv_call *c)
|
||||
{
|
||||
VkPhysicalDevice pd = (VkPhysicalDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
if (c->d.err || !c->table) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
const vkb_pd_knowledge *k = vkb_pd_lookup(c->dt, pd);
|
||||
vkb_server_pd_info info;
|
||||
memset(&info, 0, sizeof(info));
|
||||
if (k) info = k->info;
|
||||
else VKB_WARN("query for a physical device the self-test did not see");
|
||||
vkb_enc_raw(&c->r, &info, sizeof(info));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ device */
|
||||
|
||||
static int list_has(const char *const *l, uint32_t n, const char *s)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (l[i] && !strcmp(l[i], s)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void vkb_sv_vkCreateDevice(vkb_srv_call *c)
|
||||
{
|
||||
VkPhysicalDevice pd = (VkPhysicalDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDeviceCreateInfo *ci = NULL;
|
||||
if (vkb_dec_u8(&c->d)) {
|
||||
ci = vkb_dec_alloc(&c->d, sizeof(*ci));
|
||||
if (ci) vkb_dec_VkDeviceCreateInfo(&c->d, ci);
|
||||
}
|
||||
uint8_t want_out = vkb_dec_u8(&c->d);
|
||||
vkb_srv_table *inst = c->table;
|
||||
if (c->d.err || !ci || !want_out || !inst || inst->is_device) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
const vkb_pd_knowledge *k = vkb_pd_lookup(&inst->real, pd);
|
||||
uint32_t strategy = k ? k->info.strategy : VKB_MEM_NONE;
|
||||
uint32_t emu = k ? k->info.emu : 0;
|
||||
|
||||
/* Extensions the server itself needs (memory sharing), when the driver has them. */
|
||||
uint32_t avail_n = 0;
|
||||
inst->real.vkEnumerateDeviceExtensionProperties(pd, NULL, &avail_n, NULL);
|
||||
VkExtensionProperties *avail = vkb_dec_alloc(&c->d, (avail_n ? avail_n : 1) * sizeof(*avail));
|
||||
inst->real.vkEnumerateDeviceExtensionProperties(pd, NULL, &avail_n, avail);
|
||||
uint32_t extra_n = 0;
|
||||
const char *const *extra = vkb_mem_required_extensions(strategy, &extra_n);
|
||||
const char **exts = vkb_dec_alloc(&c->d, (ci->enabledExtensionCount + extra_n + 10) * sizeof(char *));
|
||||
uint32_t n = 0;
|
||||
for (uint32_t i = 0; i < ci->enabledExtensionCount; i++) {
|
||||
const char *e = ci->ppEnabledExtensionNames[i];
|
||||
if (!has_ext(avail, avail_n, e)) {
|
||||
VKB_DBG("device extension %s is emulated or client-side; not passed to the driver", e);
|
||||
continue;
|
||||
}
|
||||
exts[n++] = e;
|
||||
}
|
||||
for (uint32_t i = 0; i < extra_n; i++)
|
||||
if (has_ext(avail, avail_n, extra[i]) && !list_has(exts, n, extra[i])) exts[n++] = extra[i];
|
||||
/* What the client's presentation code uses on every device (dma-buf swapchains, sync fds). */
|
||||
static const char *const wsi_exts[] = {
|
||||
"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf", "VK_KHR_image_format_list",
|
||||
"VK_EXT_image_drm_format_modifier", "VK_KHR_external_semaphore_fd", "VK_KHR_external_fence_fd",
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(wsi_exts) / sizeof(wsi_exts[0]); i++)
|
||||
if (has_ext(avail, avail_n, wsi_exts[i]) && !list_has(exts, n, wsi_exts[i])) exts[n++] = wsi_exts[i];
|
||||
/* The BC decoder binds its buffer and image with push descriptors. */
|
||||
if ((emu & VKB_EMU_BCN) && has_ext(avail, avail_n, "VK_KHR_push_descriptor") && !list_has(exts, n, "VK_KHR_push_descriptor"))
|
||||
exts[n++] = "VK_KHR_push_descriptor";
|
||||
ci->enabledExtensionCount = n;
|
||||
ci->ppEnabledExtensionNames = exts;
|
||||
ci->enabledLayerCount = 0;
|
||||
ci->ppEnabledLayerNames = NULL;
|
||||
|
||||
vkb_emu_device_create_info(inst, pd, emu, ci, c->d.arena);
|
||||
|
||||
VkDevice dev = VK_NULL_HANDLE;
|
||||
VkResult r = inst->real.vkCreateDevice(pd, ci, NULL, &dev);
|
||||
uint32_t id = 0;
|
||||
if (r == VK_SUCCESS) {
|
||||
vkb_srv_table *t = calloc(1, sizeof(*t));
|
||||
pthread_mutex_init(&t->lock, NULL);
|
||||
t->is_device = 1;
|
||||
t->proc = c->conn->proc;
|
||||
t->instance = inst->instance;
|
||||
t->device = dev;
|
||||
t->physical = pd;
|
||||
t->parent = inst;
|
||||
t->pd = k;
|
||||
t->api_version = inst->api_version;
|
||||
t->real = inst->real;
|
||||
PFN_vkGetDeviceProcAddr gdpa = (PFN_vkGetDeviceProcAddr)vkb_gipa(inst->instance, "vkGetDeviceProcAddr");
|
||||
vkb_dispatch_load_device(&t->real, gdpa, dev);
|
||||
t->dt = t->real;
|
||||
id = vkb_table_register(t);
|
||||
if (!id) {
|
||||
t->real.vkDestroyDevice(dev, NULL);
|
||||
free(t);
|
||||
dev = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
} else {
|
||||
vkb_emu_device_init(t, emu);
|
||||
vkb_pcache_device_init(t);
|
||||
vkb_dsmap_device_init(t);
|
||||
vkb_spvfix_device_init(t);
|
||||
vkb_cbtrack_device_init(t); /* last: it wraps what the others installed */
|
||||
VKB_INFO("device %u created on %s (%u extensions, memory sharing %s)", id, k ? k->name : "?", n,
|
||||
vkb_mem_strategy_name(strategy));
|
||||
for (uint32_t i = 0; i < n; i++) VKB_DBG(" device extension %s", exts[i]);
|
||||
}
|
||||
} else {
|
||||
VKB_ERR("vkCreateDevice failed: %d (%u extensions)", r, n);
|
||||
for (uint32_t i = 0; i < n; i++) VKB_ERR(" requested %s", exts[i]);
|
||||
}
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
vkb_enc_u64(&c->r, (uint64_t)(uintptr_t)dev);
|
||||
vkb_enc_u32(&c->r, id);
|
||||
}
|
||||
|
||||
void vkb_sv_vkDestroyDevice(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (!t || !t->is_device || t->device != dev) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
vkb_table_unregister(t);
|
||||
vkb_cbtrack_device_destroy(t);
|
||||
vkb_spvfix_device_destroy(t);
|
||||
vkb_dsmap_device_destroy(t);
|
||||
vkb_pcache_device_destroy(t);
|
||||
vkb_emu_device_destroy(t);
|
||||
vkb_mem_free_all(t);
|
||||
t->real.vkDestroyDevice(dev, NULL);
|
||||
VKB_INFO("device %u destroyed", t->id);
|
||||
pthread_mutex_destroy(&t->lock);
|
||||
free(t);
|
||||
c->table = NULL;
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* vkbridge server entry point.
|
||||
*
|
||||
* libvkbridge_server.so --socket <path> [--log <file>] [--vulkan <libvulkan>] [--cache-dir <dir>] [--selftest]
|
||||
*
|
||||
* Packaged as a "library" so Android extracts it into the native library directory, from where
|
||||
* the app executes it like proot. It loads the system Vulkan loader (on the device: the vendor's
|
||||
* Mali driver behind /system/lib64/libvulkan.so), runs a self-test that decides how mapped memory
|
||||
* is shared with the Linux side, then serves the session's Vulkan calls until it is killed or its
|
||||
* parent dies.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/un.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include <android/log.h>
|
||||
#elif defined(__GLIBC__)
|
||||
#include <execinfo.h>
|
||||
#endif
|
||||
|
||||
PFN_vkGetInstanceProcAddr vkb_gipa;
|
||||
vkb_dispatch vkb_global_dt;
|
||||
int vkb_verbose;
|
||||
|
||||
static FILE *log_file;
|
||||
static int log_level = VKB_LOG_INFO;
|
||||
static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
int vkb_log_level(void) { return log_level; }
|
||||
|
||||
void vkb_log(int level, const char *fmt, ...)
|
||||
{
|
||||
if (level > log_level) return;
|
||||
char msg[2048];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(msg, sizeof(msg), fmt, ap);
|
||||
va_end(ap);
|
||||
static const char *const tags[] = {"E", "W", "I", "D"};
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
struct tm tm;
|
||||
localtime_r(&ts.tv_sec, &tm);
|
||||
pthread_mutex_lock(&log_lock);
|
||||
FILE *f = log_file ? log_file : stderr;
|
||||
fprintf(f, "%02d:%02d:%02d.%03ld vkbridge-server %s %s\n", tm.tm_hour, tm.tm_min, tm.tm_sec,
|
||||
ts.tv_nsec / 1000000, tags[level & 3], msg);
|
||||
fflush(f);
|
||||
pthread_mutex_unlock(&log_lock);
|
||||
#ifdef __ANDROID__
|
||||
static const int prio[] = {ANDROID_LOG_ERROR, ANDROID_LOG_WARN, ANDROID_LOG_INFO, ANDROID_LOG_DEBUG};
|
||||
__android_log_write(prio[level & 3], "vkbridge", msg);
|
||||
#endif
|
||||
}
|
||||
|
||||
extern __thread const char *vkb_srv_current_cmd;
|
||||
|
||||
/* A crash is almost always the driver's: say in which call, then die as we would have. */
|
||||
__attribute__((unused)) static void on_crash(int sig)
|
||||
{
|
||||
char buf[256];
|
||||
const char *cmd = vkb_srv_current_cmd ? vkb_srv_current_cmd : "(no Vulkan call)";
|
||||
int n = snprintf(buf, sizeof(buf), "vkbridge-server E crashed with signal %d in %s\n", sig, cmd);
|
||||
if (log_file) {
|
||||
if (write(fileno(log_file), buf, (size_t)n) < 0) {}
|
||||
}
|
||||
if (write(2, buf, (size_t)n) < 0) {}
|
||||
#ifdef __ANDROID__
|
||||
__android_log_write(ANDROID_LOG_FATAL, "vkbridge", buf);
|
||||
#elif defined(__GLIBC__)
|
||||
void *frames[32];
|
||||
int nf = backtrace(frames, 32);
|
||||
backtrace_symbols_fd(frames, nf, 2);
|
||||
if (log_file) backtrace_symbols_fd(frames, nf, fileno(log_file));
|
||||
#endif
|
||||
signal(sig, SIG_DFL);
|
||||
raise(sig);
|
||||
}
|
||||
|
||||
static void *load_vulkan(const char *override)
|
||||
{
|
||||
const char *names[] = {
|
||||
override,
|
||||
#ifdef __ANDROID__
|
||||
"libvulkan.so",
|
||||
#else
|
||||
"libvulkan.so.1",
|
||||
"libvulkan.so",
|
||||
#endif
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {
|
||||
if (!names[i]) continue;
|
||||
void *h = dlopen(names[i], RTLD_NOW | RTLD_LOCAL);
|
||||
if (h) {
|
||||
VKB_INFO("Vulkan loader: %s", names[i]);
|
||||
return h;
|
||||
}
|
||||
VKB_WARN("cannot open %s: %s", names[i], dlerror());
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static int listen_on(const char *path)
|
||||
{
|
||||
struct sockaddr_un a;
|
||||
if (strlen(path) >= sizeof(a.sun_path)) {
|
||||
VKB_ERR("socket path too long (%zu bytes): %s", strlen(path), path);
|
||||
return -1;
|
||||
}
|
||||
int fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) {
|
||||
VKB_ERR("socket: %s", strerror(errno));
|
||||
return -1;
|
||||
}
|
||||
memset(&a, 0, sizeof(a));
|
||||
a.sun_family = AF_UNIX;
|
||||
strcpy(a.sun_path, path);
|
||||
unlink(path);
|
||||
if (bind(fd, (struct sockaddr *)&a, sizeof(a)) < 0) {
|
||||
VKB_ERR("bind %s: %s", path, strerror(errno));
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
chmod(path, 0600);
|
||||
if (listen(fd, 128) < 0) {
|
||||
VKB_ERR("listen: %s", strerror(errno));
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* Opens (or switches to) the log file; NULL keeps logging to stderr/logcat only. */
|
||||
static void open_log(const char *path)
|
||||
{
|
||||
FILE *f = path ? fopen(path, "ae") : NULL;
|
||||
if (path && !f) fprintf(stderr, "vkbridge-server: cannot open log %s: %s\n", path, strerror(errno));
|
||||
pthread_mutex_lock(&log_lock);
|
||||
FILE *old = log_file;
|
||||
log_file = f;
|
||||
pthread_mutex_unlock(&log_lock);
|
||||
if (old) fclose(old);
|
||||
}
|
||||
|
||||
/* Loads the Vulkan loader and runs the self-test; 0 when there is nothing to serve. */
|
||||
static int server_init(const char *vk_lib, const char *cache_dir)
|
||||
{
|
||||
VKB_INFO("starting (pid %d, protocol %016llx)", getpid(), (unsigned long long)VKB_PROTOCOL_HASH);
|
||||
void *lib = load_vulkan(vk_lib);
|
||||
if (!lib) {
|
||||
VKB_ERR("no Vulkan loader; nothing to serve");
|
||||
return 0;
|
||||
}
|
||||
vkb_gipa = (PFN_vkGetInstanceProcAddr)dlsym(lib, "vkGetInstanceProcAddr");
|
||||
if (!vkb_gipa) {
|
||||
VKB_ERR("the Vulkan loader exports no vkGetInstanceProcAddr");
|
||||
return 0;
|
||||
}
|
||||
vkb_dispatch_load_instance(&vkb_global_dt, vkb_gipa, VK_NULL_HANDLE);
|
||||
vkb_pcache_set_dir(cache_dir);
|
||||
vkb_selftest_all();
|
||||
return 1;
|
||||
}
|
||||
|
||||
#ifdef VKB_JNI
|
||||
/*
|
||||
* In the app's own process (the default on the device): Android chooses the GPU driver, Samsung's
|
||||
* updatable one included, while the app starts up, and only for the app's process - a separate
|
||||
* executable gets the plain /vendor driver, which on the Tab S10+ lacked VK_EXT_robustness2 and
|
||||
* more that the app itself sees. Winlator's Vortek runs its server in-process for the same reason.
|
||||
* Started once and kept for the app's life; each session only points the log at its own folder.
|
||||
*/
|
||||
#include <jni.h>
|
||||
|
||||
static pthread_mutex_t jni_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static char jni_socket[256];
|
||||
static int jni_state; /* 0 not started, 1 serving, -1 failed */
|
||||
|
||||
static void *serve_thread(void *arg)
|
||||
{
|
||||
vkb_srv_serve((int)(intptr_t)arg);
|
||||
VKB_ERR("in-app server stopped serving");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static char *jstr(JNIEnv *env, jstring s)
|
||||
{
|
||||
if (!s) return NULL;
|
||||
const char *c = (*env)->GetStringUTFChars(env, s, NULL);
|
||||
char *r = c ? strdup(c) : NULL;
|
||||
if (c) (*env)->ReleaseStringUTFChars(env, s, c);
|
||||
return r;
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_com_droiddeck_launcher_gpu_VkBridgeNative_nativeStart(JNIEnv *env, jclass cls, jstring jsocket,
|
||||
jstring jlog, jstring jcache)
|
||||
{
|
||||
(void)cls;
|
||||
char *sock = jstr(env, jsocket), *logp = jstr(env, jlog), *cache = jstr(env, jcache);
|
||||
pthread_mutex_lock(&jni_lock);
|
||||
open_log(logp);
|
||||
if (getenv("VKBRIDGE_DEBUG")) {
|
||||
vkb_verbose = 1;
|
||||
log_level = VKB_LOG_DEBUG;
|
||||
}
|
||||
int ok = 0;
|
||||
if (jni_state == 1 && sock && !strcmp(sock, jni_socket) && access(sock, F_OK) == 0) {
|
||||
VKB_INFO("in-app server already serving at %s (pid %d); this session's log continues here", sock, getpid());
|
||||
vkb_log_summary();
|
||||
ok = 1;
|
||||
} else if (jni_state == 1) {
|
||||
VKB_ERR("in-app server serves %s, asked for %s (or its socket is gone)", jni_socket, sock ? sock : "(none)");
|
||||
} else if (jni_state == 0 && sock) {
|
||||
jni_state = -1;
|
||||
if (server_init(NULL, cache)) {
|
||||
int lfd = listen_on(sock);
|
||||
pthread_t t;
|
||||
if (lfd >= 0 && pthread_create(&t, NULL, serve_thread, (void *)(intptr_t)lfd) == 0) {
|
||||
pthread_detach(t);
|
||||
snprintf(jni_socket, sizeof(jni_socket), "%s", sock);
|
||||
jni_state = 1;
|
||||
ok = 1;
|
||||
VKB_INFO("listening on %s (in the app's process)", sock);
|
||||
}
|
||||
}
|
||||
}
|
||||
pthread_mutex_unlock(&jni_lock);
|
||||
free(sock);
|
||||
free(logp);
|
||||
free(cache);
|
||||
return ok;
|
||||
}
|
||||
#else
|
||||
static void usage(void)
|
||||
{
|
||||
fprintf(stderr, "usage: vkbridge-server --socket PATH [--log FILE] [--vulkan LIB] [--cache-dir DIR] [--selftest] [--verbose]\n");
|
||||
}
|
||||
|
||||
static pid_t parent_pid;
|
||||
|
||||
static void *parent_watch(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
sleep(1);
|
||||
if (getppid() != parent_pid) {
|
||||
VKB_INFO("the app (pid %d) is gone; exiting", (int)parent_pid);
|
||||
_exit(0);
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void start_parent_watch(void)
|
||||
{
|
||||
parent_pid = getppid();
|
||||
if (parent_pid <= 1) return; /* started by init or a shell that already left: nothing to watch */
|
||||
pthread_t t;
|
||||
pthread_attr_t a;
|
||||
pthread_attr_init(&a);
|
||||
pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
|
||||
pthread_create(&t, &a, parent_watch, NULL);
|
||||
pthread_attr_destroy(&a);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
const char *sock_path = getenv("VKBRIDGE_SOCKET");
|
||||
const char *log_path = getenv("VKBRIDGE_SERVER_LOG");
|
||||
const char *vk_lib = getenv("VKBRIDGE_SERVER_VULKAN");
|
||||
const char *cache_dir = getenv("VKBRIDGE_CACHE_DIR");
|
||||
int selftest_only = 0;
|
||||
for (int i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--socket") && i + 1 < argc) sock_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--log") && i + 1 < argc) log_path = argv[++i];
|
||||
else if (!strcmp(argv[i], "--vulkan") && i + 1 < argc) vk_lib = argv[++i];
|
||||
else if (!strcmp(argv[i], "--cache-dir") && i + 1 < argc) cache_dir = argv[++i];
|
||||
else if (!strcmp(argv[i], "--selftest")) selftest_only = 1;
|
||||
else if (!strcmp(argv[i], "--verbose")) vkb_verbose = 1;
|
||||
else {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
if (getenv("VKBRIDGE_DEBUG")) vkb_verbose = 1;
|
||||
if (vkb_verbose) log_level = VKB_LOG_DEBUG;
|
||||
open_log(log_path);
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
signal(SIGSEGV, on_crash);
|
||||
signal(SIGBUS, on_crash);
|
||||
signal(SIGABRT, on_crash);
|
||||
signal(SIGILL, on_crash);
|
||||
signal(SIGFPE, on_crash);
|
||||
/* The server is the app's child: when the app dies, so does the session's GPU. Not with
|
||||
* PR_SET_PDEATHSIG: that fires when the parent THREAD exits, and Android's ProcessBuilder forks
|
||||
* from the session's start-up thread, which ends right after starting the guest (the server
|
||||
* was killed 6 ms into the first device run). The parent process is watched instead. */
|
||||
start_parent_watch();
|
||||
|
||||
if (!server_init(vk_lib, cache_dir)) return 1;
|
||||
if (selftest_only) return vkb_npds > 0 ? 0 : 1;
|
||||
|
||||
if (!sock_path) {
|
||||
usage();
|
||||
return 2;
|
||||
}
|
||||
int lfd = listen_on(sock_path);
|
||||
if (lfd < 0) return 1;
|
||||
VKB_INFO("listening on %s", sock_path);
|
||||
vkb_srv_serve(lfd);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,834 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Host-visible memory shared with the client.
|
||||
*
|
||||
* A Linux program maps Vulkan memory and writes to it directly; those writes must land in the
|
||||
* pages the GPU reads. The server makes such memory shareable in one of three ways, chosen per
|
||||
* GPU by a self-test at startup that checks the GPU and both CPU mappings really see the same
|
||||
* bytes:
|
||||
* hostptr the client creates a memfd, the server maps it and imports it
|
||||
* (VK_EXT_external_memory_host);
|
||||
* dmabuf the server allocates exportable memory and hands the client its dma-buf
|
||||
* (VK_EXT_external_memory_dma_buf), which the client maps;
|
||||
* ahb the server allocates a BLOB AHardwareBuffer, imports it, and hands the client the
|
||||
* dma-buf behind it (Android only);
|
||||
* dmaheap the server allocates from /dev/dma_heap (system-uncached, else system), imports that
|
||||
* dma-buf into the driver and hands it to the client - what GameNative's wrapper does on
|
||||
* Mali when the driver will not export one (Android; root-only on desktops).
|
||||
* VKBRIDGE_MEMORY=hostptr|dmabuf|dmaheap|ahb forces one.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#ifdef __ANDROID__
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR 1
|
||||
#endif
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <linux/dma-heap.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#ifdef __ANDROID__
|
||||
#include <vulkan/vulkan_android.h>
|
||||
/* libnativewindow, opened at run time (getNativeHandle is not in the NDK headers). */
|
||||
typedef struct {
|
||||
uint32_t width, height, layers, format;
|
||||
uint64_t usage;
|
||||
uint32_t stride, rfu0;
|
||||
uint64_t rfu1;
|
||||
} vkb_ahb_desc;
|
||||
typedef struct {
|
||||
int version, numFds, numInts;
|
||||
int data[0];
|
||||
} vkb_native_handle;
|
||||
static int (*p_AHardwareBuffer_allocate)(const vkb_ahb_desc *, struct AHardwareBuffer **);
|
||||
static void (*p_AHardwareBuffer_release)(struct AHardwareBuffer *);
|
||||
static const vkb_native_handle *(*p_AHardwareBuffer_getNativeHandle)(const struct AHardwareBuffer *);
|
||||
#define AHB_FORMAT_BLOB 0x21
|
||||
#define AHB_USAGE_CPU_READ_OFTEN 3ull
|
||||
#define AHB_USAGE_CPU_WRITE_OFTEN (3ull << 4)
|
||||
#define AHB_USAGE_GPU_DATA_BUFFER (1ull << 24)
|
||||
|
||||
static int ahb_load(void)
|
||||
{
|
||||
static int state;
|
||||
if (state) return state > 0;
|
||||
void *h = dlopen("libnativewindow.so", RTLD_NOW);
|
||||
if (!h) h = dlopen("libandroid.so", RTLD_NOW);
|
||||
if (h) {
|
||||
p_AHardwareBuffer_allocate = dlsym(h, "AHardwareBuffer_allocate");
|
||||
p_AHardwareBuffer_release = dlsym(h, "AHardwareBuffer_release");
|
||||
p_AHardwareBuffer_getNativeHandle = dlsym(h, "AHardwareBuffer_getNativeHandle");
|
||||
}
|
||||
state = (p_AHardwareBuffer_allocate && p_AHardwareBuffer_release && p_AHardwareBuffer_getNativeHandle) ? 1 : -1;
|
||||
if (state < 0) VKB_WARN("AHardwareBuffer functions unavailable");
|
||||
return state > 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
static const char *const ext_hostptr[] = {"VK_KHR_external_memory", "VK_EXT_external_memory_host"};
|
||||
static const char *const ext_dmabuf[] = {"VK_KHR_external_memory", "VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf"};
|
||||
#ifdef __ANDROID__
|
||||
static const char *const ext_ahb[] = {"VK_KHR_external_memory", "VK_ANDROID_external_memory_android_hardware_buffer",
|
||||
"VK_EXT_queue_family_foreign", "VK_KHR_sampler_ycbcr_conversion",
|
||||
"VK_KHR_dedicated_allocation", "VK_KHR_get_memory_requirements2"};
|
||||
#endif
|
||||
|
||||
const char *const *vkb_mem_required_extensions(uint32_t strategy, uint32_t *count)
|
||||
{
|
||||
switch (strategy) {
|
||||
case VKB_MEM_HOSTPTR: *count = 2; return ext_hostptr;
|
||||
case VKB_MEM_DMABUF: *count = 3; return ext_dmabuf;
|
||||
case VKB_MEM_DMAHEAP: *count = 3; return ext_dmabuf;
|
||||
#ifdef __ANDROID__
|
||||
case VKB_MEM_AHB: *count = 6; return ext_ahb;
|
||||
#endif
|
||||
default: *count = 0; return NULL;
|
||||
}
|
||||
}
|
||||
|
||||
static uint32_t strategy_handle_type(uint32_t s)
|
||||
{
|
||||
switch (s) {
|
||||
case VKB_MEM_HOSTPTR: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
|
||||
case VKB_MEM_DMABUF: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
case VKB_MEM_DMAHEAP: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
#ifdef __ANDROID__
|
||||
case VKB_MEM_AHB: return VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID;
|
||||
#endif
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int vkb_memfd(const char *name, size_t size)
|
||||
{
|
||||
int fd = (int)syscall(SYS_memfd_create, name, 1u /* MFD_CLOEXEC */);
|
||||
if (fd < 0) return -1;
|
||||
if (ftruncate(fd, (off_t)size) < 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tracking */
|
||||
|
||||
static unsigned mem_hash(VkDeviceMemory m)
|
||||
{
|
||||
uint64_t v = (uint64_t)(uintptr_t)m;
|
||||
v ^= v >> 17;
|
||||
v *= 0x9E3779B97F4A7C15ull;
|
||||
return (unsigned)(v >> 56);
|
||||
}
|
||||
|
||||
void vkb_mem_track(vkb_srv_table *dev, vkb_srv_mem *m)
|
||||
{
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
unsigned h = mem_hash(m->mem);
|
||||
m->next = dev->mems[h];
|
||||
dev->mems[h] = m;
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
}
|
||||
|
||||
vkb_srv_mem *vkb_mem_find(vkb_srv_table *dev, VkDeviceMemory mem, int remove)
|
||||
{
|
||||
pthread_mutex_lock(&dev->lock);
|
||||
vkb_srv_mem **pp = &dev->mems[mem_hash(mem)];
|
||||
while (*pp && (*pp)->mem != mem) pp = &(*pp)->next;
|
||||
vkb_srv_mem *m = *pp;
|
||||
if (m && remove) *pp = m->next;
|
||||
pthread_mutex_unlock(&dev->lock);
|
||||
return m;
|
||||
}
|
||||
|
||||
/* Frees the server-side resources of an allocation (the VkDeviceMemory must already be freed). */
|
||||
static void mem_release_backing(vkb_srv_mem *m)
|
||||
{
|
||||
if (m->host_ptr) munmap(m->host_ptr, m->host_len);
|
||||
#ifdef __ANDROID__
|
||||
if (m->ahb) p_AHardwareBuffer_release(m->ahb);
|
||||
#endif
|
||||
free(m);
|
||||
}
|
||||
|
||||
void vkb_mem_release(vkb_srv_table *dev, vkb_srv_mem *m)
|
||||
{
|
||||
if (m->mapped) dev->real.vkUnmapMemory(dev->device, m->mem);
|
||||
dev->real.vkFreeMemory(dev->device, m->mem, NULL);
|
||||
mem_release_backing(m);
|
||||
}
|
||||
|
||||
void vkb_mem_free_all(vkb_srv_table *dev)
|
||||
{
|
||||
for (int i = 0; i < 256; i++) {
|
||||
vkb_srv_mem *m = dev->mems[i];
|
||||
dev->mems[i] = NULL;
|
||||
while (m) {
|
||||
vkb_srv_mem *n = m->next;
|
||||
vkb_mem_release(dev, m);
|
||||
m = n;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The dma-heap the dmaheap strategy allocates from, opened once: system-uncached first (the GPU
|
||||
* and the client both write through it without cache maintenance), else the cached system heap. */
|
||||
static int dmaheap_fd(void)
|
||||
{
|
||||
static int fd = -2;
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
pthread_mutex_lock(&lock);
|
||||
if (fd == -2) {
|
||||
const char *names[] = {"/dev/dma_heap/system-uncached", "/dev/dma_heap/system"};
|
||||
if (getenv("VKBRIDGE_DMAHEAP_CACHED")) names[0] = "/dev/dma_heap/system";
|
||||
fd = -1;
|
||||
for (int i = 0; i < 2 && fd < 0; i++) {
|
||||
fd = open(names[i], O_RDONLY | O_CLOEXEC);
|
||||
if (fd >= 0) VKB_INFO("dmaheap: allocating from %s", names[i]);
|
||||
else VKB_INFO("dmaheap: %s: %s", names[i], strerror(errno));
|
||||
}
|
||||
}
|
||||
int r = fd;
|
||||
pthread_mutex_unlock(&lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Unlinks every structure of type t from the chain starting at *head. */
|
||||
static void chain_drop(const void **head, VkStructureType t)
|
||||
{
|
||||
const VkBaseInStructure **pp = (const VkBaseInStructure **)head;
|
||||
while (*pp) {
|
||||
if ((*pp)->sType == t) *pp = (*pp)->pNext;
|
||||
else pp = (const VkBaseInStructure **)&((VkBaseInStructure *)*pp)->pNext;
|
||||
}
|
||||
}
|
||||
|
||||
/* The driver's vkGetDeviceProcAddr (for entry points the dispatch table does not carry). */
|
||||
PFN_vkGetDeviceProcAddr vkb_mem_gdpa;
|
||||
|
||||
/* ------------------------------------------------------------------ allocation */
|
||||
|
||||
/*
|
||||
* Allocates shared memory with strategy `s`. `ai` is the app's (or the self-test's) allocate
|
||||
* info; for hostptr, `client_fd` is the client's memfd (consumed). On success *out_fd is the fd
|
||||
* to send to the client (-1 for hostptr, where the client already has its pages).
|
||||
*/
|
||||
static VkResult alloc_shared(const vkb_dispatch *dt, VkDevice dev, uint32_t s, const VkMemoryAllocateInfo *ai,
|
||||
int client_fd, vkb_srv_mem **out, int *out_fd)
|
||||
{
|
||||
*out_fd = -1;
|
||||
*out = NULL;
|
||||
vkb_srv_mem *m = calloc(1, sizeof(*m));
|
||||
if (!m) {
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
return VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
}
|
||||
m->size = ai->allocationSize;
|
||||
m->type = ai->memoryTypeIndex;
|
||||
m->strategy = s;
|
||||
VkMemoryAllocateInfo info = *ai;
|
||||
VkResult r = VK_ERROR_FEATURE_NOT_PRESENT;
|
||||
switch (s) {
|
||||
case VKB_MEM_HOSTPTR: {
|
||||
if (client_fd < 0) break;
|
||||
void *p = mmap(NULL, (size_t)ai->allocationSize, PROT_READ | PROT_WRITE, MAP_SHARED, client_fd, 0);
|
||||
close(client_fd);
|
||||
client_fd = -1;
|
||||
if (p == MAP_FAILED) {
|
||||
VKB_ERR("hostptr: mmap of the client's memory failed: %s", strerror(errno));
|
||||
r = VK_ERROR_OUT_OF_HOST_MEMORY;
|
||||
break;
|
||||
}
|
||||
m->host_ptr = p;
|
||||
m->host_len = (size_t)ai->allocationSize;
|
||||
VkMemoryHostPointerPropertiesEXT hp = {VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};
|
||||
if (!dt->vkGetMemoryHostPointerPropertiesEXT ||
|
||||
dt->vkGetMemoryHostPointerPropertiesEXT(dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, p, &hp) != VK_SUCCESS ||
|
||||
!(hp.memoryTypeBits & (1u << ai->memoryTypeIndex))) {
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
VkImportMemoryHostPointerInfoEXT imp = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT, info.pNext,
|
||||
VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, p};
|
||||
info.pNext = &imp;
|
||||
r = dt->vkAllocateMemory(dev, &info, NULL, &m->mem);
|
||||
break;
|
||||
}
|
||||
case VKB_MEM_DMABUF: {
|
||||
VkExportMemoryAllocateInfo exp = {VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO, info.pNext,
|
||||
VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
||||
/* An export the app asked for itself is merged rather than duplicated. */
|
||||
for (VkBaseOutStructure *b = (VkBaseOutStructure *)info.pNext; b; b = b->pNext) {
|
||||
if (b->sType == VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO) {
|
||||
((VkExportMemoryAllocateInfo *)b)->handleTypes |= VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT;
|
||||
exp.sType = VK_STRUCTURE_TYPE_MAX_ENUM;
|
||||
}
|
||||
}
|
||||
if (exp.sType != VK_STRUCTURE_TYPE_MAX_ENUM) info.pNext = &exp;
|
||||
r = dt->vkAllocateMemory(dev, &info, NULL, &m->mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO("dmabuf: exportable allocation of %llu bytes (type %u) failed: %d", (unsigned long long)info.allocationSize,
|
||||
info.memoryTypeIndex, r);
|
||||
break;
|
||||
}
|
||||
VkMemoryGetFdInfoKHR gi = {VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR, NULL, m->mem, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
||||
int fd = -1;
|
||||
VkResult fr = dt->vkGetMemoryFdKHR ? dt->vkGetMemoryFdKHR(dev, &gi, &fd) : VK_ERROR_EXTENSION_NOT_PRESENT;
|
||||
if (fr != VK_SUCCESS || fd < 0) {
|
||||
VKB_INFO("dmabuf: vkGetMemoryFdKHR %s: %d (fd %d)", dt->vkGetMemoryFdKHR ? "failed" : "not loaded", fr, fd);
|
||||
dt->vkFreeMemory(dev, m->mem, NULL);
|
||||
m->mem = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
*out_fd = fd;
|
||||
break;
|
||||
}
|
||||
case VKB_MEM_DMAHEAP: {
|
||||
int hfd = dmaheap_fd();
|
||||
if (hfd < 0) break;
|
||||
uint64_t len = (ai->allocationSize + 4095) & ~4095ull;
|
||||
struct dma_heap_allocation_data hd = {len, 0, O_RDWR | O_CLOEXEC, 0};
|
||||
if (ioctl(hfd, DMA_HEAP_IOCTL_ALLOC, &hd) < 0) {
|
||||
VKB_INFO("dmaheap: allocating %llu bytes failed: %s", (unsigned long long)len, strerror(errno));
|
||||
r = VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
break;
|
||||
}
|
||||
int fd = (int)hd.fd;
|
||||
VkMemoryFdPropertiesKHR fp = {VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR};
|
||||
VkResult pr = dt->vkGetMemoryFdPropertiesKHR
|
||||
? dt->vkGetMemoryFdPropertiesKHR(dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, fd, &fp)
|
||||
: VK_ERROR_EXTENSION_NOT_PRESENT;
|
||||
if (pr != VK_SUCCESS || !(fp.memoryTypeBits & (1u << ai->memoryTypeIndex))) {
|
||||
VKB_INFO("dmaheap: fd properties %d, memory types 0x%x (want type %u)", pr, fp.memoryTypeBits, ai->memoryTypeIndex);
|
||||
close(fd);
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
/* The import takes its own fd; ours goes to the client. A dedicated-allocation struct
|
||||
* with an imported dma-buf crashes some Mali drivers (GameNative mesa PR #8): dropped. */
|
||||
int imp_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
|
||||
VkImportMemoryFdInfoKHR imp = {VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, info.pNext,
|
||||
VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, imp_fd};
|
||||
chain_drop(&imp.pNext, VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO);
|
||||
chain_drop(&imp.pNext, VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO);
|
||||
info.pNext = &imp;
|
||||
info.allocationSize = len;
|
||||
r = imp_fd >= 0 ? dt->vkAllocateMemory(dev, &info, NULL, &m->mem) : VK_ERROR_TOO_MANY_OBJECTS;
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO("dmaheap: import of %llu bytes failed: %d", (unsigned long long)len, r);
|
||||
if (imp_fd >= 0) close(imp_fd); /* a failed import leaves the fd with us */
|
||||
close(fd);
|
||||
break;
|
||||
}
|
||||
*out_fd = fd;
|
||||
break;
|
||||
}
|
||||
#ifdef __ANDROID__
|
||||
case VKB_MEM_AHB: {
|
||||
if (!ahb_load()) break;
|
||||
/* Through the device's own vkGetDeviceProcAddr: Android's loader answers NULL for it from
|
||||
* vkGetInstanceProcAddr(NULL, ...), which desktop loaders allow (the first device run). */
|
||||
PFN_vkGetAndroidHardwareBufferPropertiesANDROID get_props = NULL;
|
||||
if (vkb_mem_gdpa)
|
||||
get_props = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vkb_mem_gdpa(dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
|
||||
if (!get_props) {
|
||||
VKB_INFO("ahb: vkGetAndroidHardwareBufferPropertiesANDROID not found");
|
||||
break;
|
||||
}
|
||||
uint64_t sz = ai->allocationSize;
|
||||
if (sz > 0xFFFFFFFFull) {
|
||||
r = VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
break;
|
||||
}
|
||||
/* CPU usage decides how gralloc caches the pages; VKBRIDGE_AHB_RARELY=1 asks for uncached. */
|
||||
uint64_t cpu = getenv("VKBRIDGE_AHB_RARELY") ? (2ull | (2ull << 4)) : (AHB_USAGE_CPU_READ_OFTEN | AHB_USAGE_CPU_WRITE_OFTEN);
|
||||
vkb_ahb_desc d = {(uint32_t)sz, 1, 1, AHB_FORMAT_BLOB, cpu | AHB_USAGE_GPU_DATA_BUFFER, 0, 0, 0};
|
||||
struct AHardwareBuffer *ahb = NULL;
|
||||
int ar = p_AHardwareBuffer_allocate(&d, &ahb);
|
||||
if (ar != 0 || !ahb) {
|
||||
VKB_INFO("ahb: AHardwareBuffer_allocate(%u bytes) failed: %d", (unsigned)sz, ar);
|
||||
r = VK_ERROR_OUT_OF_DEVICE_MEMORY;
|
||||
break;
|
||||
}
|
||||
m->ahb = ahb;
|
||||
VkAndroidHardwareBufferPropertiesANDROID props = {VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID};
|
||||
VkResult pr = get_props(dev, ahb, &props);
|
||||
if (pr != VK_SUCCESS || !(props.memoryTypeBits & (1u << ai->memoryTypeIndex))) {
|
||||
VKB_INFO("ahb: properties %d, memory types 0x%x (want type %u)", pr, props.memoryTypeBits, ai->memoryTypeIndex);
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
VkImportAndroidHardwareBufferInfoANDROID imp = {VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, info.pNext, ahb};
|
||||
info.pNext = &imp;
|
||||
info.allocationSize = props.allocationSize;
|
||||
r = dt->vkAllocateMemory(dev, &info, NULL, &m->mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO("ahb: import of %llu bytes failed: %d", (unsigned long long)info.allocationSize, r);
|
||||
break;
|
||||
}
|
||||
const vkb_native_handle *nh = p_AHardwareBuffer_getNativeHandle(ahb);
|
||||
if (!nh || nh->numFds < 1) {
|
||||
VKB_INFO("ahb: no fd in the native handle (%d)", nh ? nh->numFds : -1);
|
||||
dt->vkFreeMemory(dev, m->mem, NULL);
|
||||
m->mem = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
/* Mali's gralloc can put more than one fd in the handle (metadata beside the pages): the
|
||||
* memory is the one at least as large as the allocation. */
|
||||
int pick = -1;
|
||||
for (int i = 0; i < nh->numFds && pick < 0; i++) {
|
||||
off_t end = lseek(nh->data[i], 0, SEEK_END);
|
||||
if (end >= (off_t)sz) pick = nh->data[i];
|
||||
if (nh->numFds > 1) VKB_INFO("ahb: handle fd %d of %d is %lld bytes", i + 1, nh->numFds, (long long)end);
|
||||
}
|
||||
if (pick < 0) {
|
||||
VKB_INFO("ahb: no fd in the handle covers %llu bytes", (unsigned long long)sz);
|
||||
dt->vkFreeMemory(dev, m->mem, NULL);
|
||||
m->mem = VK_NULL_HANDLE;
|
||||
r = VK_ERROR_INVALID_EXTERNAL_HANDLE;
|
||||
break;
|
||||
}
|
||||
*out_fd = fcntl(pick, F_DUPFD_CLOEXEC, 0);
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
if (r != VK_SUCCESS) {
|
||||
mem_release_backing(m);
|
||||
return r;
|
||||
}
|
||||
*out = m;
|
||||
return VK_SUCCESS;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ handlers */
|
||||
|
||||
static void close_import_fds(const void *pNext)
|
||||
{
|
||||
for (const VkBaseInStructure *b = pNext; b; b = b->pNext)
|
||||
if (b->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR) vkb_close_fd(((const VkImportMemoryFdInfoKHR *)b)->fd);
|
||||
}
|
||||
|
||||
void vkb_sv_vkAllocateMemory(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkMemoryAllocateInfo ai;
|
||||
int have = vkb_dec_u8(&c->d);
|
||||
if (have) vkb_dec_VkMemoryAllocateInfo(&c->d, &ai);
|
||||
uint32_t mode = vkb_dec_u32(&c->d);
|
||||
int client_fd = vkb_dec_fd(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (c->d.err || !have || !t || !t->is_device || t->device != dev) {
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkResult r;
|
||||
vkb_srv_mem *m = NULL;
|
||||
int out_fd = -1;
|
||||
if (mode == VKB_ALLOC_SHARED) {
|
||||
uint32_t s = t->pd ? t->pd->info.strategy : VKB_MEM_NONE;
|
||||
r = alloc_shared(c->dt, dev, s, &ai, client_fd, &m, &out_fd);
|
||||
if (r != VK_SUCCESS) VKB_WARN("shared allocation of %llu bytes (type %u, %s) failed: %d",
|
||||
(unsigned long long)ai.allocationSize, ai.memoryTypeIndex, vkb_mem_strategy_name(s), r);
|
||||
} else {
|
||||
if (client_fd >= 0) close(client_fd);
|
||||
m = calloc(1, sizeof(*m));
|
||||
m->size = ai.allocationSize;
|
||||
m->type = ai.memoryTypeIndex;
|
||||
r = c->dt->vkAllocateMemory(dev, &ai, NULL, &m->mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
close_import_fds(ai.pNext);
|
||||
free(m);
|
||||
m = NULL;
|
||||
}
|
||||
}
|
||||
if (m) vkb_mem_track(t, m);
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
vkb_enc_u64(&c->r, m ? (uint64_t)(uintptr_t)m->mem : 0);
|
||||
vkb_enc_fd(&c->r, out_fd);
|
||||
if (out_fd >= 0) vkb_srv_close_after_send(c, out_fd);
|
||||
vkb_enc_u64(&c->r, m ? (uint64_t)m->size : 0);
|
||||
}
|
||||
|
||||
void vkb_sv_vkFreeMemory(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDeviceMemory mem;
|
||||
vkb_dec_bytes(&c->d, &mem, sizeof(mem));
|
||||
vkb_srv_table *t = c->table;
|
||||
if (c->d.err || !t || !t->is_device || t->device != dev) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
if (!mem) return;
|
||||
vkb_srv_mem *m = vkb_mem_find(t, mem, 1);
|
||||
if (m) {
|
||||
vkb_mem_release(t, m);
|
||||
} else {
|
||||
VKB_WARN("vkFreeMemory of untracked memory");
|
||||
c->dt->vkFreeMemory(dev, mem, NULL);
|
||||
}
|
||||
}
|
||||
|
||||
static VkResult ensure_server_map(vkb_srv_table *t, vkb_srv_mem *m)
|
||||
{
|
||||
if (m->mapped) return VK_SUCCESS;
|
||||
pthread_mutex_lock(&t->lock);
|
||||
VkResult r = VK_SUCCESS;
|
||||
if (!m->mapped) r = t->real.vkMapMemory(t->device, m->mem, 0, VK_WHOLE_SIZE, 0, &m->mapped);
|
||||
pthread_mutex_unlock(&t->lock);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void flush_or_invalidate(vkb_srv_call *c, int flush)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
uint32_t n = vkb_dec_u32(&c->d);
|
||||
vkb_srv_table *t = c->table;
|
||||
if (c->d.err || !t || !t->is_device || t->device != dev || n > 65536) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkMappedMemoryRange *ranges = vkb_dec_alloc(&c->d, (n ? n : 1) * sizeof(*ranges));
|
||||
for (uint32_t i = 0; ranges && i < n; i++) vkb_dec_VkMappedMemoryRange(&c->d, &ranges[i]);
|
||||
if (c->d.err) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
VkResult r = VK_SUCCESS;
|
||||
for (uint32_t i = 0; i < n && r == VK_SUCCESS; i++) {
|
||||
vkb_srv_mem *m = vkb_mem_find(t, ranges[i].memory, 0);
|
||||
if (m) r = ensure_server_map(t, m);
|
||||
}
|
||||
if (r == VK_SUCCESS && n) {
|
||||
r = flush ? c->dt->vkFlushMappedMemoryRanges(dev, n, ranges) : c->dt->vkInvalidateMappedMemoryRanges(dev, n, ranges);
|
||||
}
|
||||
vkb_enc_u32(&c->r, (uint32_t)r);
|
||||
}
|
||||
|
||||
void vkb_sv_vkFlushMappedMemoryRanges(vkb_srv_call *c) { flush_or_invalidate(c, 1); }
|
||||
void vkb_sv_vkInvalidateMappedMemoryRanges(vkb_srv_call *c) { flush_or_invalidate(c, 0); }
|
||||
|
||||
/* ------------------------------------------------------------------ self-test */
|
||||
|
||||
typedef struct {
|
||||
const vkb_dispatch *idt;
|
||||
vkb_dispatch dt;
|
||||
VkPhysicalDevice pd;
|
||||
VkDevice dev;
|
||||
VkQueue queue;
|
||||
VkCommandPool pool;
|
||||
uint32_t qf;
|
||||
VkPhysicalDeviceMemoryProperties mp;
|
||||
VkDeviceSize import_align;
|
||||
} selftest;
|
||||
|
||||
static int submit_and_wait(selftest *st, VkCommandBuffer cb)
|
||||
{
|
||||
VkFenceCreateInfo fci = {VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};
|
||||
VkFence f;
|
||||
if (st->dt.vkCreateFence(st->dev, &fci, NULL, &f) != VK_SUCCESS) return 0;
|
||||
VkSubmitInfo si = {VK_STRUCTURE_TYPE_SUBMIT_INFO, NULL, 0, NULL, NULL, 1, &cb, 0, NULL};
|
||||
int ok = st->dt.vkQueueSubmit(st->queue, 1, &si, f) == VK_SUCCESS &&
|
||||
st->dt.vkWaitForFences(st->dev, 1, &f, VK_TRUE, 5000000000ull) == VK_SUCCESS;
|
||||
st->dt.vkDestroyFence(st->dev, f, NULL);
|
||||
return ok;
|
||||
}
|
||||
|
||||
#define TEST_SIZE (256u * 1024u)
|
||||
|
||||
/* One allocation of `type` with strategy `s`, checked from both sides. 1 = shared and coherent
|
||||
* (no flush needed), 2 = shared when flushed, 0 = not shared. */
|
||||
static int test_type_mode(selftest *st, uint32_t s, uint32_t type, int no_flush);
|
||||
|
||||
/* Without flushes first: imported pages from an uncached heap are coherent in practice even where
|
||||
* the driver's type does not say HOST_COHERENT (Mali-G720: dma-heap imports land in type 1,
|
||||
* HOST_CACHED without COHERENT, and pass with no flush). Only if that fails, with flushes. */
|
||||
static int test_type(selftest *st, uint32_t s, uint32_t type)
|
||||
{
|
||||
int coherent_flag = (st->mp.memoryTypes[type].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
|
||||
if (!coherent_flag && !getenv("VKBRIDGE_SELFTEST_NOFLUSH")) {
|
||||
int r = test_type_mode(st, s, type, 1);
|
||||
if (r) {
|
||||
VKB_INFO(" %s, type %u: coherent in practice (no flushes needed)", vkb_mem_strategy_name(s), type);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return test_type_mode(st, s, type, 0);
|
||||
}
|
||||
|
||||
static int test_type_mode(selftest *st, uint32_t s, uint32_t type, int no_flush)
|
||||
{
|
||||
const vkb_dispatch *dt = &st->dt;
|
||||
int result = 0;
|
||||
VkExternalMemoryBufferCreateInfo ext = {VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO, NULL, strategy_handle_type(s)};
|
||||
VkBufferCreateInfo bci = {VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &ext, 0, TEST_SIZE,
|
||||
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
|
||||
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |
|
||||
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
|
||||
VK_SHARING_MODE_EXCLUSIVE, 0, NULL};
|
||||
VkBuffer buf = VK_NULL_HANDLE;
|
||||
if (dt->vkCreateBuffer(st->dev, &bci, NULL, &buf) != VK_SUCCESS) return 0;
|
||||
VkMemoryRequirements req;
|
||||
dt->vkGetBufferMemoryRequirements(st->dev, buf, &req);
|
||||
if (!(req.memoryTypeBits & (1u << type))) {
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
VkDeviceSize size = req.size;
|
||||
if (s == VKB_MEM_HOSTPTR) size = (size + st->import_align - 1) & ~(st->import_align - 1);
|
||||
VkMemoryAllocateInfo ai = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, size, type};
|
||||
int cfd = -1;
|
||||
if (s == VKB_MEM_HOSTPTR) {
|
||||
cfd = vkb_memfd("vkbridge-selftest", (size_t)size);
|
||||
if (cfd < 0) {
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
int keep_fd = s == VKB_MEM_HOSTPTR ? fcntl(cfd, F_DUPFD_CLOEXEC, 0) : -1;
|
||||
vkb_srv_mem *m = NULL;
|
||||
int out_fd = -1;
|
||||
VkResult r = alloc_shared(dt, st->dev, s, &ai, cfd, &m, &out_fd);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_INFO(" %s, type %u: allocation failed (%d)", vkb_mem_strategy_name(s), type, r);
|
||||
if (keep_fd >= 0) close(keep_fd);
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
return 0;
|
||||
}
|
||||
int map_fd = s == VKB_MEM_HOSTPTR ? keep_fd : out_fd;
|
||||
uint8_t *cmap = mmap(NULL, (size_t)m->size, PROT_READ | PROT_WRITE, MAP_SHARED, map_fd, 0);
|
||||
if (map_fd >= 0) close(map_fd);
|
||||
void *smap = NULL;
|
||||
if (cmap == MAP_FAILED) {
|
||||
VKB_INFO(" %s, type %u: the client cannot map the memory (%s)", vkb_mem_strategy_name(s), type, strerror(errno));
|
||||
cmap = NULL;
|
||||
goto out;
|
||||
}
|
||||
if (dt->vkBindBufferMemory(st->dev, buf, m->mem, 0) != VK_SUCCESS ||
|
||||
dt->vkMapMemory(st->dev, m->mem, 0, VK_WHOLE_SIZE, 0, &smap) != VK_SUCCESS) {
|
||||
VKB_INFO(" %s, type %u: bind/map failed", vkb_mem_strategy_name(s), type);
|
||||
goto out;
|
||||
}
|
||||
int coherent = (st->mp.memoryTypes[type].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
|
||||
/* VKBRIDGE_SELFTEST_NOFLUSH=1 forces it for every type. */
|
||||
if (no_flush || getenv("VKBRIDGE_SELFTEST_NOFLUSH")) coherent = 1;
|
||||
VkMappedMemoryRange whole = {VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE, NULL, m->mem, 0, VK_WHOLE_SIZE};
|
||||
|
||||
/* 1: the two CPU mappings are the same pages. */
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 4; i += 997) ((volatile uint32_t *)cmap)[i] = 0x11220000u + i;
|
||||
__sync_synchronize();
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 4; i += 997) {
|
||||
if (((volatile uint32_t *)smap)[i] != 0x11220000u + i) {
|
||||
VKB_INFO(" %s, type %u: CPU mappings differ at word %u", vkb_mem_strategy_name(s), type, i);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
/* 2: GPU writes, client reads. 3: client writes, GPU copies, client reads the copy. */
|
||||
for (uint32_t i = TEST_SIZE / 8; i < TEST_SIZE / 8 + TEST_SIZE / 32; i++) ((volatile uint32_t *)cmap)[i] = 0x5a000000u ^ (i * 2654435761u);
|
||||
if (!coherent) dt->vkFlushMappedMemoryRanges(st->dev, 1, &whole);
|
||||
VkCommandBufferAllocateInfo cai = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, NULL, st->pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1};
|
||||
VkCommandBuffer cb;
|
||||
if (dt->vkAllocateCommandBuffers(st->dev, &cai, &cb) != VK_SUCCESS) goto out;
|
||||
VkCommandBufferBeginInfo bi = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, NULL};
|
||||
dt->vkBeginCommandBuffer(cb, &bi);
|
||||
dt->vkCmdFillBuffer(cb, buf, 0, TEST_SIZE / 8, 0xA5A5A5A5u);
|
||||
/* Layout (bytes): [0, N/8) GPU fill; [N/2, N/2 + N/8) written by the client and copied by
|
||||
* the GPU to [3N/4, 3N/4 + N/8). */
|
||||
VkBufferCopy region = {TEST_SIZE / 2, TEST_SIZE / 4 * 3, TEST_SIZE / 8};
|
||||
dt->vkCmdCopyBuffer(cb, buf, buf, 1, ®ion);
|
||||
VkMemoryBarrier mb = {VK_STRUCTURE_TYPE_MEMORY_BARRIER, NULL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT};
|
||||
dt->vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 1, &mb, 0, NULL, 0, NULL);
|
||||
dt->vkEndCommandBuffer(cb);
|
||||
int submitted = submit_and_wait(st, cb);
|
||||
dt->vkFreeCommandBuffers(st->dev, st->pool, 1, &cb);
|
||||
if (!submitted) {
|
||||
VKB_INFO(" %s, type %u: GPU submission failed", vkb_mem_strategy_name(s), type);
|
||||
goto out;
|
||||
}
|
||||
if (!coherent) dt->vkInvalidateMappedMemoryRanges(st->dev, 1, &whole);
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 32; i++) {
|
||||
if (((volatile uint32_t *)cmap)[i] != 0xA5A5A5A5u) {
|
||||
VKB_INFO(" %s, type %u: the client does not see a GPU write (word %u = 0x%08x)", vkb_mem_strategy_name(s), type, i,
|
||||
((volatile uint32_t *)cmap)[i]);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
for (uint32_t i = 0; i < TEST_SIZE / 32; i++) {
|
||||
uint32_t want = 0x5a000000u ^ ((TEST_SIZE / 8 + i) * 2654435761u);
|
||||
uint32_t got = ((volatile uint32_t *)cmap)[TEST_SIZE / 16 * 3 + i];
|
||||
if (got != want) {
|
||||
VKB_INFO(" %s, type %u: the GPU does not see a client write (word %u = 0x%08x, want 0x%08x)", vkb_mem_strategy_name(s),
|
||||
type, i, got, want);
|
||||
goto out;
|
||||
}
|
||||
}
|
||||
result = coherent ? 1 : 2;
|
||||
VKB_INFO(" %s, type %u (flags 0x%x): shared OK%s", vkb_mem_strategy_name(s), type, st->mp.memoryTypes[type].propertyFlags,
|
||||
coherent ? ", coherent" : ", needs flushes");
|
||||
out:
|
||||
if (cmap) munmap(cmap, (size_t)m->size);
|
||||
if (smap) dt->vkUnmapMemory(st->dev, m->mem);
|
||||
dt->vkDestroyBuffer(st->dev, buf, NULL);
|
||||
dt->vkFreeMemory(st->dev, m->mem, NULL);
|
||||
mem_release_backing(m);
|
||||
return result;
|
||||
}
|
||||
|
||||
static int has_ext(const VkExtensionProperties *e, uint32_t n, const char *name)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
if (!strcmp(e[i].extensionName, name)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* What the driver says it can do with each kind of external buffer memory (the device runs). */
|
||||
static void log_external_props(const vkb_dispatch *idt, VkPhysicalDevice pd)
|
||||
{
|
||||
if (!idt->vkGetPhysicalDeviceExternalBufferProperties) return;
|
||||
static const struct { uint32_t bit; const char *name; } types[] = {
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT, "opaque fd"},
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, "dma-buf"},
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, "host allocation"},
|
||||
#ifdef __ANDROID__
|
||||
{VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID, "AHB"},
|
||||
#endif
|
||||
};
|
||||
for (size_t i = 0; i < sizeof(types) / sizeof(types[0]); i++) {
|
||||
VkPhysicalDeviceExternalBufferInfo bi = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO, NULL, 0,
|
||||
VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
|
||||
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT,
|
||||
(VkExternalMemoryHandleTypeFlagBits)types[i].bit};
|
||||
VkExternalBufferProperties ep = {VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES};
|
||||
idt->vkGetPhysicalDeviceExternalBufferProperties(pd, &bi, &ep);
|
||||
const VkExternalMemoryProperties *p = &ep.externalMemoryProperties;
|
||||
VKB_INFO("external buffers, %s: features 0x%x (%s%s%s), export from 0x%x, compatible 0x%x", types[i].name,
|
||||
p->externalMemoryFeatures,
|
||||
p->externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT ? "dedicated-only " : "",
|
||||
p->externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT ? "exportable " : "",
|
||||
p->externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT ? "importable" : "",
|
||||
p->exportFromImportedHandleTypes, p->compatibleHandleTypes);
|
||||
}
|
||||
}
|
||||
|
||||
void vkb_mem_selftest(vkb_pd_knowledge *k, VkInstance inst, const vkb_dispatch *idt, VkPhysicalDevice pd)
|
||||
{
|
||||
selftest st;
|
||||
memset(&st, 0, sizeof(st));
|
||||
st.idt = idt;
|
||||
st.pd = pd;
|
||||
idt->vkGetPhysicalDeviceMemoryProperties(pd, &st.mp);
|
||||
|
||||
uint32_t nq = 0;
|
||||
idt->vkGetPhysicalDeviceQueueFamilyProperties(pd, &nq, NULL);
|
||||
VkQueueFamilyProperties qp[16];
|
||||
if (nq > 16) nq = 16;
|
||||
idt->vkGetPhysicalDeviceQueueFamilyProperties(pd, &nq, qp);
|
||||
st.qf = 0;
|
||||
for (uint32_t i = 0; i < nq; i++)
|
||||
if (qp[i].queueFlags & (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)) {
|
||||
st.qf = i;
|
||||
break;
|
||||
}
|
||||
|
||||
uint32_t ne = 0;
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *ex = calloc(ne ? ne : 1, sizeof(*ex));
|
||||
idt->vkEnumerateDeviceExtensionProperties(pd, NULL, &ne, ex);
|
||||
|
||||
uint32_t candidates[4];
|
||||
int nc = 0;
|
||||
const char *force = getenv("VKBRIDGE_MEMORY");
|
||||
/* GameNative's order on Mali: the driver's own export, a dma-heap import, then an AHB. */
|
||||
uint32_t order[] = {VKB_MEM_HOSTPTR, VKB_MEM_DMABUF, VKB_MEM_DMAHEAP, VKB_MEM_AHB};
|
||||
for (int i = 0; i < 4; i++) {
|
||||
uint32_t s = order[i];
|
||||
if (force && strcmp(force, vkb_mem_strategy_name(s))) continue;
|
||||
uint32_t n;
|
||||
const char *const *req = vkb_mem_required_extensions(s, &n);
|
||||
if (!req) continue;
|
||||
int ok = 1;
|
||||
for (uint32_t j = 0; j < n; j++)
|
||||
if (strcmp(req[j], "VK_KHR_external_memory") && strcmp(req[j], "VK_KHR_sampler_ycbcr_conversion") &&
|
||||
strcmp(req[j], "VK_KHR_dedicated_allocation") && strcmp(req[j], "VK_KHR_get_memory_requirements2") &&
|
||||
!has_ext(ex, ne, req[j]))
|
||||
ok = 0;
|
||||
if (ok) candidates[nc++] = s;
|
||||
else VKB_INFO("memory sharing: %s unavailable (driver lacks its extensions)", vkb_mem_strategy_name(s));
|
||||
}
|
||||
|
||||
/* One test device with every candidate's extensions. */
|
||||
const char *exts[16];
|
||||
uint32_t nx = 0;
|
||||
for (int i = 0; i < nc; i++) {
|
||||
uint32_t n;
|
||||
const char *const *req = vkb_mem_required_extensions(candidates[i], &n);
|
||||
for (uint32_t j = 0; j < n; j++) {
|
||||
if (!has_ext(ex, ne, req[j])) continue;
|
||||
int dup = 0;
|
||||
for (uint32_t q = 0; q < nx; q++) dup |= !strcmp(exts[q], req[j]);
|
||||
if (!dup && nx < 16) exts[nx++] = req[j];
|
||||
}
|
||||
}
|
||||
free(ex);
|
||||
float prio = 1.0f;
|
||||
VkDeviceQueueCreateInfo qci = {VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, NULL, 0, st.qf, 1, &prio};
|
||||
VkDeviceCreateInfo dci = {VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, NULL, 0, 1, &qci, 0, NULL, nx, exts, NULL};
|
||||
if (idt->vkCreateDevice(pd, &dci, NULL, &st.dev) != VK_SUCCESS) {
|
||||
VKB_ERR("memory self-test: cannot create a device");
|
||||
return;
|
||||
}
|
||||
st.dt = *idt;
|
||||
PFN_vkGetDeviceProcAddr gdpa = (PFN_vkGetDeviceProcAddr)vkb_gipa(inst, "vkGetDeviceProcAddr");
|
||||
vkb_mem_gdpa = gdpa;
|
||||
log_external_props(idt, pd);
|
||||
vkb_dispatch_load_device(&st.dt, gdpa, st.dev);
|
||||
st.dt.vkGetDeviceQueue(st.dev, st.qf, 0, &st.queue);
|
||||
VkCommandPoolCreateInfo pci = {VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, NULL, 0, st.qf};
|
||||
st.dt.vkCreateCommandPool(st.dev, &pci, NULL, &st.pool);
|
||||
|
||||
VkPhysicalDeviceExternalMemoryHostPropertiesEXT hostp = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT};
|
||||
VkPhysicalDeviceProperties2 p2 = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &hostp};
|
||||
idt->vkGetPhysicalDeviceProperties2(pd, &p2);
|
||||
st.import_align = hostp.minImportedHostPointerAlignment ? hostp.minImportedHostPointerAlignment : 4096;
|
||||
if (st.import_align < 4096) st.import_align = 4096;
|
||||
|
||||
k->info.strategy = VKB_MEM_NONE;
|
||||
for (int i = 0; i < nc; i++) {
|
||||
uint32_t s = candidates[i];
|
||||
uint32_t shareable = 0, coherent = 0;
|
||||
for (uint32_t t = 0; t < st.mp.memoryTypeCount; t++) {
|
||||
if (!(st.mp.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT)) continue;
|
||||
if (st.mp.memoryTypes[t].propertyFlags & VK_MEMORY_PROPERTY_PROTECTED_BIT) continue;
|
||||
int res = test_type(&st, s, t);
|
||||
if (res) shareable |= 1u << t;
|
||||
if (res == 1) coherent |= 1u << t;
|
||||
}
|
||||
if (coherent) {
|
||||
k->info.strategy = s;
|
||||
k->info.buffer_handle_types = strategy_handle_type(s);
|
||||
k->info.shareable_types = shareable;
|
||||
k->info.coherent_types = coherent;
|
||||
k->info.import_alignment = st.import_align;
|
||||
break;
|
||||
}
|
||||
VKB_INFO("memory sharing: %s failed the self-test", vkb_mem_strategy_name(s));
|
||||
}
|
||||
if (k->info.strategy == VKB_MEM_NONE)
|
||||
VKB_ERR("memory sharing: no method works on %s; Linux programs will get no host-visible memory", k->name);
|
||||
|
||||
st.dt.vkDestroyCommandPool(st.dev, st.pool, NULL);
|
||||
st.dt.vkDestroyDevice(st.dev, NULL);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Descriptor update templates. The client repacks the app's data to the layout of the template
|
||||
* it created on the server (entries rewritten to packed offsets), so the blob is used as is.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
void vkb_sv_vkbDescUpdateRaw(vkb_srv_call *c)
|
||||
{
|
||||
VkDevice dev = (VkDevice)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDescriptorSet set;
|
||||
VkDescriptorUpdateTemplate tmpl;
|
||||
vkb_dec_bytes(&c->d, &set, sizeof(set));
|
||||
vkb_dec_bytes(&c->d, &tmpl, sizeof(tmpl));
|
||||
size_t n = 0;
|
||||
const void *data = vkb_dec_blob(&c->d, &n);
|
||||
if (c->d.err || !c->table) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
if (!c->dt->vkUpdateDescriptorSetWithTemplate) {
|
||||
vkb_srv_missing(c, "vkUpdateDescriptorSetWithTemplate");
|
||||
return;
|
||||
}
|
||||
c->dt->vkUpdateDescriptorSetWithTemplate(dev, set, tmpl, data);
|
||||
}
|
||||
|
||||
void vkb_sv_vkbPushDescRaw(vkb_srv_call *c)
|
||||
{
|
||||
VkCommandBuffer cb = (VkCommandBuffer)(uintptr_t)vkb_dec_u64(&c->d);
|
||||
VkDescriptorUpdateTemplate tmpl;
|
||||
VkPipelineLayout layout;
|
||||
vkb_dec_bytes(&c->d, &tmpl, sizeof(tmpl));
|
||||
vkb_dec_bytes(&c->d, &layout, sizeof(layout));
|
||||
uint32_t set = vkb_dec_u32(&c->d);
|
||||
size_t n = 0;
|
||||
const void *data = vkb_dec_blob(&c->d, &n);
|
||||
if (c->d.err || !c->table) {
|
||||
vkb_srv_bad_message(c);
|
||||
return;
|
||||
}
|
||||
if (!c->dt->vkCmdPushDescriptorSetWithTemplate) {
|
||||
vkb_srv_missing(c, "vkCmdPushDescriptorSetWithTemplate");
|
||||
return;
|
||||
}
|
||||
extern __thread size_t vkb_emu_push_size;
|
||||
vkb_emu_push_size = n;
|
||||
c->dt->vkCmdPushDescriptorSetWithTemplate(cb, tmpl, layout, set, data);
|
||||
vkb_emu_push_size = 0;
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* Persistent pipeline cache. Mali compiles every pipeline from scratch in each new process unless
|
||||
* it is handed a VkPipelineCache; games through DXVK pass none. With a cache directory set
|
||||
* (--cache-dir), each device gets a cache loaded from <dir>/<vendor>-<device>-<cacheUUID>.vkpc:
|
||||
* - pipelines created without a cache use it;
|
||||
* - caches the app creates empty start from it, and are merged back into it when destroyed;
|
||||
* - it is written back every few seconds while new pipelines come in (the app stops the server
|
||||
* with SIGKILL, so there is no reliable last chance) and when the device goes away.
|
||||
* The file's header is checked against the GPU before the driver sees it.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define PC_MAX_FILE (256u << 20)
|
||||
#define PC_SAVE_PERIOD_S 10
|
||||
|
||||
typedef struct vkb_pcache {
|
||||
vkb_srv_table *t;
|
||||
VkPipelineCache cache;
|
||||
char path[512];
|
||||
int dirty;
|
||||
size_t saved_size;
|
||||
PFN_vkCreateGraphicsPipelines create_gfx;
|
||||
PFN_vkCreateComputePipelines create_compute;
|
||||
PFN_vkCreatePipelineCache create_cache;
|
||||
PFN_vkDestroyPipelineCache destroy_cache;
|
||||
struct vkb_pcache *next;
|
||||
} vkb_pcache;
|
||||
|
||||
static const char *pc_dir;
|
||||
static pthread_mutex_t pc_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static vkb_pcache *pc_list;
|
||||
static int pc_thread_started;
|
||||
|
||||
void vkb_pcache_set_dir(const char *dir)
|
||||
{
|
||||
if (!dir || !*dir) return;
|
||||
mkdir(dir, 0700);
|
||||
/* A copy: the JNI entry frees its string once the server is up, and the pointer kept before
|
||||
* printed "pipeline cache \xef\xbf\xbdRYp/13b5-..." and wrote the cache under that name. */
|
||||
char *copy = strdup(dir);
|
||||
if (!copy) return;
|
||||
pc_dir = copy;
|
||||
VKB_INFO("pipeline cache directory %s", dir);
|
||||
}
|
||||
|
||||
static vkb_pcache *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->pcache : NULL;
|
||||
}
|
||||
|
||||
/* The header every pipeline cache starts with (VkPipelineCacheHeaderVersionOne). */
|
||||
static int header_ok(const vkb_srv_table *t, const uint8_t *data, size_t size)
|
||||
{
|
||||
VkPipelineCacheHeaderVersionOne h;
|
||||
if (size < sizeof(h)) return 0;
|
||||
memcpy(&h, data, sizeof(h));
|
||||
VkPhysicalDeviceProperties props;
|
||||
t->real.vkGetPhysicalDeviceProperties(t->physical, &props);
|
||||
return h.headerSize >= sizeof(h) && h.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE &&
|
||||
h.vendorID == props.vendorID && h.deviceID == props.deviceID &&
|
||||
!memcmp(h.pipelineCacheUUID, props.pipelineCacheUUID, VK_UUID_SIZE);
|
||||
}
|
||||
|
||||
static uint8_t *read_file(const char *path, size_t *size)
|
||||
{
|
||||
*size = 0;
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return NULL;
|
||||
struct stat st;
|
||||
uint8_t *buf = NULL;
|
||||
if (fstat(fd, &st) == 0 && st.st_size > 0 && (uint64_t)st.st_size <= PC_MAX_FILE && (buf = malloc((size_t)st.st_size))) {
|
||||
size_t got = 0;
|
||||
while (got < (size_t)st.st_size) {
|
||||
ssize_t r = read(fd, buf + got, (size_t)st.st_size - got);
|
||||
if (r <= 0) break;
|
||||
got += (size_t)r;
|
||||
}
|
||||
if (got == (size_t)st.st_size) {
|
||||
*size = got;
|
||||
} else {
|
||||
free(buf);
|
||||
buf = NULL;
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
return buf;
|
||||
}
|
||||
|
||||
/* Writes the cache next to its file and renames it over, so a kill mid-write loses nothing. */
|
||||
static void save(vkb_pcache *p)
|
||||
{
|
||||
vkb_srv_table *t = p->t;
|
||||
size_t size = 0;
|
||||
if (t->real.vkGetPipelineCacheData(t->device, p->cache, &size, NULL) != VK_SUCCESS || !size || size > PC_MAX_FILE) return;
|
||||
if (size == p->saved_size) {
|
||||
/* Nothing new was compiled (merges of what it already had leave the size alone). */
|
||||
p->dirty = 0;
|
||||
return;
|
||||
}
|
||||
uint8_t *buf = malloc(size);
|
||||
if (!buf) return;
|
||||
VkResult r = t->real.vkGetPipelineCacheData(t->device, p->cache, &size, buf);
|
||||
if (r == VK_SUCCESS) {
|
||||
char tmp[600];
|
||||
snprintf(tmp, sizeof(tmp), "%s.%d.tmp", p->path, (int)getpid());
|
||||
int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
||||
int ok = fd >= 0;
|
||||
for (size_t done = 0; ok && done < size;) {
|
||||
ssize_t w = write(fd, buf + done, size - done);
|
||||
if (w < 0 && errno == EINTR) continue;
|
||||
if (w <= 0) ok = 0;
|
||||
else done += (size_t)w;
|
||||
}
|
||||
if (fd >= 0 && fsync(fd) != 0) ok = 0;
|
||||
if (fd >= 0) close(fd);
|
||||
if (ok && rename(tmp, p->path) == 0) {
|
||||
VKB_INFO("device %u: pipeline cache saved (%zu KB)", t->id, size >> 10);
|
||||
p->saved_size = size;
|
||||
p->dirty = 0;
|
||||
} else {
|
||||
VKB_WARN("device %u: pipeline cache not saved to %s: %s", t->id, p->path, strerror(errno));
|
||||
unlink(tmp);
|
||||
}
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
static void *saver(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
struct timespec ts = {PC_SAVE_PERIOD_S, 0};
|
||||
nanosleep(&ts, NULL);
|
||||
pthread_mutex_lock(&pc_lock);
|
||||
for (vkb_pcache *p = pc_list; p; p = p->next)
|
||||
if (__atomic_load_n(&p->dirty, __ATOMIC_RELAXED)) save(p);
|
||||
pthread_mutex_unlock(&pc_lock);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ wrappers */
|
||||
|
||||
static VkResult VKAPI_CALL pc_CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkGraphicsPipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (!cache) {
|
||||
cache = p->cache;
|
||||
__atomic_store_n(&p->dirty, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return p->create_gfx(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL pc_CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkComputePipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (!cache) {
|
||||
cache = p->cache;
|
||||
__atomic_store_n(&p->dirty, 1, __ATOMIC_RELAXED);
|
||||
}
|
||||
return p->create_compute(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL pc_CreatePipelineCache(VkDevice device, const VkPipelineCacheCreateInfo *ci,
|
||||
const VkAllocationCallbacks *a, VkPipelineCache *out)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (ci->initialDataSize) return p->create_cache(device, ci, a, out);
|
||||
size_t size = 0;
|
||||
uint8_t *buf = NULL;
|
||||
if (p->t->real.vkGetPipelineCacheData(device, p->cache, &size, NULL) == VK_SUCCESS && size && (buf = malloc(size)) &&
|
||||
p->t->real.vkGetPipelineCacheData(device, p->cache, &size, buf) != VK_SUCCESS)
|
||||
size = 0;
|
||||
VkPipelineCacheCreateInfo seeded = *ci;
|
||||
seeded.initialDataSize = buf ? size : 0;
|
||||
seeded.pInitialData = buf;
|
||||
VkResult r = p->create_cache(device, &seeded, a, out);
|
||||
free(buf);
|
||||
return r;
|
||||
}
|
||||
|
||||
static void VKAPI_CALL pc_DestroyPipelineCache(VkDevice device, VkPipelineCache cache, const VkAllocationCallbacks *a)
|
||||
{
|
||||
vkb_pcache *p = cur();
|
||||
if (cache && cache != p->cache && p->t->real.vkMergePipelineCaches(device, p->cache, 1, &cache) == VK_SUCCESS)
|
||||
__atomic_store_n(&p->dirty, 1, __ATOMIC_RELAXED);
|
||||
p->destroy_cache(device, cache, a);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ device hooks */
|
||||
|
||||
void vkb_pcache_device_init(vkb_srv_table *t)
|
||||
{
|
||||
if (!pc_dir || !t->real.vkCreatePipelineCache || !t->real.vkGetPipelineCacheData || !t->real.vkMergePipelineCaches) return;
|
||||
vkb_pcache *p = calloc(1, sizeof(*p));
|
||||
if (!p) return;
|
||||
p->t = t;
|
||||
VkPhysicalDeviceProperties props;
|
||||
t->real.vkGetPhysicalDeviceProperties(t->physical, &props);
|
||||
char uuid[2 * VK_UUID_SIZE + 1];
|
||||
for (int i = 0; i < VK_UUID_SIZE; i++) snprintf(uuid + 2 * i, 3, "%02x", props.pipelineCacheUUID[i]);
|
||||
snprintf(p->path, sizeof(p->path), "%s/%04x-%04x-%s.vkpc", pc_dir, props.vendorID, props.deviceID, uuid);
|
||||
|
||||
size_t size;
|
||||
uint8_t *data = read_file(p->path, &size);
|
||||
if (data && !header_ok(t, data, size)) {
|
||||
VKB_WARN("device %u: %s is not this GPU's pipeline cache; starting empty", t->id, p->path);
|
||||
free(data);
|
||||
data = NULL;
|
||||
size = 0;
|
||||
}
|
||||
VkPipelineCacheCreateInfo ci = {VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, NULL, 0, data ? size : 0, data};
|
||||
VkResult r = t->real.vkCreatePipelineCache(t->device, &ci, NULL, &p->cache);
|
||||
if (r != VK_SUCCESS && data) {
|
||||
VKB_WARN("device %u: driver refused the saved pipeline cache (%d); starting empty", t->id, r);
|
||||
ci.initialDataSize = 0;
|
||||
ci.pInitialData = NULL;
|
||||
r = t->real.vkCreatePipelineCache(t->device, &ci, NULL, &p->cache);
|
||||
}
|
||||
free(data);
|
||||
if (r != VK_SUCCESS) {
|
||||
VKB_WARN("device %u: no pipeline cache (%d)", t->id, r);
|
||||
free(p);
|
||||
return;
|
||||
}
|
||||
p->saved_size = size;
|
||||
VKB_INFO("device %u: pipeline cache %s (%zu KB loaded)", t->id, p->path, size >> 10);
|
||||
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
p->create_gfx = dt->vkCreateGraphicsPipelines;
|
||||
p->create_compute = dt->vkCreateComputePipelines;
|
||||
p->create_cache = dt->vkCreatePipelineCache;
|
||||
p->destroy_cache = dt->vkDestroyPipelineCache;
|
||||
dt->vkCreateGraphicsPipelines = pc_CreateGraphicsPipelines;
|
||||
dt->vkCreateComputePipelines = pc_CreateComputePipelines;
|
||||
dt->vkCreatePipelineCache = pc_CreatePipelineCache;
|
||||
dt->vkDestroyPipelineCache = pc_DestroyPipelineCache;
|
||||
t->pcache = p;
|
||||
|
||||
pthread_mutex_lock(&pc_lock);
|
||||
p->next = pc_list;
|
||||
pc_list = p;
|
||||
if (!pc_thread_started) {
|
||||
pthread_t th;
|
||||
pthread_attr_t at;
|
||||
pthread_attr_init(&at);
|
||||
pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
|
||||
pc_thread_started = pthread_create(&th, &at, saver, NULL) == 0;
|
||||
pthread_attr_destroy(&at);
|
||||
}
|
||||
pthread_mutex_unlock(&pc_lock);
|
||||
}
|
||||
|
||||
/* Before the device is destroyed: last save, then the cache goes. */
|
||||
void vkb_pcache_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_pcache *p = t->pcache;
|
||||
if (!p) return;
|
||||
pthread_mutex_lock(&pc_lock);
|
||||
for (vkb_pcache **pp = &pc_list; *pp; pp = &(*pp)->next) {
|
||||
if (*pp == p) {
|
||||
*pp = p->next;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (p->dirty) save(p);
|
||||
pthread_mutex_unlock(&pc_lock);
|
||||
t->dt.vkCreateGraphicsPipelines = p->create_gfx;
|
||||
t->dt.vkCreateComputePipelines = p->create_compute;
|
||||
t->dt.vkCreatePipelineCache = p->create_cache;
|
||||
t->dt.vkDestroyPipelineCache = p->destroy_cache;
|
||||
t->real.vkDestroyPipelineCache(t->device, p->cache, NULL);
|
||||
t->pcache = NULL;
|
||||
free(p);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* SPIR-V fixes for Mali's shader compiler, applied to every module the app hands the driver.
|
||||
*
|
||||
* DXVK (1.7.3 and later) guards texture reads with OpSelect(cond, texel, vec4(0)) where cond is an
|
||||
* OpConstantComposite of OpSpecConstantTrue/False. Mali's compiler folds that composite as if it
|
||||
* were a plain constant - taking the spec constants at their default - and every texture reads
|
||||
* black. Declaring the composite OpSpecConstantComposite (same operands, same length) keeps it
|
||||
* specializable and the fold away. Found by leegao (bionic-vulkan-wrapper issue #93,
|
||||
* "OpCompositeConstant" write-up, 2025-08-10); Vortek patches the same pattern.
|
||||
*
|
||||
* The code is patched in place: it lives in the server's receive buffer (vkCreateShaderModule's
|
||||
* pCode, or a VkShaderModuleCreateInfo chained to a pipeline stage), so nothing is copied.
|
||||
* On for ARM GPUs; VKBRIDGE_SPIRV_FIX=1/0 forces it (host tests).
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "vkb_server.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define OP_SPEC_CONSTANT_TRUE 48
|
||||
#define OP_SPEC_CONSTANT_FALSE 49
|
||||
#define OP_SPEC_CONSTANT 50
|
||||
#define OP_SPEC_CONSTANT_COMPOSITE 51
|
||||
#define OP_SPEC_CONSTANT_OP 52
|
||||
#define OP_CONSTANT_COMPOSITE 44
|
||||
#define OP_FUNCTION 54
|
||||
|
||||
typedef struct vkb_spvfix {
|
||||
PFN_vkCreateShaderModule create_module;
|
||||
PFN_vkCreateGraphicsPipelines create_gfx;
|
||||
PFN_vkCreateComputePipelines create_compute;
|
||||
unsigned long patched; /* composites changed, for the log */
|
||||
} vkb_spvfix;
|
||||
|
||||
static vkb_spvfix *cur(void)
|
||||
{
|
||||
vkb_srv_table *t = vkb_srv_current_table();
|
||||
return t ? t->spvfix : NULL;
|
||||
}
|
||||
|
||||
/* Patches one module in place; returns the number of composites changed. */
|
||||
static unsigned fix_module(uint32_t *w, size_t bytes)
|
||||
{
|
||||
size_t n = bytes / 4;
|
||||
if (n < 5 || w[0] != 0x07230203u) return 0;
|
||||
uint32_t bound = w[3];
|
||||
if (!bound || bound > (1u << 24)) return 0;
|
||||
uint8_t *spec = calloc(bound, 1);
|
||||
if (!spec) return 0;
|
||||
unsigned changed = 0;
|
||||
for (size_t i = 5; i < n;) {
|
||||
uint32_t op = w[i] & 0xffff, len = w[i] >> 16;
|
||||
if (!len || i + len > n) break;
|
||||
if (op == OP_FUNCTION) break; /* constants all come before the first function */
|
||||
if ((op == OP_SPEC_CONSTANT_TRUE || op == OP_SPEC_CONSTANT_FALSE || op == OP_SPEC_CONSTANT ||
|
||||
op == OP_SPEC_CONSTANT_COMPOSITE || op == OP_SPEC_CONSTANT_OP) && len >= 3 && w[i + 2] < bound) {
|
||||
spec[w[i + 2]] = 1;
|
||||
} else if (op == OP_CONSTANT_COMPOSITE && len >= 3 && w[i + 2] < bound) {
|
||||
int any = 0;
|
||||
for (uint32_t k = 3; k < len; k++) any |= w[i + k] < bound && spec[w[i + k]];
|
||||
if (any) {
|
||||
/* A composite of spec constants is itself one: declared so, it is no longer folded. */
|
||||
w[i] = (len << 16) | OP_SPEC_CONSTANT_COMPOSITE;
|
||||
spec[w[i + 2]] = 1;
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
free(spec);
|
||||
return changed;
|
||||
}
|
||||
|
||||
static void note(vkb_spvfix *f, unsigned changed)
|
||||
{
|
||||
if (!changed) return;
|
||||
unsigned long before = __atomic_fetch_add(&f->patched, changed, __ATOMIC_RELAXED);
|
||||
if (!before) VKB_INFO("SPIR-V fix: spec-constant composites redeclared for Mali's compiler (first in this device)");
|
||||
}
|
||||
|
||||
static void fix_stages(vkb_spvfix *f, uint32_t n, const VkPipelineShaderStageCreateInfo *st)
|
||||
{
|
||||
for (uint32_t i = 0; i < n; i++)
|
||||
for (const VkBaseInStructure *b = st[i].pNext; b; b = b->pNext)
|
||||
if (b->sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) {
|
||||
const VkShaderModuleCreateInfo *mi = (const void *)b;
|
||||
note(f, fix_module((uint32_t *)mi->pCode, mi->codeSize));
|
||||
}
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL fx_CreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkShaderModule *out)
|
||||
{
|
||||
vkb_spvfix *f = cur();
|
||||
note(f, fix_module((uint32_t *)ci->pCode, ci->codeSize));
|
||||
return f->create_module(device, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL fx_CreateGraphicsPipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkGraphicsPipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_spvfix *f = cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_stages(f, ci[i].stageCount, ci[i].pStages);
|
||||
return f->create_gfx(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
static VkResult VKAPI_CALL fx_CreateComputePipelines(VkDevice device, VkPipelineCache cache, uint32_t n,
|
||||
const VkComputePipelineCreateInfo *ci, const VkAllocationCallbacks *a,
|
||||
VkPipeline *out)
|
||||
{
|
||||
vkb_spvfix *f = cur();
|
||||
for (uint32_t i = 0; i < n; i++) fix_stages(f, 1, &ci[i].stage);
|
||||
return f->create_compute(device, cache, n, ci, a, out);
|
||||
}
|
||||
|
||||
void vkb_spvfix_device_init(vkb_srv_table *t)
|
||||
{
|
||||
VkPhysicalDeviceProperties p;
|
||||
t->real.vkGetPhysicalDeviceProperties(t->physical, &p);
|
||||
const char *env = getenv("VKBRIDGE_SPIRV_FIX");
|
||||
int on = env ? strcmp(env, "0") != 0 : p.vendorID == 0x13B5; /* ARM */
|
||||
if (!on || !t->dt.vkCreateShaderModule) return;
|
||||
vkb_spvfix *f = calloc(1, sizeof(*f));
|
||||
if (!f) return;
|
||||
vkb_dispatch *dt = &t->dt;
|
||||
f->create_module = dt->vkCreateShaderModule;
|
||||
f->create_gfx = dt->vkCreateGraphicsPipelines;
|
||||
f->create_compute = dt->vkCreateComputePipelines;
|
||||
dt->vkCreateShaderModule = fx_CreateShaderModule;
|
||||
dt->vkCreateGraphicsPipelines = fx_CreateGraphicsPipelines;
|
||||
dt->vkCreateComputePipelines = fx_CreateComputePipelines;
|
||||
t->spvfix = f;
|
||||
VKB_INFO("device %u: Mali SPIR-V fixes on", t->id);
|
||||
}
|
||||
|
||||
void vkb_spvfix_device_destroy(vkb_srv_table *t)
|
||||
{
|
||||
vkb_spvfix *f = t->spvfix;
|
||||
if (!f) return;
|
||||
t->dt.vkCreateShaderModule = f->create_module;
|
||||
t->dt.vkCreateGraphicsPipelines = f->create_gfx;
|
||||
t->dt.vkCreateComputePipelines = f->create_compute;
|
||||
if (f->patched) VKB_INFO("device %u: SPIR-V fix changed %lu composites", t->id, f->patched);
|
||||
free(f);
|
||||
t->spvfix = NULL;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
#include "spirv_edit.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
int spv_parse(spv_mod *m, const uint32_t *code, size_t bytes)
|
||||
{
|
||||
memset(m, 0, sizeof(*m));
|
||||
if (bytes < 20 || (bytes & 3) || code[0] != 0x07230203u) return -1;
|
||||
memcpy(m->header, code, 20);
|
||||
size_t words = bytes / 4, pos = 5;
|
||||
while (pos < words) {
|
||||
uint32_t n = code[pos] >> 16, op = code[pos] & 0xffff;
|
||||
if (n == 0 || pos + n > words) return -1;
|
||||
spv_insert(m, m->count, (uint16_t)op, code + pos + 1, (uint16_t)(n - 1));
|
||||
if (m->err) return -1;
|
||||
pos += n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
size_t spv_write(const spv_mod *m, uint32_t **out)
|
||||
{
|
||||
size_t words = 5;
|
||||
for (uint32_t i = 0; i < m->count; i++) words += m->ins[i].n;
|
||||
uint32_t *buf = malloc(words * 4);
|
||||
if (!buf) return 0;
|
||||
memcpy(buf, m->header, 20);
|
||||
size_t pos = 5;
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
buf[pos++] = ((uint32_t)in->n << 16) | in->op;
|
||||
memcpy(buf + pos, in->w, (size_t)(in->n - 1) * 4);
|
||||
pos += in->n - 1;
|
||||
}
|
||||
*out = buf;
|
||||
return words * 4;
|
||||
}
|
||||
|
||||
void spv_free(spv_mod *m)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) free(m->ins[i].w);
|
||||
free(m->ins);
|
||||
memset(m, 0, sizeof(*m));
|
||||
}
|
||||
|
||||
uint32_t spv_insert(spv_mod *m, uint32_t at, uint16_t op, const uint32_t *ops, uint16_t nops)
|
||||
{
|
||||
if (m->count == m->cap) {
|
||||
uint32_t nc = m->cap ? m->cap * 2 : 1024;
|
||||
spv_inst *ni = realloc(m->ins, nc * sizeof(*ni));
|
||||
if (!ni) {
|
||||
m->err = 1;
|
||||
return 0;
|
||||
}
|
||||
m->ins = ni;
|
||||
m->cap = nc;
|
||||
}
|
||||
if (at > m->count) at = m->count;
|
||||
memmove(&m->ins[at + 1], &m->ins[at], (m->count - at) * sizeof(spv_inst));
|
||||
spv_inst *in = &m->ins[at];
|
||||
in->op = op;
|
||||
in->n = (uint16_t)(nops + 1);
|
||||
in->w = malloc((size_t)(nops ? nops : 1) * 4);
|
||||
if (!in->w) m->err = 1;
|
||||
else if (nops) memcpy(in->w, ops, (size_t)nops * 4);
|
||||
m->count++;
|
||||
return at;
|
||||
}
|
||||
|
||||
void spv_remove(spv_mod *m, uint32_t at)
|
||||
{
|
||||
if (at >= m->count) return;
|
||||
free(m->ins[at].w);
|
||||
memmove(&m->ins[at], &m->ins[at + 1], (m->count - at - 1) * sizeof(spv_inst));
|
||||
m->count--;
|
||||
}
|
||||
|
||||
int spv_find_op(const spv_mod *m, uint16_t op, uint32_t from)
|
||||
{
|
||||
for (uint32_t i = from; i < m->count; i++)
|
||||
if (m->ins[i].op == op) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int is_type(uint16_t op) { return op >= 19 && op <= 38; }
|
||||
static int is_const(uint16_t op) { return (op >= 41 && op <= 46) || (op >= 48 && op <= 52); }
|
||||
|
||||
uint32_t spv_result_id(const spv_inst *in)
|
||||
{
|
||||
if (in->n < 2) return 0;
|
||||
if (is_type(in->op) || in->op == SpvOpLabel || in->op == SpvOpString || in->op == SpvOpExtInstImport || in->op == 73)
|
||||
return in->w[0];
|
||||
switch (in->op) {
|
||||
case SpvOpName: case SpvOpMemberName: case SpvOpDecorate: case SpvOpMemberDecorate: case SpvOpEntryPoint:
|
||||
case SpvOpExecutionMode: case SpvOpCapability: case SpvOpExtension: case SpvOpMemoryModel: case SpvOpStore:
|
||||
case SpvOpBranch: case SpvOpBranchConditional: case SpvOpSelectionMerge: case SpvOpReturn: case SpvOpKill:
|
||||
case SpvOpFunctionEnd: case SpvOpLine: case SpvOpNoLine: case SpvOpSource: case SpvOpSourceExtension:
|
||||
case SpvOpDecorateId: case SpvOpDecorateString: case SpvOpMemberDecorateString: case SpvOpModuleProcessed:
|
||||
case SpvOpExecutionModeId: case 246 /* LoopMerge */: case 251 /* Switch */: case 254 /* ReturnValue */:
|
||||
case 255 /* Unreachable */: case 74: case 75: case 224 /* ControlBarrier */: case 225 /* MemoryBarrier */:
|
||||
case SpvOpTerminateInvocation:
|
||||
return 0;
|
||||
default:
|
||||
return in->n >= 3 ? in->w[1] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
int spv_find_def(const spv_mod *m, uint32_t id)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (spv_result_id(&m->ins[i]) == id) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
uint32_t spv_types_end(const spv_mod *m)
|
||||
{
|
||||
int f = spv_find_op(m, SpvOpFunction, 0);
|
||||
return f < 0 ? m->count : (uint32_t)f;
|
||||
}
|
||||
|
||||
uint32_t spv_annotations_end(const spv_mod *m)
|
||||
{
|
||||
uint32_t end = spv_types_end(m);
|
||||
for (uint32_t i = 0; i < end; i++) {
|
||||
uint16_t op = m->ins[i].op;
|
||||
if (is_type(op) || is_const(op) || op == SpvOpVariable || op == SpvOpUndef) return i;
|
||||
}
|
||||
return end;
|
||||
}
|
||||
|
||||
static uint32_t add_global(spv_mod *m, uint16_t op, const uint32_t *ops, uint16_t n)
|
||||
{
|
||||
uint32_t at = spv_types_end(m);
|
||||
spv_insert(m, at, op, ops, n);
|
||||
return at;
|
||||
}
|
||||
|
||||
uint32_t spv_type_float(spv_mod *m, uint32_t width)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypeFloat && m->ins[i].w[1] == width && m->ins[i].n == 3) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m), ops[2] = {id, width};
|
||||
add_global(m, SpvOpTypeFloat, ops, 2);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_int(spv_mod *m, uint32_t width, uint32_t sign)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypeInt && m->ins[i].w[1] == width && m->ins[i].w[2] == sign) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {id, width, sign};
|
||||
add_global(m, SpvOpTypeInt, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_bool(spv_mod *m)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypeBool) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m);
|
||||
add_global(m, SpvOpTypeBool, &id, 1);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_pointer(spv_mod *m, uint32_t storage, uint32_t pointee)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpTypePointer && m->ins[i].w[1] == storage && m->ins[i].w[2] == pointee) return m->ins[i].w[0];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {id, storage, pointee};
|
||||
add_global(m, SpvOpTypePointer, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_type_array(spv_mod *m, uint32_t elem, uint32_t len_const)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
if (m->ins[i].op == SpvOpTypeArray && m->ins[i].w[1] == elem && m->ins[i].w[2] == len_const &&
|
||||
spv_get_decoration(m, m->ins[i].w[0], 6 /* ArrayStride */) < 0)
|
||||
return m->ins[i].w[0];
|
||||
}
|
||||
uint32_t id = spv_new_id(m), ops[3] = {id, elem, len_const};
|
||||
add_global(m, SpvOpTypeArray, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_const_u32(spv_mod *m, uint32_t v)
|
||||
{
|
||||
uint32_t t = spv_type_int(m, 32, 0);
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpConstant && m->ins[i].w[0] == t && m->ins[i].n == 4 && m->ins[i].w[2] == v) return m->ins[i].w[1];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {t, id, v};
|
||||
add_global(m, SpvOpConstant, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t spv_const_f32(spv_mod *m, float v)
|
||||
{
|
||||
uint32_t t = spv_type_float(m, 32), bits;
|
||||
memcpy(&bits, &v, 4);
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpConstant && m->ins[i].w[0] == t && m->ins[i].n == 4 && m->ins[i].w[2] == bits) return m->ins[i].w[1];
|
||||
uint32_t id = spv_new_id(m), ops[3] = {t, id, bits};
|
||||
add_global(m, SpvOpConstant, ops, 3);
|
||||
return id;
|
||||
}
|
||||
|
||||
int64_t spv_get_decoration(const spv_mod *m, uint32_t id, uint32_t decoration)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op == SpvOpDecorate && in->w[0] == id && in->w[1] == decoration) return in->n > 3 ? (int64_t)in->w[2] : 0;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void spv_remove_decoration(spv_mod *m, uint32_t id, uint32_t decoration)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count;) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op == SpvOpDecorate && in->w[0] == id && in->w[1] == decoration) spv_remove(m, i);
|
||||
else i++;
|
||||
}
|
||||
}
|
||||
|
||||
int spv_has_capability(const spv_mod *m, uint32_t cap)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++)
|
||||
if (m->ins[i].op == SpvOpCapability && m->ins[i].w[0] == cap) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void spv_remove_capability(spv_mod *m, uint32_t cap)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count;) {
|
||||
if (m->ins[i].op == SpvOpCapability && m->ins[i].w[0] == cap) spv_remove(m, i);
|
||||
else i++;
|
||||
}
|
||||
}
|
||||
|
||||
void spv_add_capability(spv_mod *m, uint32_t cap)
|
||||
{
|
||||
if (!spv_has_capability(m, cap)) spv_insert(m, 0, SpvOpCapability, &cap, 1);
|
||||
}
|
||||
|
||||
int spv_execution_model(const spv_mod *m)
|
||||
{
|
||||
int e = spv_find_op(m, SpvOpEntryPoint, 0);
|
||||
return e < 0 ? -1 : (int)m->ins[e].w[0];
|
||||
}
|
||||
|
||||
void spv_add_interface(spv_mod *m, uint32_t var)
|
||||
{
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
spv_inst *in = &m->ins[i];
|
||||
if (in->op != SpvOpEntryPoint) continue;
|
||||
uint32_t *nw = realloc(in->w, (size_t)in->n * 4);
|
||||
if (!nw) {
|
||||
m->err = 1;
|
||||
return;
|
||||
}
|
||||
nw[in->n - 1] = var;
|
||||
in->w = nw;
|
||||
in->n++;
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t spv_array_length(const spv_mod *m, uint32_t array_type)
|
||||
{
|
||||
int d = spv_find_def(m, array_type);
|
||||
if (d < 0 || m->ins[d].op != SpvOpTypeArray) return 0;
|
||||
int c = spv_find_def(m, m->ins[d].w[2]);
|
||||
if (c < 0 || m->ins[c].op != SpvOpConstant) return 0;
|
||||
return m->ins[c].w[2];
|
||||
}
|
||||
|
||||
/* Number of locations a type occupies. */
|
||||
static uint32_t loc_count(const spv_mod *m, uint32_t type, int depth)
|
||||
{
|
||||
int d = spv_find_def(m, type);
|
||||
if (d < 0 || depth > 16) return 1;
|
||||
const spv_inst *in = &m->ins[d];
|
||||
switch (in->op) {
|
||||
case SpvOpTypeArray: return spv_array_length(m, type) * loc_count(m, in->w[1], depth + 1);
|
||||
case 24 /* Matrix */: return in->w[2] * loc_count(m, in->w[1], depth + 1);
|
||||
case SpvOpTypeStruct: {
|
||||
uint32_t s = 0;
|
||||
for (uint32_t k = 1; k < (uint32_t)in->n - 1; k++) s += loc_count(m, in->w[k], depth + 1);
|
||||
return s;
|
||||
}
|
||||
case SpvOpTypeVector: {
|
||||
int e = spv_find_def(m, in->w[1]);
|
||||
uint32_t width = e >= 0 ? m->ins[e].w[1] : 32;
|
||||
return (width == 64 && in->w[2] > 2) ? 2 : 1;
|
||||
}
|
||||
default: return 1;
|
||||
}
|
||||
}
|
||||
|
||||
int spv_max_location(const spv_mod *m, uint32_t storage)
|
||||
{
|
||||
int max = -1;
|
||||
for (uint32_t i = 0; i < m->count; i++) {
|
||||
const spv_inst *in = &m->ins[i];
|
||||
if (in->op != SpvOpVariable || in->w[2] != storage) continue;
|
||||
int p = spv_find_def(m, in->w[0]);
|
||||
if (p < 0) continue;
|
||||
uint32_t pointee = m->ins[p].w[2];
|
||||
int64_t loc = spv_get_decoration(m, in->w[1], SpvDecorationLocation);
|
||||
if (loc >= 0) {
|
||||
int top = (int)loc + (int)loc_count(m, pointee, 0) - 1;
|
||||
if (top > max) max = top;
|
||||
continue;
|
||||
}
|
||||
/* A block with member locations. */
|
||||
for (uint32_t k = 0; k < m->count; k++) {
|
||||
const spv_inst *md = &m->ins[k];
|
||||
if (md->op == SpvOpMemberDecorate && md->w[0] == pointee && md->w[2] == SpvDecorationLocation) {
|
||||
int st = spv_find_def(m, pointee);
|
||||
uint32_t mt = st >= 0 && md->w[1] + 1 < m->ins[st].n ? m->ins[st].w[1 + md->w[1]] : 0;
|
||||
int top = (int)md->w[3] + (int)loc_count(m, mt, 0) - 1;
|
||||
if (top > max) max = top;
|
||||
}
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* A small SPIR-V editor for the bridge's shader emulations: parse a module into instructions,
|
||||
* look things up, append/insert/remove instructions, and write it back.
|
||||
*/
|
||||
#ifndef VKB_SPIRV_EDIT_H
|
||||
#define VKB_SPIRV_EDIT_H
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* Opcodes and enums used (from the SPIR-V spec). */
|
||||
enum {
|
||||
SpvOpName = 5, SpvOpMemberName = 6, SpvOpExtension = 10, SpvOpExtInstImport = 11, SpvOpMemoryModel = 14,
|
||||
SpvOpEntryPoint = 15, SpvOpExecutionMode = 16, SpvOpCapability = 17, SpvOpTypeVoid = 19, SpvOpTypeBool = 20,
|
||||
SpvOpTypeInt = 21, SpvOpTypeFloat = 22, SpvOpTypeVector = 23, SpvOpTypeArray = 28, SpvOpTypeRuntimeArray = 29,
|
||||
SpvOpTypeStruct = 30, SpvOpTypePointer = 32, SpvOpTypeFunction = 33, SpvOpConstantTrue = 41,
|
||||
SpvOpConstantFalse = 42, SpvOpConstant = 43, SpvOpConstantComposite = 44, SpvOpFunction = 54,
|
||||
SpvOpFunctionParameter = 55, SpvOpFunctionEnd = 56, SpvOpVariable = 59, SpvOpLoad = 61, SpvOpStore = 62,
|
||||
SpvOpAccessChain = 65, SpvOpInBoundsAccessChain = 66, SpvOpDecorate = 71, SpvOpMemberDecorate = 72,
|
||||
SpvOpCompositeExtract = 81, SpvOpFOrdLessThan = 184, SpvOpLogicalOr = 166, SpvOpSelectionMerge = 247,
|
||||
SpvOpLabel = 248, SpvOpBranch = 249, SpvOpBranchConditional = 250, SpvOpReturn = 253, SpvOpKill = 252,
|
||||
SpvOpTerminateInvocation = 4416, SpvOpLine = 8, SpvOpNoLine = 317, SpvOpModuleProcessed = 330,
|
||||
SpvOpString = 7, SpvOpSource = 3, SpvOpSourceExtension = 4, SpvOpSourceContinued = 2, SpvOpExecutionModeId = 331,
|
||||
SpvOpDecorateId = 332, SpvOpDecorateString = 5632, SpvOpMemberDecorateString = 5633, SpvOpUndef = 1,
|
||||
SpvOpExtInst = 12, SpvOpIAdd = 128, SpvOpUDiv = 134, SpvOpISub = 130,
|
||||
};
|
||||
enum { SpvDecorationBuiltIn = 11, SpvDecorationLocation = 30, SpvDecorationComponent = 31, SpvDecorationBlock = 2,
|
||||
SpvDecorationFlat = 14, SpvDecorationPatch = 15 };
|
||||
enum { SpvBuiltInPosition = 0, SpvBuiltInPointSize = 1, SpvBuiltInClipDistance = 3, SpvBuiltInCullDistance = 4,
|
||||
SpvBuiltInInstanceIndex = 43, SpvBuiltInBaseInstance = 4425 };
|
||||
enum { SpvStorageClassInput = 1, SpvStorageClassOutput = 3, SpvStorageClassPrivate = 6, SpvStorageClassFunction = 7 };
|
||||
enum { SpvCapabilityClipDistance = 32, SpvCapabilityCullDistance = 33, SpvCapabilityTessellationPointSize = 23,
|
||||
SpvCapabilityGeometryPointSize = 24, SpvCapabilityDrawParameters = 4427 };
|
||||
enum { SpvExecutionModelVertex = 0, SpvExecutionModelTessellationControl = 1, SpvExecutionModelTessellationEvaluation = 2,
|
||||
SpvExecutionModelGeometry = 3, SpvExecutionModelFragment = 4, SpvExecutionModelGLCompute = 5 };
|
||||
|
||||
typedef struct spv_inst {
|
||||
uint16_t op;
|
||||
uint16_t n; /* word count including the first word */
|
||||
uint32_t *w; /* operand words (w[0] = first operand), n - 1 of them */
|
||||
} spv_inst;
|
||||
|
||||
typedef struct spv_mod {
|
||||
uint32_t header[5];
|
||||
spv_inst *ins;
|
||||
uint32_t count, cap;
|
||||
int err;
|
||||
} spv_mod;
|
||||
|
||||
int spv_parse(spv_mod *m, const uint32_t *code, size_t bytes);
|
||||
/* Writes the module into a malloc'd buffer; returns its size in bytes (0 on failure). */
|
||||
size_t spv_write(const spv_mod *m, uint32_t **out);
|
||||
void spv_free(spv_mod *m);
|
||||
|
||||
static inline uint32_t spv_version(const spv_mod *m) { return m->header[1]; }
|
||||
static inline uint32_t spv_new_id(spv_mod *m) { return m->header[3]++; }
|
||||
|
||||
/* Insert an instruction before index `at` (at = count appends). Operands copied. Returns index. */
|
||||
uint32_t spv_insert(spv_mod *m, uint32_t at, uint16_t op, const uint32_t *ops, uint16_t nops);
|
||||
void spv_remove(spv_mod *m, uint32_t at);
|
||||
|
||||
/* Index of the first instruction with this opcode (or of the defining instruction of `id`), or -1. */
|
||||
int spv_find_op(const spv_mod *m, uint16_t op, uint32_t from);
|
||||
int spv_find_def(const spv_mod *m, uint32_t id);
|
||||
/* The id an instruction defines (result id), or 0. */
|
||||
uint32_t spv_result_id(const spv_inst *in);
|
||||
|
||||
/* Section boundaries: index where new decorations / types / function code may be inserted. */
|
||||
uint32_t spv_types_end(const spv_mod *m); /* end of the types/constants/globals section */
|
||||
uint32_t spv_annotations_end(const spv_mod *m); /* end of the decoration section */
|
||||
|
||||
/* Types and constants: found when they already exist (non-aggregate types must be unique). */
|
||||
uint32_t spv_type_float(spv_mod *m, uint32_t width);
|
||||
uint32_t spv_type_int(spv_mod *m, uint32_t width, uint32_t sign);
|
||||
uint32_t spv_type_bool(spv_mod *m);
|
||||
uint32_t spv_type_pointer(spv_mod *m, uint32_t storage, uint32_t pointee);
|
||||
uint32_t spv_type_array(spv_mod *m, uint32_t elem, uint32_t len_const);
|
||||
uint32_t spv_const_u32(spv_mod *m, uint32_t v);
|
||||
uint32_t spv_const_f32(spv_mod *m, float v);
|
||||
|
||||
/* Decorations of an id: returns the operand (after the decoration) or -1. */
|
||||
int64_t spv_get_decoration(const spv_mod *m, uint32_t id, uint32_t decoration);
|
||||
void spv_remove_decoration(spv_mod *m, uint32_t id, uint32_t decoration);
|
||||
int spv_has_capability(const spv_mod *m, uint32_t cap);
|
||||
void spv_remove_capability(spv_mod *m, uint32_t cap);
|
||||
void spv_add_capability(spv_mod *m, uint32_t cap);
|
||||
/* The execution model of the (first) entry point, or -1. */
|
||||
int spv_execution_model(const spv_mod *m);
|
||||
/* Adds an interface variable to every entry point. */
|
||||
void spv_add_interface(spv_mod *m, uint32_t var);
|
||||
/* Highest Location used by variables of a storage class (members included), or -1. */
|
||||
int spv_max_location(const spv_mod *m, uint32_t storage);
|
||||
/* Length of an OpTypeArray (via its constant), or 0. */
|
||||
uint32_t spv_array_length(const spv_mod *m, uint32_t array_type);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,153 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later
|
||||
*
|
||||
* DroidDeck Vulkan bridge - server side (bionic on the device, glibc for host tests).
|
||||
*
|
||||
* The server owns the real Vulkan objects. Linux programs in the session talk to it through the
|
||||
* client ICD (tools/vkbridge/client) over a Unix socket; every connection is one client thread.
|
||||
*/
|
||||
#ifndef VKB_SERVER_H
|
||||
#define VKB_SERVER_H
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "vkb_server_iface.h"
|
||||
#include "vkb_proto.h"
|
||||
#include "vkb_log.h"
|
||||
#include "gen/vkb_server_gen.h"
|
||||
|
||||
#define VKB_MAX_TABLES 65536
|
||||
#define VKB_MAX_PDS 16
|
||||
|
||||
/* A client process (all connections that said hello with the same token). */
|
||||
#define VKB_SEQ_RING 65536
|
||||
|
||||
typedef struct vkb_srv_proc {
|
||||
uint64_t token;
|
||||
int pid;
|
||||
int conns;
|
||||
struct vkb_srv_proc *next;
|
||||
/* Ordering of the process's asynchronous requests (vkb_msg_hdr.seq/barrier). */
|
||||
pthread_mutex_t olock;
|
||||
pthread_cond_t ocond;
|
||||
uint64_t watermark; /* every async seq <= this has run */
|
||||
uint8_t done[VKB_SEQ_RING]; /* seqs above the watermark that have run */
|
||||
int conn_closed; /* a connection ended (a seq may never arrive) */
|
||||
int driver_crashed; /* the driver faulted serving it: its objects are left alone */
|
||||
} vkb_srv_proc;
|
||||
|
||||
typedef struct vkb_srv_conn {
|
||||
int sock;
|
||||
vkb_srv_proc *proc;
|
||||
/* Receive buffer: messages are parsed out of it in place (srv_recv). */
|
||||
uint8_t *rb;
|
||||
size_t rcap, rpos, rlen;
|
||||
int fdq[2 * VKB_MAX_FDS]; /* descriptors received ahead of their message's turn */
|
||||
int fdn;
|
||||
vkb_arena arena;
|
||||
pthread_t thread;
|
||||
} vkb_srv_conn;
|
||||
|
||||
/* Startup knowledge about each physical device (keyed by deviceUUID). */
|
||||
typedef struct vkb_pd_knowledge {
|
||||
uint8_t uuid[VK_UUID_SIZE];
|
||||
char name[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
|
||||
vkb_server_pd_info info;
|
||||
int valid;
|
||||
} vkb_pd_knowledge;
|
||||
|
||||
/* A tracked device memory allocation. */
|
||||
typedef struct vkb_srv_mem {
|
||||
VkDeviceMemory mem;
|
||||
VkDeviceSize size;
|
||||
uint32_t type;
|
||||
uint32_t strategy;
|
||||
void *host_ptr; /* hostptr: server's mapping of the client's memfd */
|
||||
size_t host_len;
|
||||
void *mapped; /* server-side vkMapMemory pointer (for flush/invalidate) */
|
||||
void *ahb; /* AHardwareBuffer* (Android) */
|
||||
struct vkb_srv_mem *next;
|
||||
} vkb_srv_mem;
|
||||
|
||||
struct vkb_emu_device;
|
||||
|
||||
typedef struct vkb_srv_table {
|
||||
uint32_t id;
|
||||
int is_device;
|
||||
vkb_srv_proc *proc;
|
||||
VkInstance instance;
|
||||
VkDevice device;
|
||||
VkPhysicalDevice physical; /* device tables */
|
||||
struct vkb_srv_table *parent; /* device -> instance */
|
||||
vkb_dispatch dt; /* what handlers call (may hold emulation wrappers) */
|
||||
vkb_dispatch real; /* the driver's own entry points */
|
||||
uint32_t api_version;
|
||||
const vkb_pd_knowledge *pd;
|
||||
pthread_mutex_t lock;
|
||||
vkb_srv_mem *mems[256]; /* hash by handle */
|
||||
struct vkb_emu_device *emu;
|
||||
struct vkb_pcache *pcache; /* server_pcache.c */
|
||||
struct vkb_dsmap *dsmap; /* server_dsmap.c */
|
||||
struct vkb_spvfix *spvfix; /* server_spvfix.c */
|
||||
struct vkb_cbtrack *cbtrack; /* server_cbtrack.c */
|
||||
} vkb_srv_table;
|
||||
|
||||
/* server_main.c */
|
||||
extern PFN_vkGetInstanceProcAddr vkb_gipa;
|
||||
extern vkb_dispatch vkb_global_dt;
|
||||
extern int vkb_verbose;
|
||||
|
||||
void vkb_log_summary(void);
|
||||
|
||||
/* server_cbtrack.c: command buffers the device handed out; others are refused, not passed on. */
|
||||
void vkb_cbtrack_device_init(vkb_srv_table *t);
|
||||
void vkb_cbtrack_device_destroy(vkb_srv_table *t);
|
||||
int vkb_cbtrack_known(vkb_srv_table *t, VkCommandBuffer cb, const char *what);
|
||||
|
||||
/* server_spvfix.c */
|
||||
void vkb_spvfix_device_init(vkb_srv_table *t);
|
||||
void vkb_spvfix_device_destroy(vkb_srv_table *t);
|
||||
|
||||
/* server_dsmap.c */
|
||||
void vkb_dsmap_device_init(vkb_srv_table *t);
|
||||
void vkb_dsmap_device_destroy(vkb_srv_table *t);
|
||||
|
||||
/* server_pcache.c */
|
||||
void vkb_pcache_set_dir(const char *dir);
|
||||
void vkb_pcache_device_init(vkb_srv_table *t);
|
||||
void vkb_pcache_device_destroy(vkb_srv_table *t);
|
||||
|
||||
/* server_conn.c */
|
||||
void vkb_srv_serve(int listen_fd);
|
||||
vkb_srv_table *vkb_table_get(uint32_t id);
|
||||
uint32_t vkb_table_register(vkb_srv_table *t);
|
||||
void vkb_table_unregister(vkb_srv_table *t);
|
||||
void vkb_srv_reply_status(vkb_srv_call *c, uint32_t status);
|
||||
/* The table of the call being executed on this thread (emulation wrappers use it). */
|
||||
vkb_srv_table *vkb_srv_current_table(void);
|
||||
void vkb_srv_set_current_table(vkb_srv_table *t);
|
||||
void vkb_proc_cleanup(vkb_srv_proc *p);
|
||||
|
||||
/* server_instance.c */
|
||||
void vkb_selftest_all(void);
|
||||
const vkb_pd_knowledge *vkb_pd_lookup(const vkb_dispatch *dt, VkPhysicalDevice pd);
|
||||
extern vkb_pd_knowledge vkb_pds[VKB_MAX_PDS];
|
||||
extern int vkb_npds;
|
||||
|
||||
/* server_memory.c */
|
||||
extern PFN_vkGetDeviceProcAddr vkb_mem_gdpa;
|
||||
void vkb_mem_selftest(vkb_pd_knowledge *k, VkInstance inst, const vkb_dispatch *idt, VkPhysicalDevice pd);
|
||||
const char *const *vkb_mem_required_extensions(uint32_t strategy, uint32_t *count);
|
||||
void vkb_mem_track(vkb_srv_table *dev, vkb_srv_mem *m);
|
||||
vkb_srv_mem *vkb_mem_find(vkb_srv_table *dev, VkDeviceMemory mem, int remove);
|
||||
void vkb_mem_release(vkb_srv_table *dev, vkb_srv_mem *m);
|
||||
void vkb_mem_free_all(vkb_srv_table *dev);
|
||||
|
||||
/* emulation (server_emu*.c) */
|
||||
uint32_t vkb_emu_detect(const vkb_dispatch *idt, VkPhysicalDevice pd, uint32_t *missing);
|
||||
void vkb_emu_device_create_info(vkb_srv_table *inst, VkPhysicalDevice pd, uint32_t emu,
|
||||
VkDeviceCreateInfo *ci, vkb_arena *a);
|
||||
void vkb_emu_device_init(vkb_srv_table *dev, uint32_t emu);
|
||||
void vkb_emu_device_destroy(vkb_srv_table *dev);
|
||||
|
||||
#endif
|
||||
@@ -4,7 +4,7 @@
|
||||
# generated/ (no host wayland-scanner needed at app build time). Built by the app
|
||||
# (add_subdirectory from ../CMakeLists.txt) and on its own by standalone/ for
|
||||
# build-waylandcomp.yml.
|
||||
add_library(bannerwayland SHARED
|
||||
add_library(droiddeckwayland SHARED
|
||||
src/compositor.c
|
||||
src/vk_present.c
|
||||
src/effects_chain.c
|
||||
@@ -12,17 +12,20 @@ add_library(bannerwayland SHARED
|
||||
src/sc_layer.c
|
||||
src/ahb_swapchain.c
|
||||
src/waylandcomp_jni.c
|
||||
src/banner_ext.c
|
||||
src/droiddeck_ext.c
|
||||
src/wl_dmabuf.c
|
||||
src/wl_android_buffer.c
|
||||
src/wl_clipboard.c
|
||||
src/wl_text_input.c
|
||||
src/wl_toplevel_icon.c
|
||||
src/wl_single_pixel.c
|
||||
src/wl_color_mgmt.c
|
||||
src/hdr_compose.c
|
||||
src/blend_pass.c
|
||||
generated/color-management-v1-protocol.c
|
||||
generated/xdg-shell-protocol.c
|
||||
generated/linux-dmabuf-v1-protocol.c
|
||||
generated/wayland-android-protocol.c
|
||||
generated/viewporter-protocol.c
|
||||
generated/banner-desktop-v1-protocol.c
|
||||
generated/presentation-time-protocol.c
|
||||
@@ -31,14 +34,15 @@ add_library(bannerwayland SHARED
|
||||
generated/wlr-data-control-unstable-v1-protocol.c
|
||||
generated/text-input-unstable-v3-protocol.c
|
||||
generated/xdg-toplevel-icon-v1-protocol.c
|
||||
generated/single-pixel-buffer-v1-protocol.c
|
||||
generated/banner-ahb-v1-protocol.c
|
||||
src/framegen_bridge.c
|
||||
src/framegen_jni.c
|
||||
)
|
||||
# Warnings on for the compositor's own C. They do not fail the build; they are there to be read.
|
||||
target_compile_options(bannerwayland PRIVATE
|
||||
target_compile_options(droiddeckwayland PRIVATE
|
||||
$<$<COMPILE_LANGUAGE:C>:-Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers>)
|
||||
target_include_directories(bannerwayland PRIVATE
|
||||
target_include_directories(droiddeckwayland PRIVATE
|
||||
generated
|
||||
prebuilt/include
|
||||
src
|
||||
@@ -54,56 +58,56 @@ target_include_directories(bannerwayland PRIVATE
|
||||
# framegen tree and the vendored DXBC translator (thirdparty/dxbc, for the LSFG cache format),
|
||||
# which only the app build has: the standalone build (standalone/) gets the stub, which reports
|
||||
# every engine unavailable and generates nothing.
|
||||
set(BANNER_FRAMEGEN_LSFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/lsfg)
|
||||
set(BANNER_FRAMEGEN_WINFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/winfg)
|
||||
if (TARGET dxbc AND EXISTS ${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
|
||||
AND EXISTS ${BANNER_FRAMEGEN_WINFG_DIR}/winfg_engine.cpp)
|
||||
message(STATUS "bannerwayland: frame-generation engines built in (LSFG Native, Win-FG Native)")
|
||||
target_sources(bannerwayland PRIVATE
|
||||
set(DROIDDECK_FRAMEGEN_LSFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/lsfg)
|
||||
set(DROIDDECK_FRAMEGEN_WINFG_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../framegen/winfg)
|
||||
if (TARGET dxbc AND EXISTS ${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
|
||||
AND EXISTS ${DROIDDECK_FRAMEGEN_WINFG_DIR}/winfg_engine.cpp)
|
||||
message(STATUS "droiddeckwayland: frame-generation engines built in (LSFG Native, Win-FG Native)")
|
||||
target_sources(droiddeckwayland PRIVATE
|
||||
src/framegen_engine.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_dll.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_dxbc.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_vkd.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_common.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_shaders.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_mipmaps.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_alpha.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_beta.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_gamma.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_delta.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_generate.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_chain.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_pacer.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_governor.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_probe.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dll.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_dxbc.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_vkd.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_common.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_shaders.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_mipmaps.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_alpha.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_beta.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_gamma.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_delta.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_generate.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_chain.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_pacer.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_engine.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_governor.cpp
|
||||
# The Lossless.dll import (validate / extract / cache) for the app's LsfgNative.
|
||||
${BANNER_FRAMEGEN_LSFG_DIR}/lsfg_jni.cpp
|
||||
${BANNER_FRAMEGEN_WINFG_DIR}/framegen.cpp
|
||||
${BANNER_FRAMEGEN_WINFG_DIR}/winfg_vkd.cpp
|
||||
${BANNER_FRAMEGEN_WINFG_DIR}/winfg_engine.cpp
|
||||
${DROIDDECK_FRAMEGEN_LSFG_DIR}/lsfg_jni.cpp
|
||||
${DROIDDECK_FRAMEGEN_WINFG_DIR}/framegen.cpp
|
||||
${DROIDDECK_FRAMEGEN_WINFG_DIR}/winfg_vkd.cpp
|
||||
${DROIDDECK_FRAMEGEN_WINFG_DIR}/winfg_engine.cpp
|
||||
)
|
||||
target_include_directories(bannerwayland PRIVATE
|
||||
target_include_directories(droiddeckwayland PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/.. # <thirdparty/...> as the frame-generation engines see it
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../framegen # VulkanRendererContext.h (VkTable), lsfg/, winfg/
|
||||
)
|
||||
target_compile_options(bannerwayland PRIVATE
|
||||
target_compile_options(droiddeckwayland PRIVATE
|
||||
$<$<COMPILE_LANGUAGE:CXX>:-std=c++17 -fvisibility=hidden>)
|
||||
target_compile_definitions(bannerwayland PRIVATE
|
||||
target_compile_definitions(droiddeckwayland PRIVATE
|
||||
WINFG_UPSTREAM="${WINFG_UPSTREAM}"
|
||||
WINFG_CHAIN_HASH="${WINFG_CHAIN_HASH}"
|
||||
)
|
||||
target_link_libraries(bannerwayland dxbc atomic)
|
||||
target_link_libraries(droiddeckwayland dxbc atomic)
|
||||
else()
|
||||
message(STATUS "bannerwayland: frame-generation engines NOT built in (standalone build): stub")
|
||||
target_sources(bannerwayland PRIVATE src/framegen_engine_stub.c)
|
||||
message(STATUS "droiddeckwayland: frame-generation engines NOT built in (standalone build): stub")
|
||||
target_sources(droiddeckwayland PRIVATE src/framegen_engine_stub.c)
|
||||
endif()
|
||||
add_library(wayland-server SHARED IMPORTED)
|
||||
set_target_properties(wayland-server PROPERTIES IMPORTED_LOCATION
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/prebuilt/lib/libwayland-server.so)
|
||||
# Vulkan is loaded at runtime via adrenotools (Turnip), not linked directly - so the
|
||||
# compositor uses Turnip's driver, which supports dmabuf import (drm_format_modifier).
|
||||
target_link_libraries(bannerwayland
|
||||
target_link_libraries(droiddeckwayland
|
||||
wayland-server
|
||||
adrenotools
|
||||
dl
|
||||
|
||||
@@ -29,7 +29,7 @@ the dma-buf fd through `zwp_linux_dmabuf_v1` as today (so the blit path stays as
|
||||
The host half - one `ASurfaceControl` layer per fullscreen window, geometry from the fullscreen
|
||||
mode, release fences from `ASurfaceTransaction_setOnComplete`, black base surface, HUD/pointer as
|
||||
Android views above - is implemented in this branch as a gated prototype (`sc_layer.c`,
|
||||
`BANNER_WAYLAND_ZERO_COPY=1`) with a compositor-owned AHB pool and one blit, so the
|
||||
`DROIDDECK_WAYLAND_ZERO_COPY=1`) with a compositor-owned AHB pool and one blit, so the
|
||||
SurfaceFlinger side can be measured on the device before the driver work starts.
|
||||
|
||||
---
|
||||
@@ -240,13 +240,13 @@ Prerequisite: a build of this branch, container on Wayland, the AIO Graphics Tes
|
||||
D3D12 tabs) as the workload, session log in `Download/Wayland-logs/`.
|
||||
|
||||
0. **UBWC modifier A/B (no layers).** Done on `feat/wayland-ubwc` (advertised when the compositor's
|
||||
driver imports it, `BANNER_WAYLAND_UBWC=0` = old linear-only list; see `WAYLAND_RUNTIME.md`
|
||||
driver imports it, `DROIDDECK_WAYLAND_UBWC=0` = old linear-only list; see `WAYLAND_RUNTIME.md`
|
||||
"Compressed (UBWC) game buffers"). Run the AIO Vulkan/D3D12 with and without. Expect
|
||||
`vulkan: … is presenting GPU frames through Wayland: WxH, format XB24, tiled (zero-copy)` and
|
||||
no `dmabuf import failed`. Records how much of the 20 % is the linear swapchain alone.
|
||||
1. **Layer mode smoke.** Put `BANNER_WAYLAND_ZERO_COPY=1` in the container's environment
|
||||
1. **Layer mode smoke.** Put `DROIDDECK_WAYLAND_ZERO_COPY=1` in the container's environment
|
||||
variables, launch the AIO fullscreen. Expected log lines (tag `layer`):
|
||||
`SurfaceControl "banner_wayland_game" created as a child of the screen surface`,
|
||||
`SurfaceControl "droiddeck_wayland_game" created as a child of the screen surface`,
|
||||
`pool buffer 1920x1080 UBWC (QCOM_COMPRESSED), stride 1920 px (gralloc handle 2 fds / N ints)`
|
||||
(or `linear` after `import of a UBWC … failed` - also a result: it tells whether the compositor
|
||||
Turnip accepts gralloc's UBWC pitch), `geometry: buffer 0,0-1920,1080 -> screen …`,
|
||||
@@ -254,7 +254,7 @@ D3D12 tabs) as the workload, session log in `Download/Wayland-logs/`.
|
||||
and the probe line `kernel exports sync_file fences from the game's dma-buf …` or
|
||||
`DMA_BUF_IOCTL_EXPORT_SYNC_FILE … failed (…)`. Picture correct, HUD and pointer on top, fullscreen
|
||||
mode changes move the layer (`geometry:` lines).
|
||||
2. **Composition type.** With the AIO running: `dumpsys SurfaceFlinger | grep -A3 banner_wayland_game`
|
||||
2. **Composition type.** With the AIO running: `dumpsys SurfaceFlinger | grep -A3 droiddeck_wayland_game`
|
||||
and the `GPU_TARGET` line of the pipe table. DEVICE/DEVICE on the game layer with an empty GPU
|
||||
target = the DPU does the scaling; CLIENT = no gain on this panel orientation → try the
|
||||
handheld's native orientation / a resolution equal to the panel's.
|
||||
@@ -271,7 +271,7 @@ harden: async fence instead of CPU wait, per-window layers, presentation feedbac
|
||||
`getLatchTime`); option (a) WSI + protocol + wcp = 2–3 days + 1 day device proving; option (c) =
|
||||
3–4 days + the same proving; (b) = not buildable.
|
||||
|
||||
## 6. What the prototype in this branch does (`BANNER_WAYLAND_ZERO_COPY=1`)
|
||||
## 6. What the prototype in this branch does (`DROIDDECK_WAYLAND_ZERO_COPY=1`)
|
||||
|
||||
Files: `src/sc_layer.{c,h}` (new), `src/vk_present.{c,h}` (`vkp_image_import_dmabuf` with a
|
||||
blit-destination role, `vkp_blit_image`, `vkp_update_map`, `vkp_map_draw`, `vkp_window`,
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
/*
|
||||
* Copyright © 2022 Simon Ser
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice (including the next
|
||||
* paragraph) shall be included in all copies or substantial portions of the
|
||||
* Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE 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 wl_buffer_interface;
|
||||
|
||||
static const struct wl_interface *single_pixel_buffer_v1_types[] = {
|
||||
&wl_buffer_interface,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
};
|
||||
|
||||
static const struct wl_message wp_single_pixel_buffer_manager_v1_requests[] = {
|
||||
{ "destroy", "", single_pixel_buffer_v1_types + 0 },
|
||||
{ "create_u32_rgba_buffer", "nuuuu", single_pixel_buffer_v1_types + 0 },
|
||||
};
|
||||
|
||||
WL_PRIVATE const struct wl_interface wp_single_pixel_buffer_manager_v1_interface = {
|
||||
"wp_single_pixel_buffer_manager_v1", 1,
|
||||
2, wp_single_pixel_buffer_manager_v1_requests,
|
||||
0, NULL,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/* Generated by wayland-scanner 1.26.0 */
|
||||
|
||||
#ifndef SINGLE_PIXEL_BUFFER_V1_SERVER_PROTOCOL_H
|
||||
#define SINGLE_PIXEL_BUFFER_V1_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_single_pixel_buffer_v1 The single_pixel_buffer_v1 protocol
|
||||
* single pixel buffer factory
|
||||
*
|
||||
* @section page_desc_single_pixel_buffer_v1 Description
|
||||
*
|
||||
* This protocol extension allows clients to create single-pixel buffers.
|
||||
*
|
||||
* Compositors supporting this protocol extension should also support the
|
||||
* viewporter protocol extension. Clients may use viewporter to scale a
|
||||
* single-pixel buffer to a desired size.
|
||||
*
|
||||
* Warning! The protocol described in this file is currently in the testing
|
||||
* phase. Backward compatible changes may be added together with the
|
||||
* corresponding interface version bump. Backward incompatible changes can
|
||||
* only be done by creating a new major version of the extension.
|
||||
*
|
||||
* @section page_ifaces_single_pixel_buffer_v1 Interfaces
|
||||
* - @subpage page_iface_wp_single_pixel_buffer_manager_v1 - global factory for single-pixel buffers
|
||||
* @section page_copyright_single_pixel_buffer_v1 Copyright
|
||||
* <pre>
|
||||
*
|
||||
* Copyright © 2022 Simon Ser
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a
|
||||
* copy of this software and associated documentation files (the "Software"),
|
||||
* to deal in the Software without restriction, including without limitation
|
||||
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
* and/or sell copies of the Software, and to permit persons to whom the
|
||||
* Software is furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice (including the next
|
||||
* paragraph) shall be included in all copies or substantial portions of the
|
||||
* Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
* DEALINGS IN THE SOFTWARE.
|
||||
* </pre>
|
||||
*/
|
||||
struct wl_buffer;
|
||||
struct wp_single_pixel_buffer_manager_v1;
|
||||
|
||||
#ifndef WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE
|
||||
#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_INTERFACE
|
||||
/**
|
||||
* @page page_iface_wp_single_pixel_buffer_manager_v1 wp_single_pixel_buffer_manager_v1
|
||||
* @section page_iface_wp_single_pixel_buffer_manager_v1_desc Description
|
||||
*
|
||||
* The wp_single_pixel_buffer_manager_v1 interface is a factory for
|
||||
* single-pixel buffers.
|
||||
* @section page_iface_wp_single_pixel_buffer_manager_v1_api API
|
||||
* See @ref iface_wp_single_pixel_buffer_manager_v1.
|
||||
*/
|
||||
/**
|
||||
* @defgroup iface_wp_single_pixel_buffer_manager_v1 The wp_single_pixel_buffer_manager_v1 interface
|
||||
*
|
||||
* The wp_single_pixel_buffer_manager_v1 interface is a factory for
|
||||
* single-pixel buffers.
|
||||
*/
|
||||
extern const struct wl_interface wp_single_pixel_buffer_manager_v1_interface;
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @ingroup iface_wp_single_pixel_buffer_manager_v1
|
||||
* @struct wp_single_pixel_buffer_manager_v1_interface
|
||||
*/
|
||||
struct wp_single_pixel_buffer_manager_v1_interface {
|
||||
/**
|
||||
* destroy the manager
|
||||
*
|
||||
* Destroy the wp_single_pixel_buffer_manager_v1 object.
|
||||
*
|
||||
* The child objects created via this interface are unaffected.
|
||||
*/
|
||||
void (*destroy)(struct wl_client *client,
|
||||
struct wl_resource *resource);
|
||||
/**
|
||||
* create a 1×1 buffer from 32-bit RGBA values
|
||||
*
|
||||
* Create a single-pixel buffer from four 32-bit RGBA values.
|
||||
*
|
||||
* Unless specified in another protocol extension, the RGBA values
|
||||
* use pre-multiplied alpha.
|
||||
*
|
||||
* The width and height of the buffer are 1.
|
||||
*
|
||||
* The r, g, b and a arguments valid range is from UINT32_MIN (0)
|
||||
* to UINT32_MAX (0xffffffff).
|
||||
*
|
||||
* These arguments should be interpreted as a percentage, i.e. -
|
||||
* UINT32_MIN = 0% of the given color component - UINT32_MAX = 100%
|
||||
* of the given color component
|
||||
* @param r value of the buffer's red channel
|
||||
* @param g value of the buffer's green channel
|
||||
* @param b value of the buffer's blue channel
|
||||
* @param a value of the buffer's alpha channel
|
||||
*/
|
||||
void (*create_u32_rgba_buffer)(struct wl_client *client,
|
||||
struct wl_resource *resource,
|
||||
uint32_t id,
|
||||
uint32_t r,
|
||||
uint32_t g,
|
||||
uint32_t b,
|
||||
uint32_t a);
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
* @ingroup iface_wp_single_pixel_buffer_manager_v1
|
||||
*/
|
||||
#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_DESTROY_SINCE_VERSION 1
|
||||
/**
|
||||
* @ingroup iface_wp_single_pixel_buffer_manager_v1
|
||||
*/
|
||||
#define WP_SINGLE_PIXEL_BUFFER_MANAGER_V1_CREATE_U32_RGBA_BUFFER_SINCE_VERSION 1
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -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,76 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<protocol name="single_pixel_buffer_v1">
|
||||
<copyright>
|
||||
Copyright © 2022 Simon Ser
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a
|
||||
copy of this software and associated documentation files (the "Software"),
|
||||
to deal in the Software without restriction, including without limitation
|
||||
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
||||
and/or sell copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice (including the next
|
||||
paragraph) shall be included in all copies or substantial portions of the
|
||||
Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
|
||||
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
</copyright>
|
||||
|
||||
<description summary="single pixel buffer factory">
|
||||
This protocol extension allows clients to create single-pixel buffers.
|
||||
|
||||
Compositors supporting this protocol extension should also support the
|
||||
viewporter protocol extension. Clients may use viewporter to scale a
|
||||
single-pixel buffer to a desired size.
|
||||
|
||||
Warning! The protocol described in this file is currently in the testing
|
||||
phase. Backward compatible changes may be added together with the
|
||||
corresponding interface version bump. Backward incompatible changes can
|
||||
only be done by creating a new major version of the extension.
|
||||
</description>
|
||||
|
||||
<interface name="wp_single_pixel_buffer_manager_v1" version="1">
|
||||
<description summary="global factory for single-pixel buffers">
|
||||
The wp_single_pixel_buffer_manager_v1 interface is a factory for
|
||||
single-pixel buffers.
|
||||
</description>
|
||||
|
||||
<request name="destroy" type="destructor">
|
||||
<description summary="destroy the manager">
|
||||
Destroy the wp_single_pixel_buffer_manager_v1 object.
|
||||
|
||||
The child objects created via this interface are unaffected.
|
||||
</description>
|
||||
</request>
|
||||
|
||||
<request name="create_u32_rgba_buffer">
|
||||
<description summary="create a 1×1 buffer from 32-bit RGBA values">
|
||||
Create a single-pixel buffer from four 32-bit RGBA values.
|
||||
|
||||
Unless specified in another protocol extension, the RGBA values use
|
||||
pre-multiplied alpha.
|
||||
|
||||
The width and height of the buffer are 1.
|
||||
|
||||
The r, g, b and a arguments valid range is from UINT32_MIN (0)
|
||||
to UINT32_MAX (0xffffffff).
|
||||
|
||||
These arguments should be interpreted as a percentage, i.e.
|
||||
- UINT32_MIN = 0% of the given color component
|
||||
- UINT32_MAX = 100% of the given color component
|
||||
</description>
|
||||
<arg name="id" type="new_id" interface="wl_buffer"/>
|
||||
<arg name="r" type="uint" summary="value of the buffer's red channel"/>
|
||||
<arg name="g" type="uint" summary="value of the buffer's green channel"/>
|
||||
<arg name="b" type="uint" summary="value of the buffer's blue channel"/>
|
||||
<arg name="a" type="uint" summary="value of the buffer's alpha channel"/>
|
||||
</request>
|
||||
</interface>
|
||||
</protocol>
|
||||
@@ -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>
|
||||
@@ -2,8 +2,8 @@
|
||||
* See ahb_swapchain.h and ZERO_COPY_SPIKE.md. */
|
||||
#define _GNU_SOURCE
|
||||
#include "ahb_swapchain.h"
|
||||
#include "banner_color.h"
|
||||
#include "banner_ext.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "sc_layer.h"
|
||||
#include "vk_present.h"
|
||||
#include "banner-ahb-v1-server-protocol.h"
|
||||
@@ -22,10 +22,10 @@
|
||||
#define MOD_QCOM_COMPRESSED 0x0500000000000001ULL /* DRM_FORMAT_MOD_QCOM_COMPRESSED (UBWC) */
|
||||
|
||||
/* linux/dma-buf.h (not in the NDK sysroot's older headers): sync_file export / import. */
|
||||
struct banner_dma_buf_sync_file { uint32_t flags; int32_t fd; };
|
||||
#define BANNER_DMA_BUF_SYNC_READ 1u
|
||||
#define BANNER_DMA_BUF_IOCTL_EXPORT_SYNC_FILE _IOWR('b', 2, struct banner_dma_buf_sync_file)
|
||||
#define BANNER_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct banner_dma_buf_sync_file)
|
||||
struct droiddeck_dma_buf_sync_file { uint32_t flags; int32_t fd; };
|
||||
#define DROIDDECK_DMA_BUF_SYNC_READ 1u
|
||||
#define DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE _IOWR('b', 2, struct droiddeck_dma_buf_sync_file)
|
||||
#define DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE _IOW('b', 3, struct droiddeck_dma_buf_sync_file)
|
||||
|
||||
extern volatile int g_zero_copy;
|
||||
|
||||
@@ -86,13 +86,16 @@ static struct ahb_buf *find_buf(uint64_t id) {
|
||||
}
|
||||
|
||||
static void buf_free(struct ahb_buf *ab) {
|
||||
/* A display release does not prove the compositor's Vulkan reads finished.
|
||||
* Keep the AHB reference and its DMA-BUF record even if the client is gone. */
|
||||
if (vkp_completion_unknown()) return;
|
||||
if (ab->resource) { wl_list_remove(&ab->resource_destroy.link); ab->resource = NULL; }
|
||||
if (ab->fence_src) { wl_event_source_remove(ab->fence_src); ab->fence_src = NULL; }
|
||||
if (ab->fence_fd >= 0) { close(ab->fence_fd); ab->fence_fd = -1; }
|
||||
wl_list_remove(&ab->link);
|
||||
*banner_dmabuf_ahb_slot(ab->b) = NULL;
|
||||
*droiddeck_dmabuf_ahb_slot(ab->b) = NULL;
|
||||
AHardwareBuffer_release(ab->ahb);
|
||||
banner_dmabuf_unref(ab->b);
|
||||
droiddeck_dmabuf_unref(ab->b);
|
||||
free(ab);
|
||||
}
|
||||
|
||||
@@ -112,8 +115,9 @@ static void on_buffer_resource_destroyed(struct wl_listener *l, void *data) {
|
||||
/* ---- release: SurfaceFlinger is done with the buffer -> the game's next acquire waits, then wl_buffer.release */
|
||||
|
||||
static void send_deferred_release(struct ahb_buf *ab) {
|
||||
if (vkp_completion_unknown()) return;
|
||||
if (ab->release_pending && ab->resource)
|
||||
banner_release_buffer(ab->surface, ab->resource, ab->surface != NULL, ab->deferred_ns);
|
||||
droiddeck_release_buffer(ab->surface, ab->resource, ab->surface != NULL, ab->deferred_ns);
|
||||
ab->release_pending = 0;
|
||||
ab->surface = NULL;
|
||||
}
|
||||
@@ -138,14 +142,14 @@ static void handle_released(uint64_t id, int fd) {
|
||||
if (!ab) { if (fd >= 0) close(fd); return; }
|
||||
ab->on_layer = 0;
|
||||
if (fd >= 0) {
|
||||
struct banner_dma_buf_sync_file imp = {.flags = BANNER_DMA_BUF_SYNC_READ, .fd = fd};
|
||||
int dmabuf_fd = banner_dmabuf_fd(ab->b);
|
||||
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, BANNER_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
|
||||
struct droiddeck_dma_buf_sync_file imp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = fd};
|
||||
int dmabuf_fd = droiddeck_dmabuf_fd(ab->b);
|
||||
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE, &imp) == 0) {
|
||||
close(fd);
|
||||
} else {
|
||||
if (!g_import_failed_logged) {
|
||||
g_import_failed_logged = 1;
|
||||
banner_log("layer", "zero-copy: DMA_BUF_IOCTL_IMPORT_SYNC_FILE failed (%s): releases wait for the display's fence here instead",
|
||||
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_IMPORT_SYNC_FILE failed (%s): releases wait for the display's fence here instead",
|
||||
strerror(errno));
|
||||
}
|
||||
/* Wait it out in the event loop (a sync_file is readable once signalled). */
|
||||
@@ -196,23 +200,23 @@ void ahb_swapchain_layer_released(void *token, int release_fd) {
|
||||
/* ---- present */
|
||||
|
||||
int ahb_swapchain_has_ahb(const struct dmabuf_buffer *b) {
|
||||
return b && *banner_dmabuf_ahb_slot((struct dmabuf_buffer *)b) != NULL;
|
||||
return b && *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) != NULL;
|
||||
}
|
||||
|
||||
int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_w, int scene_h) {
|
||||
struct ahb_buf *ab = b ? *banner_dmabuf_ahb_slot(b) : NULL;
|
||||
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL;
|
||||
if (!ab) return -1;
|
||||
int dmabuf_fd = banner_dmabuf_fd(b);
|
||||
int dmabuf_fd = droiddeck_dmabuf_fd(b);
|
||||
/* Acquire fence: the game's render fence, which its driver put into the dma-buf before the
|
||||
* commit (Mesa's implicit sync). The display waits on it, not the CPU. */
|
||||
int acquire = -1;
|
||||
struct banner_dma_buf_sync_file exp = {.flags = BANNER_DMA_BUF_SYNC_READ, .fd = -1};
|
||||
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, BANNER_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
|
||||
struct droiddeck_dma_buf_sync_file exp = {.flags = DROIDDECK_DMA_BUF_SYNC_READ, .fd = -1};
|
||||
if (dmabuf_fd >= 0 && ioctl(dmabuf_fd, DROIDDECK_DMA_BUF_IOCTL_EXPORT_SYNC_FILE, &exp) == 0 && exp.fd >= 0) {
|
||||
acquire = exp.fd;
|
||||
} else if (dmabuf_fd >= 0) {
|
||||
if (!g_export_failed_logged) {
|
||||
g_export_failed_logged = 1;
|
||||
banner_log("layer", "zero-copy: DMA_BUF_IOCTL_EXPORT_SYNC_FILE failed (%s): waiting for each frame on the CPU instead",
|
||||
droiddeck_log("layer", "zero-copy: DMA_BUF_IOCTL_EXPORT_SYNC_FILE failed (%s): waiting for each frame on the CPU instead",
|
||||
strerror(errno));
|
||||
}
|
||||
struct pollfd p = {.fd = dmabuf_fd, .events = POLLIN}; /* readable = the writers are done */
|
||||
@@ -220,7 +224,7 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
|
||||
do { r = poll(&p, 1, 100); } while (r < 0 && errno == EINTR);
|
||||
}
|
||||
int r = sc_layer_present_ahb(ab->ahb, ab->w, ab->h, acquire, (void *)(uintptr_t)ab->id, scene_w, scene_h,
|
||||
s ? banner_surface_color(s) : NULL, ab->format);
|
||||
s ? droiddeck_surface_color(s) : NULL, ab->format);
|
||||
if (r < 0) return -1;
|
||||
if (r == 1) return 0; /* nothing of it on screen: not on the layer, nothing to release later */
|
||||
if (!ab->on_layer) {
|
||||
@@ -231,8 +235,8 @@ int ahb_swapchain_present(struct dmabuf_buffer *b, struct surface *s, int scene_
|
||||
if (s && g_announced != s) {
|
||||
char name[160];
|
||||
g_announced = s;
|
||||
banner_surface_describe(s, name, sizeof(name));
|
||||
banner_log("layer", "zero-copy: presenting %s without a copy", name);
|
||||
droiddeck_surface_describe(s, name, sizeof(name));
|
||||
droiddeck_log("layer", "zero-copy: presenting %s without a copy", name);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -245,7 +249,7 @@ int ahb_swapchain_last_frame_age_ms(void) {
|
||||
}
|
||||
|
||||
int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *buffer, struct surface *s, int paced) {
|
||||
struct ahb_buf *ab = b ? *banner_dmabuf_ahb_slot(b) : NULL;
|
||||
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot(b) : NULL;
|
||||
if (!ab || !ab->on_layer || !buffer || ab->resource != buffer) return 0;
|
||||
ab->release_pending = 1;
|
||||
ab->deferred_ns = now_ns();
|
||||
@@ -268,7 +272,7 @@ unsigned ahb_swapchain_stats_take(void) {
|
||||
int ahb_swapchain_advertised(void) { return g_advertised; }
|
||||
|
||||
uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b) {
|
||||
struct ahb_buf *ab = b ? *banner_dmabuf_ahb_slot((struct dmabuf_buffer *)b) : NULL;
|
||||
struct ahb_buf *ab = b ? *droiddeck_dmabuf_ahb_slot((struct dmabuf_buffer *)b) : NULL;
|
||||
return ab ? ab->format : 0;
|
||||
}
|
||||
|
||||
@@ -279,14 +283,14 @@ static void ahb_destroy(struct wl_client *c, struct wl_resource *r) { wl_resourc
|
||||
static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_resource *buffer, int32_t sock,
|
||||
uint32_t width, uint32_t height, uint32_t stride, uint32_t mod_hi, uint32_t mod_lo,
|
||||
uint32_t image_count) {
|
||||
struct dmabuf_buffer *b = banner_dmabuf_from_resource(buffer);
|
||||
struct dmabuf_buffer *b = droiddeck_dmabuf_from_resource(buffer);
|
||||
uint64_t modifier = ((uint64_t)mod_hi << 32) | mod_lo;
|
||||
if (!b) {
|
||||
banner_log("layer", "zero-copy: %s attached an AHardwareBuffer to a non-dma-buf wl_buffer, ignored", banner_client_name(c));
|
||||
droiddeck_log("layer", "zero-copy: %s attached an AHardwareBuffer to a non-dma-buf wl_buffer, ignored", droiddeck_client_name(c));
|
||||
close(sock);
|
||||
return;
|
||||
}
|
||||
void **slot = banner_dmabuf_ahb_slot(b);
|
||||
void **slot = droiddeck_dmabuf_ahb_slot(b);
|
||||
if (*slot) { close(sock); return; } /* once per buffer */
|
||||
|
||||
/* The handle was written into the socket before the request was sent; a short wait is just
|
||||
@@ -298,17 +302,17 @@ static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_res
|
||||
int rc = pr > 0 ? AHardwareBuffer_recvHandleFromUnixSocket(sock, &ahb) : -1;
|
||||
close(sock);
|
||||
if (rc != 0 || !ahb) {
|
||||
banner_log("layer", "zero-copy: receiving %s's AHardwareBuffer failed (%s)", banner_client_name(c),
|
||||
droiddeck_log("layer", "zero-copy: receiving %s's AHardwareBuffer failed (%s)", droiddeck_client_name(c),
|
||||
pr > 0 ? "recvHandleFromUnixSocket" : "nothing on the socket");
|
||||
return;
|
||||
}
|
||||
AHardwareBuffer_Desc d;
|
||||
AHardwareBuffer_describe(ahb, &d);
|
||||
int bw, bh;
|
||||
banner_dmabuf_size(b, &bw, &bh);
|
||||
droiddeck_dmabuf_size(b, &bw, &bh);
|
||||
if ((int)d.width != bw || (int)d.height != bh || (int)width != bw || (int)height != bh) {
|
||||
banner_log("layer", "zero-copy: %s's AHardwareBuffer is %ux%u but its wl_buffer %dx%d, ignored",
|
||||
banner_client_name(c), d.width, d.height, bw, bh);
|
||||
droiddeck_log("layer", "zero-copy: %s's AHardwareBuffer is %ux%u but its wl_buffer %dx%d, ignored",
|
||||
droiddeck_client_name(c), d.width, d.height, bw, bh);
|
||||
AHardwareBuffer_release(ahb);
|
||||
return;
|
||||
}
|
||||
@@ -317,7 +321,7 @@ static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_res
|
||||
if (!ab) { AHardwareBuffer_release(ahb); wl_client_post_no_memory(c); return; }
|
||||
ab->id = g_next_id++;
|
||||
ab->b = b;
|
||||
banner_dmabuf_ref(b);
|
||||
droiddeck_dmabuf_ref(b);
|
||||
ab->ahb = ahb;
|
||||
ab->w = bw; ab->h = bh;
|
||||
ab->stride = d.stride ? d.stride : stride;
|
||||
@@ -335,8 +339,8 @@ static void ahb_attach(struct wl_client *c, struct wl_resource *r, struct wl_res
|
||||
if (g_last_chain.client != c || g_last_chain.w != bw || g_last_chain.h != bh ||
|
||||
g_last_chain.image_count != image_count || g_last_chain.modifier != modifier || g_last_chain.format != d.format) {
|
||||
g_last_chain = (struct chain_seen){c, bw, bh, image_count, modifier, d.format};
|
||||
banner_log("layer", "zero-copy: AHB swapchain from %s (%u images, %dx%d, %s, %s, stride %u px)", banner_client_name(c),
|
||||
image_count, bw, bh, banner_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)"
|
||||
droiddeck_log("layer", "zero-copy: AHB swapchain from %s (%u images, %dx%d, %s, %s, stride %u px)", droiddeck_client_name(c),
|
||||
image_count, bw, bh, droiddeck_ahb_format_name(d.format), modifier == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)"
|
||||
: modifier == 0 ? "linear" : "unknown modifier", ab->stride);
|
||||
}
|
||||
}
|
||||
@@ -363,7 +367,7 @@ static void bind_ahb(struct wl_client *c, void *data, uint32_t ver, uint32_t id)
|
||||
/* One line per program, not per surface-format query (each binds its own). */
|
||||
if (last_named != c) {
|
||||
last_named = c;
|
||||
banner_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", banner_client_name(c), ver,
|
||||
droiddeck_log("layer", "zero-copy: %s bound banner_ahb_v1 version %u (%s)", droiddeck_client_name(c), ver,
|
||||
ver >= 2 ? "follows the live switch" : "version 1: decides from its launch environment only");
|
||||
}
|
||||
}
|
||||
@@ -372,7 +376,7 @@ void ahb_swapchain_set_mode(int on, int live) {
|
||||
on = on ? 1 : 0;
|
||||
g_zero_copy = on;
|
||||
if (!g_advertised) {
|
||||
if (live) banner_log("layer", "zero-copy switched %s from the drawer, but no display layer is available on this device: no change",
|
||||
if (live) droiddeck_log("layer", "zero-copy switched %s from the drawer, but no display layer is available on this device: no change",
|
||||
on ? "on" : "off");
|
||||
return;
|
||||
}
|
||||
@@ -390,37 +394,37 @@ void ahb_swapchain_set_mode(int on, int live) {
|
||||
memset(&g_last_chain, 0, sizeof(g_last_chain));
|
||||
g_announced = NULL;
|
||||
if (live)
|
||||
banner_log("layer", "zero-copy switched %s from the drawer: %d bound program%s told to rebuild their swapchains%s",
|
||||
droiddeck_log("layer", "zero-copy switched %s from the drawer: %d bound program%s told to rebuild their swapchains%s",
|
||||
on ? "on" : "off", told, told == 1 ? "" : "s",
|
||||
on ? "; frames go on the display layer once the new gralloc swapchain is up"
|
||||
: "; gralloc frames still in flight stay on the layer (or take the copy path) until then");
|
||||
else
|
||||
banner_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
|
||||
on ? "BANNER_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer"
|
||||
droiddeck_log("layer", "zero-copy: %s at launch (%s)", on ? "on" : "off",
|
||||
on ? "DROIDDECK_WAYLAND_ZERO_COPY=1: games present their own gralloc buffers on the display layer"
|
||||
: "the drawer's Zero-copy presentation switch turns it on live");
|
||||
if (live) wl_display_flush_clients(banner_get_display());
|
||||
banner_request_redraw();
|
||||
if (live) wl_display_flush_clients(droiddeck_get_display());
|
||||
droiddeck_request_redraw();
|
||||
}
|
||||
|
||||
void ahb_swapchain_init(struct wl_display *display) {
|
||||
wl_list_init(&g_bufs);
|
||||
wl_list_init(&g_clients);
|
||||
if (!sc_layer_available()) {
|
||||
banner_log("layer", "zero-copy: no display layer on this device (see the line above): banner_ahb_v1 not advertised");
|
||||
droiddeck_log("layer", "zero-copy: no display layer on this device (see the line above): banner_ahb_v1 not advertised");
|
||||
return;
|
||||
}
|
||||
g_loop = wl_display_get_event_loop(display);
|
||||
if (pipe2(g_rel_pipe, O_CLOEXEC | O_NONBLOCK) != 0) {
|
||||
banner_log("error", "zero-copy: release pipe creation failed (%s); zero-copy presents disabled", strerror(errno));
|
||||
droiddeck_log("error", "zero-copy: release pipe creation failed (%s); zero-copy presents disabled", strerror(errno));
|
||||
g_rel_pipe[0] = g_rel_pipe[1] = -1;
|
||||
return;
|
||||
}
|
||||
wl_event_loop_add_fd(g_loop, g_rel_pipe[0], WL_EVENT_READABLE, on_release_pipe, NULL);
|
||||
if (!wl_global_create(display, &banner_ahb_v1_interface, 2, NULL, bind_ahb)) {
|
||||
banner_log("error", "zero-copy: banner_ahb_v1 global creation failed");
|
||||
droiddeck_log("error", "zero-copy: banner_ahb_v1 global creation failed");
|
||||
return;
|
||||
}
|
||||
g_advertised = 1;
|
||||
banner_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)");
|
||||
droiddeck_log("layer", "zero-copy: banner_ahb_v1 version 2 advertised (games built for it present their own gralloc buffers while the switch is on)");
|
||||
ahb_swapchain_set_mode(g_zero_copy, 0);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#ifndef AHB_SWAPCHAIN_H
|
||||
#define AHB_SWAPCHAIN_H
|
||||
/*
|
||||
* Zero-copy game frames (layer mode, BANNER_WAYLAND_ZERO_COPY=1 at launch, the drawer's "Zero-copy
|
||||
* Zero-copy game frames (layer mode, DROIDDECK_WAYLAND_ZERO_COPY=1 at launch, the drawer's "Zero-copy
|
||||
* presentation" switch live): the guest half of the design in ZERO_COPY_SPIKE.md. Our Wayland Turnip
|
||||
* (banners-turnip-wayland, patches/wayland/banner_ahb_wsi.py) binds the private global banner_ahb_v1
|
||||
* (version 2), which this compositor advertises on every session where a display layer is possible,
|
||||
@@ -63,21 +63,21 @@ uint32_t ahb_swapchain_ahb_format(const struct dmabuf_buffer *b);
|
||||
void ahb_swapchain_layer_released(void *token, int release_fd);
|
||||
|
||||
/* ---- ahb_swapchain.c -> compositor.c (hooks) */
|
||||
struct dmabuf_buffer *banner_dmabuf_from_resource(struct wl_resource *buffer);
|
||||
int banner_dmabuf_fd(const struct dmabuf_buffer *b); /* plane 0's dma-buf */
|
||||
void banner_dmabuf_size(const struct dmabuf_buffer *b, int *w, int *h);
|
||||
void **banner_dmabuf_ahb_slot(struct dmabuf_buffer *b); /* this module's per-buffer state */
|
||||
void banner_dmabuf_ref(struct dmabuf_buffer *b);
|
||||
void banner_dmabuf_unref(struct dmabuf_buffer *b);
|
||||
struct dmabuf_buffer *droiddeck_dmabuf_from_resource(struct wl_resource *buffer);
|
||||
int droiddeck_dmabuf_fd(const struct dmabuf_buffer *b); /* plane 0's dma-buf */
|
||||
void droiddeck_dmabuf_size(const struct dmabuf_buffer *b, int *w, int *h);
|
||||
void **droiddeck_dmabuf_ahb_slot(struct dmabuf_buffer *b); /* this module's per-buffer state */
|
||||
void droiddeck_dmabuf_ref(struct dmabuf_buffer *b);
|
||||
void droiddeck_dmabuf_unref(struct dmabuf_buffer *b);
|
||||
/* Give a wl_buffer back to its client now (paced = 0) or on the FPS limiter's cadence (s != NULL).
|
||||
* since_ns = when the compositor let go of it (CLOCK_MONOTONIC; the perf line's release latency). */
|
||||
void banner_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns);
|
||||
void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns);
|
||||
/* Redraw the scene on the next tick (the present path may have changed). */
|
||||
void banner_request_redraw(void);
|
||||
void droiddeck_request_redraw(void);
|
||||
/* "<title>" (program) of the window a surface belongs to, for the log. */
|
||||
void banner_surface_describe(const struct surface *s, char *out, size_t size);
|
||||
/* The surface's current image description (banner_color.h), NULL = none / HDR gate closed. */
|
||||
struct banner_color;
|
||||
const struct banner_color *banner_surface_color(const struct surface *s);
|
||||
void droiddeck_surface_describe(const struct surface *s, char *out, size_t size);
|
||||
/* The surface's current image description (droiddeck_color.h), NULL = none / HDR gate closed. */
|
||||
struct droiddeck_color;
|
||||
const struct droiddeck_color *droiddeck_surface_color(const struct surface *s);
|
||||
|
||||
#endif
|
||||
@@ -1,50 +0,0 @@
|
||||
/*
|
||||
* Interface between compositor.c and the extension modules that live in their own files:
|
||||
* wl_clipboard.c wl_data_device_manager + zwlr_data_control_manager_v1 (selection only)
|
||||
* wl_text_input.c zwp_text_input_manager_v3 (host IME / soft keyboard)
|
||||
* wl_toplevel_icon.c xdg_toplevel_icon_manager_v1 (accepted, not rendered)
|
||||
* banner_ext.c the host→compositor message queue shared by the modules
|
||||
* Everything here runs on the compositor (dispatch) thread unless noted.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <wayland-server.h>
|
||||
|
||||
void banner_log(const char *tag, const char *fmt, ...);
|
||||
|
||||
/* ---- compositor.c → modules */
|
||||
void banner_ext_init(struct wl_display *display); /* creates the globals + host queue */
|
||||
void banner_clipboard_keyboard_focus(struct wl_client *client); /* keyboard focus moved; NULL = none */
|
||||
void banner_text_input_refocus(void); /* the text-input target may have changed */
|
||||
void banner_text_input_surface_gone(struct wl_resource *surface);
|
||||
|
||||
/* ---- modules → compositor.c */
|
||||
const char *banner_client_name(struct wl_client *client);
|
||||
struct wl_display *banner_get_display(void);
|
||||
/* The surface text input follows (the last clicked window, else the topmost program window). */
|
||||
struct wl_resource *banner_ime_target(void);
|
||||
/* Scene (virtual desktop) origin of a toplevel surface; 0,0 when unknown. */
|
||||
void banner_surface_scene_origin(struct wl_resource *surface, int *x, int *y);
|
||||
/* Deliver a key press/release through the wl_keyboard path as if typed. */
|
||||
void banner_inject_key(uint32_t evdev, int pressed);
|
||||
|
||||
/* ---- modules → app (JNI upcalls; waylandcomp_jni.c) */
|
||||
void banner_on_clipboard_text(const char *utf8, int len);
|
||||
void banner_on_text_input(int enabled, const char *program, int x, int y, int w, int h);
|
||||
|
||||
/* ---- app → modules (callable from any thread; queued to the compositor thread) */
|
||||
void banner_host_clipboard_text(const char *utf8, int len); /* len 0 = clear */
|
||||
void banner_host_text_commit(const char *utf8, int len);
|
||||
void banner_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
|
||||
void banner_host_text_delete(int before, int after);
|
||||
void banner_host_zero_copy(int on, int live); /* the drawer's zero-copy switch (ahb_swapchain_set_mode) */
|
||||
void banner_host_hdr_output(int on); /* the drawer's HDR output switch (banner_color_set_output) */
|
||||
|
||||
/* ---- module internals reached through the queue (banner_ext.c → modules) */
|
||||
void clipboard_init(struct wl_display *display);
|
||||
void clipboard_host_text(char *utf8, size_t len); /* takes ownership of utf8 */
|
||||
void text_input_init(struct wl_display *display);
|
||||
void text_input_host_commit(const char *utf8, size_t len);
|
||||
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end);
|
||||
void text_input_host_delete(int before, int after);
|
||||
void toplevel_icon_init(struct wl_display *display);
|
||||
@@ -2,7 +2,7 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "blend_pass.h"
|
||||
#include "vk_loader.h"
|
||||
#include "vk_present.h" /* banner_log, vkp_gpu_name */
|
||||
#include "vk_present.h" /* droiddeck_log, vkp_gpu_name */
|
||||
#include <string.h>
|
||||
|
||||
/* SPIR-V, pre-compiled (glslangValidator -V blend.vert --vn blend_vert_code, the same for blend.frag)
|
||||
@@ -168,12 +168,12 @@ static int objects_ensure(void) {
|
||||
if (!(g_vert = shader(blend_vert_code, sizeof(blend_vert_code)))) goto fail;
|
||||
if (!(g_frag = shader(blend_frag_code, sizeof(blend_frag_code)))) goto fail;
|
||||
g_ready = 1;
|
||||
banner_log("gpu", "alpha composition ready on %s: translucent surfaces are blended over what is under them",
|
||||
droiddeck_log("gpu", "alpha composition ready on %s: translucent surfaces are blended over what is under them",
|
||||
vkp_gpu_name());
|
||||
return 0;
|
||||
fail:
|
||||
objects_destroy();
|
||||
banner_log("error", "gpu: the alpha composition pass could not be built on this driver; translucent surfaces "
|
||||
droiddeck_log("error", "gpu: the alpha composition pass could not be built on this driver; translucent surfaces "
|
||||
"are drawn opaque this session");
|
||||
return -1;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
* What compositor.c shares with the protocol modules split out of it (wl_dmabuf.c): the dma-buf
|
||||
* buffer records, the per-client bookkeeping and the few functions and globals both sides use.
|
||||
* Everything declared here is hidden: it is internal to libbannerwayland, not part of its ABI.
|
||||
* Everything declared here is hidden: it is internal to libdroiddeckwayland, not part of its ABI.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
@@ -13,7 +13,7 @@
|
||||
#define COMPOSITOR_INTERNAL __attribute__((visibility("hidden")))
|
||||
|
||||
#ifndef WLOGE
|
||||
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "BannerWayland", __VA_ARGS__)
|
||||
#define WLOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", __VA_ARGS__)
|
||||
#endif
|
||||
|
||||
/* ------------------------------------------------------------------ dmabuf buffers */
|
||||
@@ -71,9 +71,12 @@ struct client_info {
|
||||
COMPOSITOR_INTERNAL struct client_info *client_info_of(struct wl_client *client);
|
||||
COMPOSITOR_INTERNAL void dmabuf_buffer_unref(struct dmabuf_buffer *b);
|
||||
COMPOSITOR_INTERNAL extern const struct wl_buffer_interface dbuf_buffer_impl;
|
||||
extern volatile int g_ubwc; /* BANNER_WAYLAND_UBWC (waylandcomp_jni.c sets it) */
|
||||
extern volatile int g_no_render_node; /* BANNER_WAYLAND_NO_RENDER_NODE */
|
||||
extern volatile int g_ubwc; /* DROIDDECK_WAYLAND_UBWC (waylandcomp_jni.c sets it) */
|
||||
extern volatile int g_no_render_node; /* DROIDDECK_WAYLAND_NO_RENDER_NODE */
|
||||
|
||||
/* ---- wl_dmabuf.c */
|
||||
COMPOSITOR_INTERNAL extern dev_t g_main_device; /* the render node clients are told to allocate on */
|
||||
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);
|
||||
+47
-47
@@ -1,5 +1,5 @@
|
||||
#ifndef BANNER_COLOR_H
|
||||
#define BANNER_COLOR_H
|
||||
#ifndef DROIDDECK_COLOR_H
|
||||
#define DROIDDECK_COLOR_H
|
||||
/*
|
||||
* HDR10 output on the Wayland backend (opt-in) - the compositor half of HDR_RECON.md Phase A (round 1)
|
||||
* plus HDR-aware composition (round 2, hdr_compose.h), implemented in wl_color_mgmt.c. The game half
|
||||
@@ -8,18 +8,18 @@
|
||||
* with DXVK_HDR=1 (the app exports it when the setting is on).
|
||||
*
|
||||
* THE GATE. Nothing here exists for a session unless all of these hold when the compositor starts:
|
||||
* - the container's / game's "HDR output" setting is on, or BANNER_WAYLAND_HDR=1 in their
|
||||
* - the container's / game's "HDR output" setting is on, or DROIDDECK_WAYLAND_HDR=1 in their
|
||||
* environment (which overrides the setting either way);
|
||||
* - the display the game is on lists HDR10 among its supported HDR types (read by the app from
|
||||
* android.view.Display - a property of the connector, not of the device);
|
||||
* - display layers with dataspace control (ASurfaceTransaction_setBufferDataSpace, Android 10+)
|
||||
* and the zero-copy global (banner_ahb_v1): the HDR frame (or the composed HDR picture) is shown
|
||||
* on the game's own display layer, tagged BT2020_PQ.
|
||||
* In game, the drawer's HDR output switch (banner_color_set_output) flips between that and the same
|
||||
* In game, the drawer's HDR output switch (droiddeck_color_set_output) flips between that and the same
|
||||
* frames tone-mapped to SDR, live; the gate itself never changes during a session.
|
||||
* A closed gate advertises nothing - no colour-management global, no 10-bit dma-buf formats - so the
|
||||
* session is byte-for-byte what it was before this file existed, and the session log says why.
|
||||
* BANNER_WAYLAND_HDR=force skips the display check only (testing the negotiation on an SDR panel;
|
||||
* DROIDDECK_WAYLAND_HDR=force skips the display check only (testing the negotiation on an SDR panel;
|
||||
* SurfaceFlinger then tone-maps the layer, and says so in its composition type).
|
||||
*
|
||||
* WHAT AN OPEN GATE OFFERS (exactly the subset Mesa binds, HDR_RECON.md §2.2): wp_color_manager_v1
|
||||
@@ -35,13 +35,13 @@
|
||||
#include <wayland-server.h>
|
||||
|
||||
/* ADataSpace values (NDK <android/data_space.h>) the layer path emits. */
|
||||
#define BANNER_ADATASPACE_UNKNOWN 0
|
||||
#define BANNER_ADATASPACE_BT2020_PQ 163971072 /* STANDARD_BT2020 | TRANSFER_ST2084 | RANGE_FULL = 0x09c60000 */
|
||||
#define BANNER_ADATASPACE_BT2020_HLG 168165376 /* STANDARD_BT2020 | TRANSFER_HLG | RANGE_FULL */
|
||||
#define DROIDDECK_ADATASPACE_UNKNOWN 0
|
||||
#define DROIDDECK_ADATASPACE_BT2020_PQ 163971072 /* STANDARD_BT2020 | TRANSFER_ST2084 | RANGE_FULL = 0x09c60000 */
|
||||
#define DROIDDECK_ADATASPACE_BT2020_HLG 168165376 /* STANDARD_BT2020 | TRANSFER_HLG | RANGE_FULL */
|
||||
|
||||
/* One image description as the program made it, and what it becomes on a display layer. Immutable:
|
||||
* a changed description is a new record with a new identity. */
|
||||
struct banner_color {
|
||||
struct droiddeck_color {
|
||||
uint32_t identity; /* the id the `ready` event carried (never 0) */
|
||||
uint32_t primaries, tf; /* wp_color_manager_v1 named values */
|
||||
int32_t dataspace; /* ADataSpace on a display layer; 0 = none (treated as sRGB) */
|
||||
@@ -54,97 +54,97 @@ struct banner_color {
|
||||
};
|
||||
|
||||
/* ---- app -> compositor (JNI, any thread) */
|
||||
/* mode 0 = off, 1 = BANNER_WAYLAND_HDR=1, 2 = BANNER_WAYLAND_HDR=force (testing). source names where
|
||||
/* mode 0 = off, 1 = DROIDDECK_WAYLAND_HDR=1, 2 = DROIDDECK_WAYLAND_HDR=force (testing). source names where
|
||||
* the switch came from; dxvk_hdr = DXVK_HDR=1 is in the game's environment; zero_copy_forced = the
|
||||
* app turned zero-copy presentation on for this session because HDR needs it. Before the start. */
|
||||
void banner_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced);
|
||||
void droiddeck_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced);
|
||||
/* The display the game is on, as android.view.Display reports it. Before the start (it feeds the
|
||||
* gate) and again whenever it changes (logged; the gate is decided once per session). */
|
||||
void banner_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum,
|
||||
void droiddeck_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum,
|
||||
float max_avg, float min_lum, int ratio_available, float ratio, int api);
|
||||
/* One reading of Display.getHdrSdrRatio() (API 34+; < 0 = not available). listener = it came from
|
||||
* the display's ratio listener rather than the app's periodic sampler. */
|
||||
void banner_color_ratio_sample(float ratio, int listener);
|
||||
void droiddeck_color_ratio_sample(float ratio, int listener);
|
||||
/* Milliseconds since an HDR frame last went onto a display layer; -1 = none this session. */
|
||||
int banner_color_last_frame_age_ms(void);
|
||||
int droiddeck_color_last_frame_age_ms(void);
|
||||
/* -1 = the compositor has not decided yet, 0 = closed, 1 = open. */
|
||||
int banner_color_gate_state(void);
|
||||
int droiddeck_color_gate_state(void);
|
||||
/* The session is ending: write the summary line ("HDR on screen: …"). */
|
||||
void banner_color_session_end(void);
|
||||
void droiddeck_color_session_end(void);
|
||||
/* 1 while HDR frames are really on screen: a frame tagged BT2020_PQ reached a display layer or the HDR
|
||||
* swapchain in the last 1.5 s AND, where the display reports an HDR/SDR ratio, its last reading is
|
||||
* above 1.01 (the HUD badge). */
|
||||
int banner_color_hdr_on_screen(void);
|
||||
int droiddeck_color_hdr_on_screen(void);
|
||||
/* The HUD / drawer state: 0 = no HDR frames on screen (or not confirmed yet), 1 = HDR frames on screen
|
||||
* with headroom (as banner_color_hdr_on_screen), 2 = HDR frames on screen but the display has given
|
||||
* with headroom (as droiddeck_color_hdr_on_screen), 2 = HDR frames on screen but the display has given
|
||||
* them NO headroom (ratio <= 1.01) for 5 s or more - the brightness slider at maximum, or a screen
|
||||
* recording (Android turns HDR headroom off while the screen is recorded). */
|
||||
int banner_color_hdr_state(void);
|
||||
int droiddeck_color_hdr_state(void);
|
||||
/* Nits SDR content is placed at inside an HDR picture (default 203, BT.2408); any thread. */
|
||||
void banner_color_set_sdr_white(float nits);
|
||||
float banner_color_sdr_white(void);
|
||||
/* The HDR session was asked for (BANNER_WAYLAND_HDR / the setting resolved on or force) - known before
|
||||
void droiddeck_color_set_sdr_white(float nits);
|
||||
float droiddeck_color_sdr_white(void);
|
||||
/* The HDR session was asked for (DROIDDECK_WAYLAND_HDR / the setting resolved on or force) - known before
|
||||
* the compositor starts, so the Vulkan instance can enable VK_EXT_swapchain_colorspace for it. */
|
||||
int banner_color_requested(void);
|
||||
int droiddeck_color_requested(void);
|
||||
/* The drawer's live "HDR output" switch, per session, starting ON. On = HDR frames go to the display as
|
||||
* HDR; off = the SAME frames are composed tone-mapped to SDR (hdr_compose.h) - the game is told nothing
|
||||
* and keeps rendering HDR (DXVK_HDR and the colour-manager offer were decided at launch). Compositor
|
||||
* thread (the app posts it through banner_host_hdr_output); logs the flip and redraws. */
|
||||
void banner_color_set_output(int on);
|
||||
* thread (the app posts it through droiddeck_host_hdr_output); logs the flip and redraws. */
|
||||
void droiddeck_color_set_output(int on);
|
||||
/* 1 = HDR output on (any thread). */
|
||||
int banner_color_output(void);
|
||||
int droiddeck_color_output(void);
|
||||
/* 1 while an HDR game's frames are being shown tone-mapped to SDR (the last one < 1.5 s ago); any thread. */
|
||||
int banner_color_tonemapped_on_screen(void);
|
||||
int droiddeck_color_tonemapped_on_screen(void);
|
||||
/* Device evidence beside the HDR/SDR headroom (the app, non-root APIs; any thread; HDR sessions only):
|
||||
* PowerManager thermal status (0..6, -1 unknown) + getThermalHeadroom(10) (< 0 = not available),
|
||||
* Settings.System SCREEN_BRIGHTNESS (0..255, -1 unknown) + SCREEN_BRIGHTNESS_MODE (1 auto, 0 manual).
|
||||
* Changes of status and brightness are logged; every no-headroom line, the 10 s line and the verdict
|
||||
* carry the last values. */
|
||||
void banner_color_env_sample(int thermal, float headroom, int brightness, int bmode);
|
||||
void droiddeck_color_env_sample(int thermal, float headroom, int brightness, int bmode);
|
||||
|
||||
/* ---- the explicit HDR headroom request (Android 15+: ASurfaceTransaction_setDesiredHdrHeadroom on the game
|
||||
* layer, SurfaceView.setDesiredHdrHeadroom on the screen surface). Some phones only boost HDR when asked. */
|
||||
/* The ratio to ask for an HDR frame of `c`: content peak (max CLL, else mastering max, else the display's
|
||||
* peak) / SDR white (203), capped at the display's highest ratio when it reports one; 0 = ask nothing
|
||||
* (not HDR, or the display reports it cannot boost). `why` gets the one-line reason. Any thread. */
|
||||
float banner_color_desired_headroom(const struct banner_color *c, char *why, size_t n);
|
||||
float droiddeck_color_desired_headroom(const struct droiddeck_color *c, char *why, size_t n);
|
||||
/* What was last asked for (> 0 the ratio, 0 nothing, -1 the API is missing): for the no-headroom lines. */
|
||||
void banner_color_note_headroom_request(float ratio);
|
||||
void droiddeck_color_note_headroom_request(float ratio);
|
||||
/* Display.getHighestHdrSdrRatio() (Android 16+; <= 0 = not reported). Any thread; logged when it arrives. */
|
||||
void banner_color_set_highest_ratio(float ratio);
|
||||
void droiddeck_color_set_highest_ratio(float ratio);
|
||||
/* The headroom the SCREEN surface should ask for (frames through the HDR10 swapchain in the last 1.5 s),
|
||||
* 0 = none; `why` gets the reason. The app polls it and applies it. Any thread. */
|
||||
float banner_color_screen_headroom(char *why, size_t n);
|
||||
float droiddeck_color_screen_headroom(char *why, size_t n);
|
||||
|
||||
/* ---- compositor.c -> here */
|
||||
/* Decide the gate (call after ahb_swapchain_init) and create the global when it is open. */
|
||||
void banner_color_init(struct wl_display *display);
|
||||
void droiddeck_color_init(struct wl_display *display);
|
||||
/* The gate is open: the 10-bit dma-buf formats may be advertised, descriptions may exist. */
|
||||
int banner_color_hdr_open(void);
|
||||
int droiddeck_color_hdr_open(void);
|
||||
/* wl_surface.commit: the pending image description (if any request touched it) becomes current. */
|
||||
void banner_color_commit(struct wl_resource *surface);
|
||||
void droiddeck_color_commit(struct wl_resource *surface);
|
||||
/* The surface's current image description; NULL = none (sRGB, today's default). */
|
||||
const struct banner_color *banner_color_of(struct wl_resource *surface);
|
||||
const struct droiddeck_color *droiddeck_color_of(struct wl_resource *surface);
|
||||
/* A program disconnected: if it presented HDR, its part of the summary is written now. */
|
||||
void banner_color_client_gone(struct wl_client *client);
|
||||
void droiddeck_color_client_gone(struct wl_client *client);
|
||||
/* The 10 s summary tick (one `color` line when anything HDR happened in the window). */
|
||||
void banner_color_stats_tick(void);
|
||||
void droiddeck_color_stats_tick(void);
|
||||
/* A frame of an HDR-described surface went through the compositor's own 8-bit sRGB pass this scene
|
||||
* (who = the window, reason = why it did not get the display layer). Shown untone-mapped. */
|
||||
void banner_color_frame_copied(const char *who, const char *reason);
|
||||
void droiddeck_color_frame_copied(const char *who, const char *reason);
|
||||
|
||||
/* ---- sc_layer.c / compositor.c -> here: a NEW frame of an HDR-described surface was shown, and how */
|
||||
enum banner_hdr_path {
|
||||
BANNER_HDR_ZERO_COPY = 0, /* the game's own gralloc buffer on its display layer, tagged */
|
||||
BANNER_HDR_LAYER_COPY, /* one 8-bit copy of the game's frame on its layer, tagged */
|
||||
BANNER_HDR_COMPOSED, /* the whole scene composed into one PQ picture on the game layer (hdr_compose.h) */
|
||||
BANNER_HDR_SWAPCHAIN, /* composed into PQ and presented through an HDR10 swapchain (frame generation) */
|
||||
BANNER_HDR_TONEMAPPED, /* composed and tone-mapped to SDR (HDR output switched off, or a present that
|
||||
enum droiddeck_hdr_path {
|
||||
DROIDDECK_HDR_ZERO_COPY = 0, /* the game's own gralloc buffer on its display layer, tagged */
|
||||
DROIDDECK_HDR_LAYER_COPY, /* one 8-bit copy of the game's frame on its layer, tagged */
|
||||
DROIDDECK_HDR_COMPOSED, /* the whole scene composed into one PQ picture on the game layer (hdr_compose.h) */
|
||||
DROIDDECK_HDR_SWAPCHAIN, /* composed into PQ and presented through an HDR10 swapchain (frame generation) */
|
||||
DROIDDECK_HDR_TONEMAPPED, /* composed and tone-mapped to SDR (HDR output switched off, or a present that
|
||||
* cannot carry HDR) - NOT HDR */
|
||||
};
|
||||
/* ahb_format = the buffer's AHARDWAREBUFFER_FORMAT_* where one exists (0 otherwise). */
|
||||
void banner_color_frame_shown(const struct banner_color *c, int path, uint32_t ahb_format);
|
||||
void droiddeck_color_frame_shown(const struct droiddeck_color *c, int path, uint32_t ahb_format);
|
||||
/* "RGBA1010102 (10-bit)" etc. for an AHARDWAREBUFFER_FORMAT_* value (static buffer). */
|
||||
const char *banner_ahb_format_name(uint32_t format);
|
||||
const char *droiddeck_ahb_format_name(uint32_t format);
|
||||
|
||||
#endif
|
||||
+14
-13
@@ -2,7 +2,7 @@
|
||||
* Host → compositor message queue plus the init of the extension modules.
|
||||
*
|
||||
* The app's threads (UI thread, clipboard listener) hand text to the compositor through
|
||||
* banner_host_* ; the messages are queued under a mutex and a pipe byte wakes the wl event
|
||||
* droiddeck_host_* ; the messages are queued under a mutex and a pipe byte wakes the wl event
|
||||
* loop, which drains them on the compositor thread - the only thread that may touch
|
||||
* wl_resources.
|
||||
*/
|
||||
@@ -13,9 +13,9 @@
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <android/log.h>
|
||||
#include "banner_ext.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "banner_color.h"
|
||||
#include "droiddeck_color.h"
|
||||
|
||||
enum host_kind { HOST_CLIPBOARD = 1, HOST_TEXT_COMMIT, HOST_TEXT_PREEDIT, HOST_TEXT_DELETE, HOST_ZERO_COPY, HOST_HDR_OUTPUT };
|
||||
|
||||
@@ -53,22 +53,22 @@ static void host_post(enum host_kind kind, const char *text, size_t len, int a,
|
||||
}
|
||||
}
|
||||
|
||||
void banner_host_clipboard_text(const char *utf8, int len) {
|
||||
void droiddeck_host_clipboard_text(const char *utf8, int len) {
|
||||
host_post(HOST_CLIPBOARD, utf8, len > 0 ? (size_t)len : 0, 0, 0);
|
||||
}
|
||||
void banner_host_text_commit(const char *utf8, int len) {
|
||||
void droiddeck_host_text_commit(const char *utf8, int len) {
|
||||
host_post(HOST_TEXT_COMMIT, utf8, len > 0 ? (size_t)len : 0, 0, 0);
|
||||
}
|
||||
void banner_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end) {
|
||||
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end) {
|
||||
host_post(HOST_TEXT_PREEDIT, utf8, len > 0 ? (size_t)len : 0, cursor_begin, cursor_end);
|
||||
}
|
||||
void banner_host_text_delete(int before, int after) {
|
||||
void droiddeck_host_text_delete(int before, int after) {
|
||||
host_post(HOST_TEXT_DELETE, NULL, 0, before, after);
|
||||
}
|
||||
void banner_host_zero_copy(int on, int live) {
|
||||
void droiddeck_host_zero_copy(int on, int live) {
|
||||
host_post(HOST_ZERO_COPY, NULL, 0, on, live);
|
||||
}
|
||||
void banner_host_hdr_output(int on) {
|
||||
void droiddeck_host_hdr_output(int on) {
|
||||
host_post(HOST_HDR_OUTPUT, NULL, 0, on, 0);
|
||||
}
|
||||
|
||||
@@ -99,17 +99,17 @@ static int on_wake(int fd, uint32_t mask, void *data) {
|
||||
ahb_swapchain_set_mode(m->a, m->b);
|
||||
break;
|
||||
case HOST_HDR_OUTPUT:
|
||||
banner_color_set_output(m->a);
|
||||
droiddeck_color_set_output(m->a);
|
||||
break;
|
||||
}
|
||||
free(m->text);
|
||||
free(m);
|
||||
}
|
||||
wl_display_flush_clients(banner_get_display());
|
||||
wl_display_flush_clients(droiddeck_get_display());
|
||||
return 0;
|
||||
}
|
||||
|
||||
void banner_ext_init(struct wl_display *display) {
|
||||
void droiddeck_ext_init(struct wl_display *display) {
|
||||
struct wl_event_loop *loop = wl_display_get_event_loop(display);
|
||||
if (pipe2(g_wake, O_CLOEXEC | O_NONBLOCK) == 0) {
|
||||
wl_event_loop_add_fd(loop, g_wake[0], WL_EVENT_READABLE, on_wake, NULL);
|
||||
@@ -118,8 +118,9 @@ void banner_ext_init(struct wl_display *display) {
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (queued) { char c = 1; ssize_t n = write(g_wake[1], &c, 1); (void)n; }
|
||||
} else
|
||||
__android_log_print(ANDROID_LOG_ERROR, "BannerWayland", "host queue pipe failed");
|
||||
__android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "host queue pipe failed");
|
||||
clipboard_init(display);
|
||||
text_input_init(display);
|
||||
toplevel_icon_init(display);
|
||||
single_pixel_init(display);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Interface between compositor.c and the extension modules that live in their own files:
|
||||
* wl_clipboard.c wl_data_device_manager + zwlr_data_control_manager_v1 (selection only)
|
||||
* wl_text_input.c zwp_text_input_manager_v3 (host IME / soft keyboard)
|
||||
* wl_toplevel_icon.c xdg_toplevel_icon_manager_v1 (accepted, not rendered)
|
||||
* droiddeck_ext.c the host→compositor message queue shared by the modules
|
||||
* Everything here runs on the compositor (dispatch) thread unless noted.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <wayland-server.h>
|
||||
|
||||
void droiddeck_log(const char *tag, const char *fmt, ...);
|
||||
|
||||
/* ---- compositor.c → modules */
|
||||
void droiddeck_ext_init(struct wl_display *display); /* creates the globals + host queue */
|
||||
void droiddeck_clipboard_keyboard_focus(struct wl_client *client); /* keyboard focus moved; NULL = none */
|
||||
void droiddeck_text_input_refocus(void); /* the text-input target may have changed */
|
||||
void droiddeck_text_input_surface_gone(struct wl_resource *surface);
|
||||
|
||||
/* ---- modules → compositor.c */
|
||||
const char *droiddeck_client_name(struct wl_client *client);
|
||||
struct wl_display *droiddeck_get_display(void);
|
||||
/* The surface text input follows (the last clicked window, else the topmost program window). */
|
||||
struct wl_resource *droiddeck_ime_target(void);
|
||||
/* Scene (virtual desktop) origin of a toplevel surface; 0,0 when unknown. */
|
||||
void droiddeck_surface_scene_origin(struct wl_resource *surface, int *x, int *y);
|
||||
/* Deliver a key press/release through the wl_keyboard path as if typed. */
|
||||
void droiddeck_inject_key(uint32_t evdev, int pressed);
|
||||
|
||||
/* ---- modules → app (JNI upcalls; waylandcomp_jni.c) */
|
||||
void droiddeck_on_clipboard_text(const char *utf8, int len);
|
||||
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h);
|
||||
|
||||
/* ---- app → modules (callable from any thread; queued to the compositor thread) */
|
||||
void droiddeck_host_clipboard_text(const char *utf8, int len); /* len 0 = clear */
|
||||
void droiddeck_host_text_commit(const char *utf8, int len);
|
||||
void droiddeck_host_text_preedit(const char *utf8, int len, int cursor_begin, int cursor_end);
|
||||
void droiddeck_host_text_delete(int before, int after);
|
||||
void droiddeck_host_zero_copy(int on, int live); /* the drawer's zero-copy switch (ahb_swapchain_set_mode) */
|
||||
void droiddeck_host_hdr_output(int on); /* the drawer's HDR output switch (droiddeck_color_set_output) */
|
||||
|
||||
/* ---- module internals reached through the queue (droiddeck_ext.c → modules) */
|
||||
void clipboard_init(struct wl_display *display);
|
||||
void clipboard_host_text(char *utf8, size_t len); /* takes ownership of utf8 */
|
||||
void text_input_init(struct wl_display *display);
|
||||
void text_input_host_commit(const char *utf8, size_t len);
|
||||
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end);
|
||||
void text_input_host_delete(int before, int after);
|
||||
void toplevel_icon_init(struct wl_display *display);
|
||||
void single_pixel_init(struct wl_display *display);
|
||||
/* A wp_single_pixel_buffer_manager_v1 buffer: 1 and its pixel (B, G, R, A, premultiplied), else 0. */
|
||||
int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]);
|
||||
@@ -2,7 +2,7 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "effects_chain.h"
|
||||
#include "vk_loader.h"
|
||||
#include "vk_present.h" /* banner_log */
|
||||
#include "vk_present.h" /* droiddeck_log */
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -115,7 +115,7 @@ static void log_settings(const struct fx_settings *s) {
|
||||
char line[400];
|
||||
int n;
|
||||
if (!spatial_mode(s->scaling) && !effect_count(s)) {
|
||||
banner_log("effects", "all off: scaling=%s (plain blit)", scaling_name(s->scaling));
|
||||
droiddeck_log("effects", "all off: scaling=%s (plain blit)", scaling_name(s->scaling));
|
||||
return;
|
||||
}
|
||||
n = snprintf(line, sizeof(line), "scaling=%s", scaling_name(s->scaling));
|
||||
@@ -133,7 +133,7 @@ static void log_settings(const struct fx_settings *s) {
|
||||
if (s->crt) n += snprintf(line + n, sizeof(line) - n, ", CRT on");
|
||||
if (s->deband_on) n += snprintf(line + n, sizeof(line) - n, ", Deband on %d%%", s->deband_pct);
|
||||
(void)n;
|
||||
banner_log("effects", "%s", line);
|
||||
droiddeck_log("effects", "%s", line);
|
||||
}
|
||||
|
||||
int vkp_effects_sync(void) {
|
||||
@@ -255,14 +255,18 @@ static void target_destroy(struct fx_target *t) {
|
||||
static int target_ensure(struct fx_target *t, int w, int h, const char *what) {
|
||||
if (t->img && t->w == w && t->h == h) return 0;
|
||||
target_destroy(t);
|
||||
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
|
||||
/* Unrestricted mutable views keep these render-then-blit targets uncompressed on Turnip.
|
||||
* UBWC targets corrupt even a constant-colour pass on Adreno 740 (FSR becomes black).
|
||||
* Only the chain's intermediate images need this; the scene and guest images stay unchanged. */
|
||||
VkImageCreateInfo ii = {.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
|
||||
.flags = VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT, .imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = g_fx_fmt, .extent = {(uint32_t)w, (uint32_t)h, 1}, .mipLevels = 1,
|
||||
.arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
|
||||
VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
VkResult r = g_vk.CreateImage(g_dev, &ii, NULL, &t->img);
|
||||
if (r != VK_SUCCESS) { banner_log("error", "effects: %s image %dx%d: vkCreateImage %d", what, w, h, (int)r); return -1; }
|
||||
if (r != VK_SUCCESS) { droiddeck_log("error", "effects: %s image %dx%d: vkCreateImage %d", what, w, h, (int)r); return -1; }
|
||||
VkMemoryRequirements req;
|
||||
g_vk.GetImageMemoryRequirements(g_dev, t->img, &req);
|
||||
int idx = memtype(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
@@ -271,7 +275,7 @@ static int target_ensure(struct fx_target *t, int w, int h, const char *what) {
|
||||
.memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
|
||||
r = g_vk.AllocateMemory(g_dev, &mai, NULL, &t->mem);
|
||||
if (r != VK_SUCCESS) {
|
||||
banner_log("error", "effects: %s image %dx%d (%llu bytes): vkAllocateMemory %d", what, w, h,
|
||||
droiddeck_log("error", "effects: %s image %dx%d (%llu bytes): vkAllocateMemory %d", what, w, h,
|
||||
(unsigned long long)req.size, (int)r);
|
||||
target_destroy(t); return -1;
|
||||
}
|
||||
@@ -292,6 +296,10 @@ static void scene_release(void) {
|
||||
memset(&g_scene, 0, sizeof(g_scene));
|
||||
}
|
||||
|
||||
void vkp_effects_forget_image(VkImage img) {
|
||||
if (img && g_scene.img == img) scene_release();
|
||||
}
|
||||
|
||||
static int scene_ensure(VkImage img, int w, int h) {
|
||||
if (g_scene.img == img && g_scene.w == w && g_scene.h == h && g_scene.ds) return 0;
|
||||
scene_release();
|
||||
@@ -312,7 +320,7 @@ static VkShaderModule shader(const uint32_t *code, size_t size) {
|
||||
* viewport/scissor - the X11 renderer's createPostPipeline. */
|
||||
static VkPipeline post_pipeline(VkShaderModule vert, const uint32_t *frag_code, size_t frag_size, const char *name) {
|
||||
VkShaderModule frag = shader(frag_code, frag_size);
|
||||
if (!frag) { banner_log("error", "effects: %s: vkCreateShaderModule failed", name); return VK_NULL_HANDLE; }
|
||||
if (!frag) { droiddeck_log("error", "effects: %s: vkCreateShaderModule failed", name); return VK_NULL_HANDLE; }
|
||||
VkPipelineShaderStageCreateInfo st[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT, .module = vert, .pName = "main"},
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT, .module = frag, .pName = "main"}};
|
||||
@@ -340,7 +348,7 @@ static VkPipeline post_pipeline(VkShaderModule vert, const uint32_t *frag_code,
|
||||
VkPipeline p = VK_NULL_HANDLE;
|
||||
VkResult r = g_vk.CreateGraphicsPipelines(g_dev, VK_NULL_HANDLE, 1, &pi, NULL, &p);
|
||||
g_vk.DestroyShaderModule(g_dev, frag, NULL);
|
||||
if (r != VK_SUCCESS) { banner_log("error", "effects: %s: vkCreateGraphicsPipelines %d", name, (int)r); return VK_NULL_HANDLE; }
|
||||
if (r != VK_SUCCESS) { droiddeck_log("error", "effects: %s: vkCreateGraphicsPipelines %d", name, (int)r); return VK_NULL_HANDLE; }
|
||||
return p;
|
||||
}
|
||||
|
||||
@@ -367,7 +375,7 @@ void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt) {
|
||||
g_fx_fmt = target_fmt;
|
||||
g_scene_fmt = scene_fmt;
|
||||
if (g_dev)
|
||||
banner_log("effects", "chain now works in %s (%s)",
|
||||
droiddeck_log("effects", "chain now works in %s (%s)",
|
||||
target_fmt == FX_FORMAT ? "8-bit RGBA"
|
||||
: target_fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? "FP16 RGBA" : "10-bit RGB",
|
||||
target_fmt == FX_FORMAT ? "SDR frames"
|
||||
@@ -383,7 +391,7 @@ void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt) {
|
||||
* unavailable for this session (logged once; frames fall back to the plain blit). */
|
||||
static int objects_ensure(void) {
|
||||
if (g_ready) return g_ready == 1 ? 0 : -1;
|
||||
if (!g_dev || !g_vk.CreateGraphicsPipelines) { g_ready = -1; banner_log("error", "effects: no device for the chain"); return -1; }
|
||||
if (!g_dev || !g_vk.CreateGraphicsPipelines) { g_ready = -1; droiddeck_log("error", "effects: no device for the chain"); return -1; }
|
||||
/* Render pass: one colour target, overwritten whole (DONT_CARE), left SHADER_READ_ONLY for the
|
||||
* next pass. The dependencies order this pass after whoever read the target last (previous
|
||||
* pass / previous frame's blit) and before whoever samples or blits it next. */
|
||||
@@ -448,12 +456,12 @@ static int objects_ensure(void) {
|
||||
#undef MK
|
||||
g_vk.DestroyShaderModule(g_dev, vert, NULL);
|
||||
g_ready = 1;
|
||||
banner_log("effects", "chain ready: 13 passes (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, Toon, HDR, NTSC, CRT, deband) on %s", vkp_gpu_name());
|
||||
droiddeck_log("effects", "chain ready: 13 passes (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, Toon, HDR, NTSC, CRT, deband) on %s", vkp_gpu_name());
|
||||
return 0;
|
||||
fail:
|
||||
objects_destroy();
|
||||
g_ready = -1;
|
||||
banner_log("error", "effects: the screen-effect chain could not be built on this driver; effects are off for this session");
|
||||
droiddeck_log("error", "effects: the screen-effect chain could not be built on this driver; effects are off for this session");
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
|
||||
/* Compositor thread: drop every Vulkan object (device teardown / device lost). */
|
||||
void vkp_effects_destroy(void);
|
||||
|
||||
/* Compositor thread: release the cached source view/descriptor before its owner destroys img.
|
||||
* A later image can reuse the same Vulkan handle and dimensions; that is not the same resource. */
|
||||
void vkp_effects_forget_image(VkImage img);
|
||||
|
||||
/* Compositor thread, before vkp_effects_run(): the format of the scene image it will be handed and the
|
||||
* format its own targets use. R8G8B8A8 / R8G8B8A8 for every SDR frame (the default); A2B10G10R10 /
|
||||
* A2B10G10R10 while an HDR picture runs through it (hdr_compose.h). A target-format change rebuilds the
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
#include <time.h>
|
||||
#include <android/log.h>
|
||||
|
||||
void banner_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
|
||||
#define FGLOG(...) banner_log("framegen", __VA_ARGS__)
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "BannerWayland", __VA_ARGS__)
|
||||
void droiddeck_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
|
||||
#define FGLOG(...) droiddeck_log("framegen", __VA_ARGS__)
|
||||
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "DroidDeckWayland", __VA_ARGS__)
|
||||
|
||||
/* ---- app controls (written from any thread, read on the compositor thread) ------------- */
|
||||
static _Atomic int g_kind = VKP_FG_ENGINE_LSFG;
|
||||
|
||||
@@ -20,8 +20,8 @@
|
||||
#include "lsfg/lsfg_vkd.h"
|
||||
#include "winfg/winfg_engine.h"
|
||||
|
||||
#define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "BannerWayland", "framegen: " __VA_ARGS__)
|
||||
#define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "BannerWayland", "framegen: " __VA_ARGS__)
|
||||
#define ELOG(...) __android_log_print(ANDROID_LOG_INFO, "DroidDeckWayland", "framegen: " __VA_ARGS__)
|
||||
#define ELOGE(...) __android_log_print(ANDROID_LOG_ERROR, "DroidDeckWayland", "framegen: " __VA_ARGS__)
|
||||
|
||||
namespace {
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "hdr_compose.h"
|
||||
#include "vk_loader.h"
|
||||
#include "vk_present.h" /* banner_log, vkp_gpu_name */
|
||||
#include "vk_present.h" /* droiddeck_log, vkp_gpu_name */
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
@@ -190,7 +190,7 @@ static int objects_ensure(void) {
|
||||
if (!(g_out[i].pipe = make_pipe(g_out[i].rp))) goto fail;
|
||||
}
|
||||
g_ready = 1;
|
||||
banner_log("color", "HDR composition ready on %s: scenes that mix HDR and SDR content are put into one "
|
||||
droiddeck_log("color", "HDR composition ready on %s: scenes that mix HDR and SDR content are put into one "
|
||||
"encoding (PQ BT.2020, or tone-mapped sRGB) instead of being shown washed out", vkp_gpu_name());
|
||||
return 0;
|
||||
fail:
|
||||
@@ -200,7 +200,7 @@ fail:
|
||||
g_dev = keep;
|
||||
}
|
||||
g_ready = -1;
|
||||
banner_log("error", "color: the HDR composition pass could not be built on this driver; HDR scenes that cannot "
|
||||
droiddeck_log("error", "color: the HDR composition pass could not be built on this driver; HDR scenes that cannot "
|
||||
"stay on the game's own layer are shown the old way (washed out) this session");
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#define _GNU_SOURCE
|
||||
#include "sc_layer.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "banner_color.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "vk_present.h"
|
||||
#include <android/hardware_buffer.h>
|
||||
#include <android/native_window.h>
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
/* The gralloc buffer handle behind an AHardwareBuffer (AOSP cutils/native_handle.h, which the NDK
|
||||
* does not ship; the layout is a stable ABI: fds first, then ints). */
|
||||
struct banner_native_handle { int version; int numFds; int numInts; int data[]; };
|
||||
struct droiddeck_native_handle { int version; int numFds; int numInts; int data[]; };
|
||||
|
||||
/* ---- libandroid SurfaceControl API (dlsym) ---------------------------------------------------- */
|
||||
|
||||
@@ -44,12 +44,12 @@ typedef struct ASurfaceTransactionStats ASurfaceTransactionStats;
|
||||
typedef void (*sc_complete_fn)(void *context, ASurfaceTransactionStats *stats);
|
||||
|
||||
/* <android/hdr_metadata.h> (NDK, API 29), declared here like the rest of this table: stable ABI. */
|
||||
struct banner_color_xy { float x, y; };
|
||||
struct banner_hdr_smpte2086 {
|
||||
struct banner_color_xy displayPrimaryRed, displayPrimaryGreen, displayPrimaryBlue, whitePoint;
|
||||
struct droiddeck_color_xy { float x, y; };
|
||||
struct droiddeck_hdr_smpte2086 {
|
||||
struct droiddeck_color_xy displayPrimaryRed, displayPrimaryGreen, displayPrimaryBlue, whitePoint;
|
||||
float maxLuminance, minLuminance;
|
||||
};
|
||||
struct banner_hdr_cta861_3 { float maxContentLightLevel, maxFrameAverageLightLevel; };
|
||||
struct droiddeck_hdr_cta861_3 { float maxContentLightLevel, maxFrameAverageLightLevel; };
|
||||
|
||||
static struct {
|
||||
ASurfaceControl *(*createFromWindow)(ANativeWindow *, const char *);
|
||||
@@ -69,11 +69,11 @@ static struct {
|
||||
* the layer simply carries no vote and the app's surface vote is all there is. */
|
||||
void (*setFrameRate)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t);
|
||||
void (*setFrameRateStrategy)(ASurfaceTransaction *, ASurfaceControl *, float, int8_t, int8_t);
|
||||
/* Colour (API 29), optional: only an HDR session ever calls them (banner_color.h's gate needs
|
||||
/* Colour (API 29), optional: only an HDR session ever calls them (droiddeck_color.h's gate needs
|
||||
* setBufferDataSpace; the metadata calls are sent when present). */
|
||||
void (*setBufferDataSpace)(ASurfaceTransaction *, ASurfaceControl *, int32_t);
|
||||
void (*setHdrMetadata_smpte2086)(ASurfaceTransaction *, ASurfaceControl *, const struct banner_hdr_smpte2086 *);
|
||||
void (*setHdrMetadata_cta861_3)(ASurfaceTransaction *, ASurfaceControl *, const struct banner_hdr_cta861_3 *);
|
||||
void (*setHdrMetadata_smpte2086)(ASurfaceTransaction *, ASurfaceControl *, const struct droiddeck_hdr_smpte2086 *);
|
||||
void (*setHdrMetadata_cta861_3)(ASurfaceTransaction *, ASurfaceControl *, const struct droiddeck_hdr_cta861_3 *);
|
||||
/* Not in the public NDK headers (vndk/hardware_buffer.h) but exported by libnativewindow.so on
|
||||
* every device; Mesa's Android WSI calls it for every gralloc buffer it imports. */
|
||||
const void *(*getNativeHandle)(const AHardwareBuffer *);
|
||||
@@ -95,12 +95,12 @@ static int load_api(void) {
|
||||
if (!nw) nw = dlopen("libnativewindow.so", RTLD_NOW);
|
||||
api.getNativeHandle = nw ? dlsym(nw, "AHardwareBuffer_getNativeHandle") : NULL;
|
||||
if (!api.getNativeHandle) {
|
||||
banner_log("layer", "unavailable: libnativewindow.so has no AHardwareBuffer_getNativeHandle");
|
||||
droiddeck_log("layer", "unavailable: libnativewindow.so has no AHardwareBuffer_getNativeHandle");
|
||||
return -1;
|
||||
}
|
||||
void *lib = dlopen("libandroid.so", RTLD_NOW | RTLD_NOLOAD);
|
||||
if (!lib) lib = dlopen("libandroid.so", RTLD_NOW);
|
||||
if (!lib) { banner_log("layer", "unavailable: dlopen(libandroid.so): %s", dlerror()); return -1; }
|
||||
if (!lib) { droiddeck_log("layer", "unavailable: dlopen(libandroid.so): %s", dlerror()); return -1; }
|
||||
#define SYM(field, name) api.field = dlsym(lib, name)
|
||||
SYM(createFromWindow, "ASurfaceControl_createFromWindow");
|
||||
SYM(release, "ASurfaceControl_release");
|
||||
@@ -125,7 +125,7 @@ static int load_api(void) {
|
||||
if (!api.createFromWindow || !api.release || !api.txCreate || !api.txDelete || !api.txApply ||
|
||||
!api.setBuffer || !api.setZOrder || !api.setVisibility || !api.setGeometry ||
|
||||
!api.setBufferTransparency || !api.reparent || !api.setOnComplete || !api.prevReleaseFence) {
|
||||
banner_log("layer", "unavailable: libandroid.so lacks part of the ASurfaceControl API (Android 10+)");
|
||||
droiddeck_log("layer", "unavailable: libandroid.so lacks part of the ASurfaceControl API (Android 10+)");
|
||||
return -1;
|
||||
}
|
||||
api.state = 1;
|
||||
@@ -214,10 +214,10 @@ static AHardwareBuffer *g_blank;
|
||||
static void layers_init(void) {
|
||||
if (g_layers_ready) return;
|
||||
g_layers_ready = 1;
|
||||
g_layers[SC_LAYER_GAME] = (struct layer){.name = "banner_wayland_game", .z = 1, .pool_n = POOL_MAX,
|
||||
g_layers[SC_LAYER_GAME] = (struct layer){.name = "droiddeck_wayland_game", .z = 1, .pool_n = POOL_MAX,
|
||||
.cur_slot = -1, .votes_rate = 1, .fps_applied = -1.0f, .hr_applied = -1.0f,
|
||||
.ds_applied = -1};
|
||||
g_layers[SC_LAYER_OVERLAY] = (struct layer){.name = "banner_wayland_overlay", .z = 2, .pool_n = 3,
|
||||
g_layers[SC_LAYER_OVERLAY] = (struct layer){.name = "droiddeck_wayland_overlay", .z = 2, .pool_n = 3,
|
||||
.cur_slot = -1, .votes_rate = 0, .fps_applied = -1.0f,
|
||||
.hr_applied = -1.0f, .ds_applied = -1};
|
||||
for (int i = 0; i < SC_LAYER_COUNT; i++)
|
||||
@@ -330,7 +330,7 @@ static void retire_sc(struct layer *l) {
|
||||
if (l->cur_token) ahb_swapchain_layer_released(l->cur_token, -1);
|
||||
api.release(l->sc);
|
||||
}
|
||||
banner_log("layer", "%s: SurfaceControl retired (window %p)", l->name, (void *)l->win);
|
||||
droiddeck_log("layer", "%s: SurfaceControl retired (window %p)", l->name, (void *)l->win);
|
||||
l->sc = NULL; l->win = NULL;
|
||||
l->shown = 0; l->cur_slot = -1; l->cur_token = NULL; l->geo_valid = 0;
|
||||
l->fps_applied = -1.0f; /* the next SurfaceControl carries no vote until it is re-applied */
|
||||
@@ -368,7 +368,7 @@ static void drain_and_free_pools(void) {
|
||||
/* Native-handle sniff, the same one Mesa's u_gralloc fallback uses (u_gralloc_fallback.c): a QTI
|
||||
* gralloc private_handle_t carries the magic 'gmsm' as its first int and the UBWC flag
|
||||
* (PRIV_FLAGS_UBWC_ALIGNED, 0x08000000) in the next one. Returns 0 when the layout is unknown. */
|
||||
static int sniff_modifier(const struct banner_native_handle *h, uint64_t *mod) {
|
||||
static int sniff_modifier(const struct droiddeck_native_handle *h, uint64_t *mod) {
|
||||
const uint32_t gmsm = ('g' << 24) | ('m' << 16) | ('s' << 8) | 'm';
|
||||
if (!h || h->numFds < 1 || h->numInts < 2) return 0;
|
||||
if ((uint32_t)h->data[h->numFds] != gmsm) return 0;
|
||||
@@ -387,7 +387,7 @@ static int g_alloc_failed; /* set by alloc_slot when gralloc or the import refus
|
||||
* TIER_PLAIN the same without the vendor bit (a gralloc that refuses unknown bits; what we asked before).
|
||||
* TIER_LINEAR plus a CPU bit, so the layout is known to be linear even when the handle is unreadable. */
|
||||
enum { TIER_UBWC, TIER_PLAIN, TIER_LINEAR };
|
||||
#define BANNER_AHB_USAGE_VENDOR_UBWC (1ULL << 28) /* AHARDWAREBUFFER_USAGE_VENDOR_0 */
|
||||
#define DROIDDECK_AHB_USAGE_VENDOR_UBWC (1ULL << 28) /* AHARDWAREBUFFER_USAGE_VENDOR_0 */
|
||||
|
||||
static const char *tier_name(int tier) {
|
||||
return tier == TIER_UBWC ? "asked for UBWC" : tier == TIER_PLAIN ? "no UBWC request" : "linear by request (CPU bit)";
|
||||
@@ -404,22 +404,22 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
|
||||
* composer overlay (the display scans it out). See the tiers above for the rest. */
|
||||
.usage = AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
|
||||
AHARDWAREBUFFER_USAGE_COMPOSER_OVERLAY |
|
||||
(tier == TIER_UBWC ? BANNER_AHB_USAGE_VENDOR_UBWC : 0) |
|
||||
(tier == TIER_UBWC ? DROIDDECK_AHB_USAGE_VENDOR_UBWC : 0) |
|
||||
(tier == TIER_LINEAR ? AHARDWAREBUFFER_USAGE_CPU_READ_RARELY : 0)};
|
||||
AHardwareBuffer *ahb = NULL;
|
||||
if (AHardwareBuffer_allocate(&d, &ahb) != 0 || !ahb) {
|
||||
if (tier < TIER_LINEAR) {
|
||||
banner_log("layer", "%s: gralloc refused a %dx%d pool buffer (%s): trying %s", l->name, w, h,
|
||||
droiddeck_log("layer", "%s: gralloc refused a %dx%d pool buffer (%s): trying %s", l->name, w, h,
|
||||
tier_name(tier), tier_name(tier + 1));
|
||||
l->alloc_tier = tier + 1;
|
||||
continue;
|
||||
}
|
||||
banner_log("error", "layer: %s: AHardwareBuffer_allocate %dx%d (format %#x) failed", l->name, w, h, fmt);
|
||||
droiddeck_log("error", "layer: %s: AHardwareBuffer_allocate %dx%d (format %#x) failed", l->name, w, h, fmt);
|
||||
g_alloc_failed = 1;
|
||||
return -1;
|
||||
}
|
||||
AHardwareBuffer_Desc got; AHardwareBuffer_describe(ahb, &got);
|
||||
const struct banner_native_handle *nh = api.getNativeHandle(ahb);
|
||||
const struct droiddeck_native_handle *nh = api.getNativeHandle(ahb);
|
||||
uint64_t mod = MOD_LINEAR;
|
||||
if (!sniff_modifier(nh, &mod)) {
|
||||
/* Not a handle we can read: the only layout we can assume is linear, and only if the buffer
|
||||
@@ -427,7 +427,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
|
||||
if (tier < TIER_LINEAR) {
|
||||
AHardwareBuffer_release(ahb);
|
||||
l->alloc_tier = TIER_LINEAR;
|
||||
banner_log("layer", "%s: gralloc handle layout unknown (%d fds, %d ints): using linear pool buffers",
|
||||
droiddeck_log("layer", "%s: gralloc handle layout unknown (%d fds, %d ints): using linear pool buffers",
|
||||
l->name, nh ? nh->numFds : -1, nh ? nh->numInts : -1);
|
||||
continue;
|
||||
}
|
||||
@@ -439,7 +439,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
|
||||
struct vkp_image *img = fd >= 0 ? vkp_image_import_dmabuf(fd, fmt == AHB_RGB10A2 ? DRM_ABGR2101010 : DRM_ABGR8888,
|
||||
mod, w, h, got.stride * 4, 0, 1) : NULL;
|
||||
if (!img) {
|
||||
banner_log("layer", "%s: import of a %s %dx%d pool buffer (stride %u px) into the compositor's Turnip failed",
|
||||
droiddeck_log("layer", "%s: import of a %s %dx%d pool buffer (stride %u px) into the compositor's Turnip failed",
|
||||
l->name, mod == MOD_QCOM_COMPRESSED ? "UBWC" : "linear", w, h, got.stride);
|
||||
AHardwareBuffer_release(ahb);
|
||||
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
|
||||
@@ -451,7 +451,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
|
||||
if (l->logged_w != w || l->logged_h != h || l->logged_fmt != fmt || l->logged_mod != mod ||
|
||||
l->logged_tier != tier) {
|
||||
l->logged_w = w; l->logged_h = h; l->logged_fmt = fmt; l->logged_mod = mod; l->logged_tier = tier;
|
||||
banner_log("layer", "%s: pool buffers %dx%d%s: %s (%s), stride %u px, up to %d buffers (gralloc handle %d fds / %d ints)",
|
||||
droiddeck_log("layer", "%s: pool buffers %dx%d%s: %s (%s), stride %u px, up to %d buffers (gralloc handle %d fds / %d ints)",
|
||||
l->name, w, h, fmt == AHB_RGB10A2 ? " 10-bit RGBA1010102" : "",
|
||||
mod == MOD_QCOM_COMPRESSED ? "UBWC (QCOM_COMPRESSED)" : "linear", tier_name(tier),
|
||||
got.stride, l->pool_n, nh ? nh->numFds : -1, nh ? nh->numInts : -1);
|
||||
@@ -532,10 +532,10 @@ void sc_layer_probe_dmabuf_fd(int fd) {
|
||||
struct { uint32_t flags; int32_t fd; } exp = {.flags = 1u /* DMA_BUF_SYNC_READ */, .fd = -1};
|
||||
/* DMA_BUF_IOCTL_EXPORT_SYNC_FILE = _IOWR('b', 2, struct dma_buf_export_sync_file) */
|
||||
if (ioctl(fd, _IOWR('b', 2, exp), &exp) == 0) {
|
||||
banner_log("layer", "kernel exports sync_file fences from the game's dma-buf: zero-copy acquire fences can come from the buffer itself");
|
||||
droiddeck_log("layer", "kernel exports sync_file fences from the game's dma-buf: zero-copy acquire fences can come from the buffer itself");
|
||||
if (exp.fd >= 0) close(exp.fd);
|
||||
} else {
|
||||
banner_log("layer", "DMA_BUF_IOCTL_EXPORT_SYNC_FILE on the game's dma-buf failed (%s): acquire fences must be exported by the game's driver (sync_fd) instead",
|
||||
droiddeck_log("layer", "DMA_BUF_IOCTL_EXPORT_SYNC_FILE on the game's dma-buf failed (%s): acquire fences must be exported by the game's driver (sync_fd) instead",
|
||||
strerror(errno));
|
||||
}
|
||||
}
|
||||
@@ -549,7 +549,7 @@ static int ensure_sc(struct layer *l) {
|
||||
if (l->sc && l->win != win) retire_sc(l);
|
||||
if (!l->sc) {
|
||||
l->sc = api.createFromWindow(win, l->name);
|
||||
if (!l->sc) { banner_log("error", "layer: ASurfaceControl_createFromWindow(%s) failed", l->name); return -1; }
|
||||
if (!l->sc) { droiddeck_log("error", "layer: ASurfaceControl_createFromWindow(%s) failed", l->name); return -1; }
|
||||
l->win = win;
|
||||
l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f;
|
||||
ASurfaceTransaction *tx = api.txCreate();
|
||||
@@ -559,7 +559,7 @@ static int ensure_sc(struct layer *l) {
|
||||
apply_frame_rate(tx, l);
|
||||
api.txApply(tx); api.txDelete(tx);
|
||||
}
|
||||
banner_log("layer", "SurfaceControl \"%s\" created as a child of the screen surface (z=%d)", l->name, (int)l->z);
|
||||
droiddeck_log("layer", "SurfaceControl \"%s\" created as a child of the screen surface (z=%d)", l->name, (int)l->z);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -585,7 +585,7 @@ static void apply_geometry(ASurfaceTransaction *tx, struct layer *l, const int r
|
||||
l->geo_src = srcR; l->geo_dst = dstR; l->geo_valid = 1;
|
||||
char cov[96] = "";
|
||||
if (l->ds_applied > 0) coverage_text(l, cov, sizeof(cov));
|
||||
banner_log("layer", "%s geometry: buffer %d,%d-%d,%d -> screen %d,%d-%d,%d%s%s%s", l->name,
|
||||
droiddeck_log("layer", "%s geometry: buffer %d,%d-%d,%d -> screen %d,%d-%d,%d%s%s%s", l->name,
|
||||
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], cov[0] ? " (HDR layer " : "", cov, cov[0] ? ")" : "");
|
||||
}
|
||||
}
|
||||
@@ -606,11 +606,11 @@ static void apply_frame_rate(ASurfaceTransaction *tx, struct layer *l) {
|
||||
}
|
||||
int first = l->fps_applied < 0.0f;
|
||||
l->fps_applied = want;
|
||||
if (want > 0.0f) banner_log("layer", "display frame-rate vote on %s: %.2f Hz", l->name, want);
|
||||
else if (!first) banner_log("layer", "display frame-rate vote on %s cleared (panel runs free)", l->name);
|
||||
if (want > 0.0f) droiddeck_log("layer", "display frame-rate vote on %s: %.2f Hz", l->name, want);
|
||||
else if (!first) droiddeck_log("layer", "display frame-rate vote on %s cleared (panel runs free)", l->name);
|
||||
}
|
||||
|
||||
/* ---- colour (HDR, banner_color.h) -------------------------------------------------------------
|
||||
/* ---- colour (HDR, droiddeck_color.h) -------------------------------------------------------------
|
||||
* The layer is told what its buffer's pixels MEAN - the dataspace (BT2020_PQ for an HDR10 frame) and
|
||||
* the game's mastering / content-light metadata - in the same transaction as the buffer, so the
|
||||
* display never shows an HDR frame decoded as sRGB or the other way round. A layer that has never been
|
||||
@@ -630,67 +630,67 @@ static void coverage_text(const struct layer *l, char *out, size_t n) {
|
||||
|
||||
/* API 35: ask the display for HDR headroom explicitly while the layer carries an HDR frame, and clear the
|
||||
* request (0 = no preference) when it stops. Only on change; a layer never tagged is never touched. */
|
||||
static void apply_headroom(ASurfaceTransaction *tx, struct layer *l, const struct banner_color *c) {
|
||||
static void apply_headroom(ASurfaceTransaction *tx, struct layer *l, const struct droiddeck_color *c) {
|
||||
static int said_missing;
|
||||
if (!api.setDesiredHdrHeadroom) {
|
||||
if (c && c->dataspace && !said_missing) {
|
||||
said_missing = 1;
|
||||
banner_color_note_headroom_request(-1.0f);
|
||||
banner_log("color", "HDR headroom request not available on %s (Android < 15 has no "
|
||||
droiddeck_color_note_headroom_request(-1.0f);
|
||||
droiddeck_log("color", "HDR headroom request not available on %s (Android < 15 has no "
|
||||
"ASurfaceTransaction_setDesiredHdrHeadroom): the layer relies on Android's default", l->name);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const float want = (c && c->dataspace) ? banner_color_desired_headroom(c, NULL, 0) : 0.0f;
|
||||
const float want = (c && c->dataspace) ? droiddeck_color_desired_headroom(c, NULL, 0) : 0.0f;
|
||||
if (l->hr_applied < 0.0f && want == 0.0f && !(c && c->dataspace)) return; /* never asked: leave it be */
|
||||
if (l->hr_applied >= 0.0f && fabsf(want - l->hr_applied) < 0.005f) return;
|
||||
char why[200] = "";
|
||||
if (c && c->dataspace) banner_color_desired_headroom(c, why, sizeof(why));
|
||||
if (c && c->dataspace) droiddeck_color_desired_headroom(c, why, sizeof(why));
|
||||
api.setDesiredHdrHeadroom(tx, l->sc, want);
|
||||
const int first = l->hr_applied < 0.0f;
|
||||
l->hr_applied = want;
|
||||
banner_color_note_headroom_request(want);
|
||||
droiddeck_color_note_headroom_request(want);
|
||||
if (want > 0.0f)
|
||||
banner_log("color", "requested HDR headroom %.1fx on %s (%s)", want, l->name, why);
|
||||
droiddeck_log("color", "requested HDR headroom %.1fx on %s (%s)", want, l->name, why);
|
||||
else if (c && c->dataspace)
|
||||
banner_log("color", "no HDR headroom requested on %s: %s", l->name, why);
|
||||
droiddeck_log("color", "no HDR headroom requested on %s: %s", l->name, why);
|
||||
else if (!first)
|
||||
banner_log("color", "HDR headroom request on %s cleared (no preference): the frame on the layer is not HDR", l->name);
|
||||
droiddeck_log("color", "HDR headroom request on %s cleared (no preference): the frame on the layer is not HDR", l->name);
|
||||
}
|
||||
|
||||
static void apply_colour(ASurfaceTransaction *tx, struct layer *l, const struct banner_color *c) {
|
||||
int32_t want = c ? c->dataspace : BANNER_ADATASPACE_UNKNOWN;
|
||||
static void apply_colour(ASurfaceTransaction *tx, struct layer *l, const struct droiddeck_color *c) {
|
||||
int32_t want = c ? c->dataspace : DROIDDECK_ADATASPACE_UNKNOWN;
|
||||
uint32_t md = (c && c->dataspace) ? c->identity : 0;
|
||||
if (!api.setBufferDataSpace) return;
|
||||
if (l->ds_applied < 0 && want == BANNER_ADATASPACE_UNKNOWN) return; /* never tagged: leave it be */
|
||||
if (l->ds_applied < 0 && want == DROIDDECK_ADATASPACE_UNKNOWN) return; /* never tagged: leave it be */
|
||||
apply_headroom(tx, l, want ? c : NULL);
|
||||
if (want == l->ds_applied && md == l->md_applied) return;
|
||||
api.setBufferDataSpace(tx, l->sc, want);
|
||||
struct banner_hdr_smpte2086 st;
|
||||
struct banner_hdr_cta861_3 cta;
|
||||
struct droiddeck_hdr_smpte2086 st;
|
||||
struct droiddeck_hdr_cta861_3 cta;
|
||||
int st_on = c && c->dataspace && c->has_st2086, cta_on = c && c->dataspace && c->has_cta861;
|
||||
if (st_on) {
|
||||
st = (struct banner_hdr_smpte2086){
|
||||
st = (struct droiddeck_hdr_smpte2086){
|
||||
.displayPrimaryRed = {c->red[0], c->red[1]}, .displayPrimaryGreen = {c->green[0], c->green[1]},
|
||||
.displayPrimaryBlue = {c->blue[0], c->blue[1]}, .whitePoint = {c->white[0], c->white[1]},
|
||||
.maxLuminance = c->max_lum, .minLuminance = c->min_lum};
|
||||
}
|
||||
if (cta_on) cta = (struct banner_hdr_cta861_3){.maxContentLightLevel = c->max_cll, .maxFrameAverageLightLevel = c->max_fall};
|
||||
if (cta_on) cta = (struct droiddeck_hdr_cta861_3){.maxContentLightLevel = c->max_cll, .maxFrameAverageLightLevel = c->max_fall};
|
||||
/* NULL clears what a previous description set: metadata never outlives the frame it belongs to. */
|
||||
if (api.setHdrMetadata_smpte2086) api.setHdrMetadata_smpte2086(tx, l->sc, st_on ? &st : NULL);
|
||||
if (api.setHdrMetadata_cta861_3) api.setHdrMetadata_cta861_3(tx, l->sc, cta_on ? &cta : NULL);
|
||||
if (want) {
|
||||
char cov[96];
|
||||
coverage_text(l, cov, sizeof(cov));
|
||||
banner_log("color", "%s: dataspace %s (%#x) set on the display layer for image description #%u%s%s; SMPTE 2086 "
|
||||
"%s, CTA-861.3 %s [%s]", l->name, want == BANNER_ADATASPACE_BT2020_PQ ? "BT2020_PQ" : "HDR",
|
||||
droiddeck_log("color", "%s: dataspace %s (%#x) set on the display layer for image description #%u%s%s; SMPTE 2086 "
|
||||
"%s, CTA-861.3 %s [%s]", l->name, want == DROIDDECK_ADATASPACE_BT2020_PQ ? "BT2020_PQ" : "HDR",
|
||||
(unsigned)want, c->identity, cov[0] ? ", " : "", cov,
|
||||
st_on ? (api.setHdrMetadata_smpte2086 ? "sent" : "not supported by this Android") : "none given",
|
||||
cta_on ? (api.setHdrMetadata_cta861_3 ? "sent" : "not supported by this Android") : "none given",
|
||||
c->text);
|
||||
}
|
||||
else
|
||||
banner_log("color", "%s: dataspace back to UNKNOWN (sRGB), HDR metadata cleared - the frame on the layer is "
|
||||
droiddeck_log("color", "%s: dataspace back to UNKNOWN (sRGB), HDR metadata cleared - the frame on the layer is "
|
||||
"not an HDR frame", l->name);
|
||||
l->ds_applied = want;
|
||||
l->md_applied = md;
|
||||
@@ -711,7 +711,7 @@ void sc_layer_hdr_symbols(char *out, size_t size) {
|
||||
static void log_layer_count(void) {
|
||||
if (g_two_logged) return;
|
||||
g_two_logged = 1;
|
||||
banner_log("layer", "%d display layers in use: \"%s\" (z=%d) and \"%s\" (z=%d) above it, both children of the "
|
||||
droiddeck_log("layer", "%d display layers in use: \"%s\" (z=%d) and \"%s\" (z=%d) above it, both children of the "
|
||||
"screen surface; the app's own views (drawer, HUD, pointer) stay above both. %d is the cap - more "
|
||||
"would push SurfaceFlinger into GPU client composition",
|
||||
SC_LAYER_COUNT, g_layers[SC_LAYER_GAME].name, (int)g_layers[SC_LAYER_GAME].z,
|
||||
@@ -748,7 +748,7 @@ static ASurfaceControl *swap_sc_begin(struct layer *l) {
|
||||
if (!win || win != l->win) return NULL; /* the window changed: ensure_sc re-creates it anyway */
|
||||
ASurfaceControl *fresh = api.createFromWindow(win, l->name);
|
||||
if (!fresh) {
|
||||
banner_log("error", "layer: %s: composition recovery could not create a new SurfaceControl", l->name);
|
||||
droiddeck_log("error", "layer: %s: composition recovery could not create a new SurfaceControl", l->name);
|
||||
return NULL;
|
||||
}
|
||||
ASurfaceControl *old = l->sc;
|
||||
@@ -760,14 +760,14 @@ static ASurfaceControl *swap_sc_begin(struct layer *l) {
|
||||
l->geo_valid = 0;
|
||||
l->fps_applied = -1.0f;
|
||||
l->ds_applied = -1; l->md_applied = 0; l->hr_applied = -1.0f;
|
||||
banner_log("layer", "composition recovery: %s got a fresh SurfaceControl now that nothing is above "
|
||||
droiddeck_log("layer", "composition recovery: %s got a fresh SurfaceControl now that nothing is above "
|
||||
"the game (measured on this panel: hardware composition does NOT return from this alone)", l->name);
|
||||
return old;
|
||||
}
|
||||
|
||||
/* The transaction that puts pool slot `idx` of layer `l` on screen at `r`, as `color` (NULL = no
|
||||
* description). 0 = applied. */
|
||||
static int present_slot(struct layer *l, int idx, const int r[8], const struct banner_color *color,
|
||||
static int present_slot(struct layer *l, int idx, const int r[8], const struct droiddeck_color *color,
|
||||
int translucent) {
|
||||
struct slot *s = &l->slots[idx];
|
||||
ASurfaceTransaction *tx = api.txCreate();
|
||||
@@ -792,7 +792,7 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct b
|
||||
api.txDelete(tx);
|
||||
l->cur_slot = idx;
|
||||
l->cur_token = NULL;
|
||||
if (!l->shown) { l->shown = 1; banner_log("layer", "%s: layer shown", l->name); }
|
||||
if (!l->shown) { l->shown = 1; droiddeck_log("layer", "%s: layer shown", l->name); }
|
||||
g_stat_layer_frames++;
|
||||
return 0;
|
||||
}
|
||||
@@ -805,7 +805,7 @@ static void log_drop(struct layer *l) {
|
||||
l->drops_unlogged++;
|
||||
int64_t t = now_ns();
|
||||
if (!l->drop_logged_ns || t - l->drop_logged_ns > 30000000000LL) {
|
||||
banner_log("layer", "%s: no free layer buffer (display still holds all %d): %u frame%s dropped%s", l->name,
|
||||
droiddeck_log("layer", "%s: no free layer buffer (display still holds all %d): %u frame%s dropped%s", l->name,
|
||||
l->pool_n, l->drops_unlogged, l->drops_unlogged == 1 ? "" : "s",
|
||||
l->drop_logged_ns ? " since the last such line" : "");
|
||||
l->drop_logged_ns = t;
|
||||
@@ -820,7 +820,7 @@ unsigned sc_layer_drops_take(void) {
|
||||
}
|
||||
|
||||
int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token, int scene_w, int scene_h,
|
||||
const struct banner_color *color, uint32_t ahb_format) {
|
||||
const struct droiddeck_color *color, uint32_t ahb_format) {
|
||||
struct layer *l = layer_of(SC_LAYER_GAME);
|
||||
int r[8];
|
||||
if (!ahb || !token || ensure_sc(l) != 0) goto unavailable;
|
||||
@@ -836,6 +836,7 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi
|
||||
apply_geometry(tx, l, r); apply_frame_rate(tx, l); apply_colour(tx, l, color);
|
||||
api.txApply(tx); api.txDelete(tx);
|
||||
}
|
||||
vkp_signal_first_frame();
|
||||
return 0;
|
||||
}
|
||||
ASurfaceTransaction *tx = api.txCreate();
|
||||
@@ -862,16 +863,19 @@ int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, voi
|
||||
api.txDelete(tx);
|
||||
l->cur_slot = -1;
|
||||
l->cur_token = token;
|
||||
if (!l->shown) { l->shown = 1; banner_log("layer", "%s: layer shown", l->name); }
|
||||
if (!l->first_logged) { l->first_logged = 1; vkp_signal_first_frame(); }
|
||||
if (color && color->dataspace) banner_color_frame_shown(color, BANNER_HDR_ZERO_COPY, ahb_format);
|
||||
if (!l->shown) { l->shown = 1; droiddeck_log("layer", "%s: layer shown", l->name); }
|
||||
/* The notification is re-armed for each session; the layer and its logging flag can
|
||||
* outlive it. Let the notification's own one-shot decide whether to fire. */
|
||||
if (!l->first_logged) l->first_logged = 1;
|
||||
vkp_signal_first_frame();
|
||||
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_ZERO_COPY, ahb_format);
|
||||
return 0;
|
||||
unavailable:
|
||||
if (acquire_fd >= 0) close(acquire_fd);
|
||||
return -1;
|
||||
}
|
||||
|
||||
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct banner_color *color) {
|
||||
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color) {
|
||||
struct layer *l = layer_of(SC_LAYER_GAME);
|
||||
if (!src || ensure_sc(l) != 0) return -1;
|
||||
int sw = vkp_image_width(src), sh = vkp_image_height(src);
|
||||
@@ -885,14 +889,14 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
|
||||
if (idx < 0) { log_drop(l); return 0; }
|
||||
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
|
||||
if (present_slot(l, idx, r, color, 0) != 0) return -1;
|
||||
if (color && color->dataspace) banner_color_frame_shown(color, BANNER_HDR_LAYER_COPY, AHB_RGBA8);
|
||||
if (color && color->dataspace) droiddeck_color_frame_shown(color, DROIDDECK_HDR_LAYER_COPY, AHB_RGBA8);
|
||||
if (!l->first_logged) {
|
||||
l->first_logged = 1;
|
||||
banner_log("layer", "presenting %dx%d game frames on their own SurfaceControl layer (%s pool, %d buffers); "
|
||||
droiddeck_log("layer", "presenting %dx%d game frames on their own SurfaceControl layer (%s pool, %d buffers); "
|
||||
"HUD and pointer stay Android views above it", sw, sh,
|
||||
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear", l->pool_n);
|
||||
vkp_signal_first_frame();
|
||||
}
|
||||
vkp_signal_first_frame();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -912,11 +916,11 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
|
||||
if (present_slot(l, idx, r, NULL, 0) != 0) return -1; /* the effects chain's result is 8-bit sRGB */
|
||||
if (!l->first_logged) {
|
||||
l->first_logged = 1;
|
||||
banner_log("layer", "presenting %dx%d frames on their own SurfaceControl layer (%s pool, %d buffers); "
|
||||
droiddeck_log("layer", "presenting %dx%d frames on their own SurfaceControl layer (%s pool, %d buffers); "
|
||||
"HUD and pointer stay Android views above it", rw, rh,
|
||||
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear", l->pool_n);
|
||||
vkp_signal_first_frame();
|
||||
}
|
||||
vkp_signal_first_frame();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -931,7 +935,7 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
|
||||
static uint32_t g_hdr_pool_fmt = AHB_RGB10A2;
|
||||
|
||||
int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf,
|
||||
int scene_w, int scene_h, const struct banner_color *color) {
|
||||
int scene_w, int scene_h, const struct droiddeck_color *color) {
|
||||
struct layer *l = layer_of(SC_LAYER_GAME);
|
||||
int rw = 0, rh = 0, r[8];
|
||||
if (!draws || n <= 0 || !hf || ensure_sc(l) != 0) return -1;
|
||||
@@ -945,7 +949,7 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct
|
||||
int idx = take_free_slot(l, rw, rh, fmt, &wait_fd);
|
||||
if (idx < 0 && g_alloc_failed && fmt == AHB_RGB10A2) {
|
||||
g_hdr_pool_fmt = AHB_RGBA8;
|
||||
banner_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes "
|
||||
droiddeck_log("color", "%s: this device will not make a 10-bit layer buffer (RGBA1010102): the HDR picture goes "
|
||||
"on 8-bit buffers instead (still tagged BT2020_PQ; less precision)", l->name);
|
||||
idx = take_free_slot(l, rw, rh, g_hdr_pool_fmt, &wait_fd);
|
||||
}
|
||||
@@ -953,25 +957,26 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct
|
||||
if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1;
|
||||
if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1; /* tone-mapped = plain sRGB: no tag */
|
||||
if (color && color->dataspace)
|
||||
banner_color_frame_shown(color, tm ? BANNER_HDR_TONEMAPPED : BANNER_HDR_COMPOSED, tm ? AHB_RGBA8 : g_hdr_pool_fmt);
|
||||
droiddeck_color_frame_shown(color, tm ? DROIDDECK_HDR_TONEMAPPED : DROIDDECK_HDR_COMPOSED, tm ? AHB_RGBA8 : g_hdr_pool_fmt);
|
||||
static int said = -1;
|
||||
if (said != tm) {
|
||||
said = tm;
|
||||
if (tm)
|
||||
banner_log("color", "tone-mapped picture on the game's display layer: %dx%d, %s 8-bit buffers, untagged "
|
||||
droiddeck_log("color", "tone-mapped picture on the game's display layer: %dx%d, %s 8-bit buffers, untagged "
|
||||
"(sRGB) - HDR output is switched off", rw, rh,
|
||||
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear");
|
||||
else {
|
||||
char cov[96];
|
||||
coverage_text(l, cov, sizeof(cov));
|
||||
banner_log("color", "HDR picture on its own display layer: %dx%d, %s %s buffers, tagged %s%s%s", rw, rh,
|
||||
droiddeck_log("color", "HDR picture on its own display layer: %dx%d, %s %s buffers, tagged %s%s%s", rw, rh,
|
||||
l->pool_modifier == MOD_QCOM_COMPRESSED ? "UBWC" : "linear",
|
||||
g_hdr_pool_fmt == AHB_RGB10A2 ? "10-bit" : "8-bit",
|
||||
color && color->dataspace == BANNER_ADATASPACE_BT2020_PQ ? "BT2020_PQ" : "HDR",
|
||||
color && color->dataspace == DROIDDECK_ADATASPACE_BT2020_PQ ? "BT2020_PQ" : "HDR",
|
||||
cov[0] ? ", " : "", cov);
|
||||
}
|
||||
}
|
||||
if (!l->first_logged) { l->first_logged = 1; vkp_signal_first_frame(); }
|
||||
if (!l->first_logged) l->first_logged = 1;
|
||||
vkp_signal_first_frame();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1020,13 +1025,13 @@ int sc_layer_overlay_affordable(void) {
|
||||
int first = g_overlay_declined < 0;
|
||||
g_overlay_declined = want;
|
||||
if (want)
|
||||
banner_log("layer", "overlay layer declined: this display rotates every layer %d° and the game "
|
||||
droiddeck_log("layer", "overlay layer declined: this display rotates every layer %d° and the game "
|
||||
"layer is scaled %dx%d -> %dx%d, and on that combination a second layer drops the "
|
||||
"whole frame to GPU composition for the rest of the session (measured). The window "
|
||||
"above the game goes on the copy path instead - same picture, one blit.",
|
||||
deg, sr[0], sr[1], ds[0], ds[1]);
|
||||
else if (!first)
|
||||
banner_log("layer", "overlay layer allowed again: the game layer is no longer both rotated and "
|
||||
droiddeck_log("layer", "overlay layer allowed again: the game layer is no longer both rotated and "
|
||||
"scaled, so a second display layer costs nothing here");
|
||||
}
|
||||
return ok;
|
||||
@@ -1077,7 +1082,7 @@ void sc_layer_hide(void) {
|
||||
* SurfaceControl, since it goes up and down with every effects/frame-generation toggle. */
|
||||
if (g_layers[SC_LAYER_OVERLAY].sc) sc_layer_hide_overlay();
|
||||
if (g_layers[SC_LAYER_GAME].shown) hide_layer(&g_layers[SC_LAYER_GAME]);
|
||||
if (said) banner_log("layer", "layers hidden (scene is not a single fullscreen window)");
|
||||
if (said) droiddeck_log("layer", "layers hidden (scene is not a single fullscreen window)");
|
||||
}
|
||||
|
||||
void sc_layer_hide_overlay(void) {
|
||||
@@ -1093,7 +1098,7 @@ void sc_layer_hide_overlay(void) {
|
||||
* buffers stay allocated for the next window. */
|
||||
if (l->shown) hide_layer(l);
|
||||
retire_sc(l);
|
||||
banner_log("layer", "%s: gone (nothing is above the game any more)", l->name);
|
||||
droiddeck_log("layer", "%s: gone (nothing is above the game any more)", l->name);
|
||||
/* ...and that is the half the measurement said is not enough: arm the game layer's
|
||||
* SurfaceControl swap, which the next frame performs (swap_sc_begin). */
|
||||
if (g_layers[SC_LAYER_GAME].sc) g_layers[SC_LAYER_GAME].recreate_pending = 1;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#ifndef SC_LAYER_H
|
||||
#define SC_LAYER_H
|
||||
/*
|
||||
* Layer mode (BANNER_WAYLAND_ZERO_COPY=1): the scene is handed to SurfaceFlinger as a small,
|
||||
* Layer mode (DROIDDECK_WAYLAND_ZERO_COPY=1): the scene is handed to SurfaceFlinger as a small,
|
||||
* deliberately ordered SET of Android display layers - ASurfaceControl children of the
|
||||
* compositor's SurfaceView - instead of being blitted into the compositor's own swapchain.
|
||||
*
|
||||
@@ -12,8 +12,8 @@
|
||||
* an ASurfaceControl has no input channel, so touch and mouse keep
|
||||
* reaching the SurfaceView exactly as they did.
|
||||
* +-- SurfaceView ..... the compositor's Vulkan swapchain; black while layer mode is up
|
||||
* +-- z=1 "banner_wayland_game" ...... the one fullscreen game window
|
||||
* +-- z=2 "banner_wayland_overlay" ... at most one window drawn ABOVE the game
|
||||
* +-- z=1 "droiddeck_wayland_game" ...... the one fullscreen game window
|
||||
* +-- z=2 "droiddeck_wayland_overlay" ... at most one window drawn ABOVE the game
|
||||
*
|
||||
* TWO layers is the hard cap (SC_LAYER_COUNT), and deliberately so: HWC composes only a few
|
||||
* layers before SurfaceFlinger falls back to GPU client composition, which would throw away the
|
||||
@@ -71,7 +71,7 @@
|
||||
|
||||
struct vkp_image;
|
||||
struct vkp_draw;
|
||||
struct banner_color;
|
||||
struct droiddeck_color;
|
||||
|
||||
/* The layers, bottom first. The z-order is the array order (z = id + 1). */
|
||||
enum sc_layer_id { SC_LAYER_GAME = 0, SC_LAYER_OVERLAY = 1, SC_LAYER_COUNT = 2 };
|
||||
@@ -84,7 +84,7 @@ int sc_layer_available(void);
|
||||
* Decides where a zero-copy acquire fence can come from; result goes to the session log. */
|
||||
void sc_layer_probe_dmabuf_fd(int fd);
|
||||
|
||||
/* HDR (banner_color.h): can a display layer be told its buffer's colour encoding here
|
||||
/* HDR (droiddeck_color.h): can a display layer be told its buffer's colour encoding here
|
||||
* (ASurfaceTransaction_setBufferDataSpace, Android 10+)? Part of the HDR gate. */
|
||||
int sc_layer_can_tag_hdr(void);
|
||||
/* Which of the colour calls this libandroid has, for the gate's log line. */
|
||||
@@ -100,7 +100,7 @@ void sc_layer_hdr_symbols(char *out, size_t size);
|
||||
* free buffer), -1 = the layer path is unavailable this frame and the caller must draw the old way.
|
||||
* The copy into the layer buffer is 8-bit: an HDR frame keeps its tag (its colours stay right), and
|
||||
* loses precision. */
|
||||
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct banner_color *color);
|
||||
int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const struct droiddeck_color *color);
|
||||
|
||||
/* GAME layer, screen effects on: run the compositor pass (composite `draws` + the effects chain,
|
||||
* vkp_pass_begin) and put its result on the layer. Same return values as sc_layer_present. */
|
||||
@@ -113,7 +113,7 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
|
||||
* Same return values as sc_layer_present. */
|
||||
struct vkp_hdr_frame;
|
||||
int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct vkp_hdr_frame *hf,
|
||||
int scene_w, int scene_h, const struct banner_color *color);
|
||||
int scene_w, int scene_h, const struct droiddeck_color *color);
|
||||
|
||||
/* GAME layer, zero-copy (ahb_swapchain.c): show the game's own w x h AHardwareBuffer, gated by
|
||||
* acquire_fd (a sync_file the layer waits on before reading; owned by the callee, -1 = none).
|
||||
@@ -124,7 +124,7 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct
|
||||
* frame (the caller draws the old way). `color` / `ahb_format`: the frame's image description (NULL =
|
||||
* none) and the buffer's AHARDWAREBUFFER_FORMAT_*, for the dataspace and the HDR evidence. */
|
||||
int sc_layer_present_ahb(AHardwareBuffer *ahb, int w, int h, int acquire_fd, void *token,
|
||||
int scene_w, int scene_h, const struct banner_color *color, uint32_t ahb_format);
|
||||
int scene_w, int scene_h, const struct droiddeck_color *color, uint32_t ahb_format);
|
||||
|
||||
/* Vote a panel refresh rate for the layer the game presents on (VRR / refresh-rate matching), the
|
||||
* same rate and compatibility the app votes on its own surface with Surface.setFrameRate; 0 = no
|
||||
|
||||
@@ -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
|
||||
@@ -8,7 +8,7 @@
|
||||
#include <sys/stat.h>
|
||||
#include <android/log.h>
|
||||
|
||||
#define TAG "BannerWayland"
|
||||
#define TAG "DroidDeckWayland"
|
||||
|
||||
struct vk_api g_vk;
|
||||
static void *g_handle;
|
||||
|
||||
@@ -3,12 +3,13 @@
|
||||
#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 "framegen_bridge.h"
|
||||
#include "hdr_compose.h"
|
||||
#include "blend_pass.h"
|
||||
#include "banner_color.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
@@ -19,9 +20,9 @@
|
||||
#include <pthread.h>
|
||||
#include <android/log.h>
|
||||
|
||||
#define TAG "BannerWayland"
|
||||
#define TAG "DroidDeckWayland"
|
||||
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
|
||||
#define LOGE(...) banner_log("error", __VA_ARGS__)
|
||||
#define LOGE(...) droiddeck_log("error", __VA_ARGS__)
|
||||
#define MOD_INVALID VKP_MOD_INVALID
|
||||
|
||||
struct vkp_image {
|
||||
@@ -35,15 +36,18 @@ struct vkp_image {
|
||||
int in_general; /* shm images: moved from PREINITIALIZED to GENERAL */
|
||||
VkFormat fmt;
|
||||
int sampled; /* created with SAMPLED usage: the alpha pass can read it */
|
||||
AHardwareBuffer *android_buffer;
|
||||
};
|
||||
|
||||
static ANativeWindow *g_window; /* the window frames go to; compositor thread only */
|
||||
static char *g_driver_path, *g_library_name, *g_native_lib_dir;
|
||||
static int g_dev_state; /* 0 = not yet, 1 = ok, -1 = failed, -2 = lost (VK_ERROR_DEVICE_LOST) */
|
||||
static int g_dev_state; /* 0 = not yet, 1 = ok, -1 = failed, -2 = lost, -3 = completion unknown */
|
||||
static void device_lost(const char *where);
|
||||
static VkInstance g_inst;
|
||||
static VkPhysicalDevice g_pd;
|
||||
static VkDevice g_dev;
|
||||
static VkQueue g_queue;
|
||||
static PFN_vkGetAndroidHardwareBufferPropertiesANDROID g_ahb_properties;
|
||||
static uint32_t g_qfam;
|
||||
static VkCommandPool g_pool;
|
||||
/* One command buffer + acquire/render-done semaphore pair per PRESENT. A scene frame is one
|
||||
@@ -73,7 +77,7 @@ static VkImage *g_images;
|
||||
static uint32_t g_nimg;
|
||||
static VkExtent2D g_extent;
|
||||
|
||||
static int g_first_frame_done; /* one-shot: fire banner_on_first_frame() on first present */
|
||||
static int g_first_frame_done; /* one-shot: fire droiddeck_on_first_frame() on first present */
|
||||
|
||||
/* The base surface under the display layers (vkp_base_black): 1 once a plain black frame has been
|
||||
* presented on the CURRENT swapchain and nothing else since. Every other present clears it, and so does
|
||||
@@ -112,11 +116,26 @@ static void perf_add(int64_t *sum, int64_t *max, unsigned *count, int64_t d) {
|
||||
if (d > *max) *max = d;
|
||||
(*count)++;
|
||||
}
|
||||
/* A timeout is not device loss and does not cancel a submit. Keep its images
|
||||
* and memory alive until this compositor process exits. Resuming
|
||||
* would reset a pending command buffer/fence or free memory still read by the GPU. */
|
||||
static void quarantine_pending_work(VkResult result, const char *where) {
|
||||
if (g_dev_state != 1) return;
|
||||
g_dev_state = -3;
|
||||
g_base_black = 0;
|
||||
LOGE("GPU completion unconfirmed (%d in %s): presenting stopped; pending resources retained; "
|
||||
"restart DroidDeck", (int)result, where);
|
||||
}
|
||||
|
||||
/* vkWaitForFences on the compositor's own work, timed for the perf line. */
|
||||
static VkResult timed_wait(VkFence fence, uint64_t timeout) {
|
||||
if (g_dev_state != 1)
|
||||
return g_dev_state == -2 ? VK_ERROR_DEVICE_LOST : VK_ERROR_UNKNOWN;
|
||||
int64_t t0 = perf_now();
|
||||
VkResult r = g_vk.WaitForFences(g_dev, 1, &fence, VK_TRUE, timeout);
|
||||
perf_add(&g_perf.wait_ns, &g_perf.wait_max_ns, &g_perf.waits, perf_now() - t0);
|
||||
if (r != VK_SUCCESS && r != VK_ERROR_DEVICE_LOST)
|
||||
quarantine_pending_work(r, "fence wait");
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -160,6 +179,11 @@ static const char *vk_result_name(VkResult r);
|
||||
static pthread_mutex_t g_req_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static ANativeWindow *g_req_window;
|
||||
static int g_req_pending;
|
||||
/* A detach was asked for since the compositor thread last looked. A rebind (null, then the same
|
||||
* window) to rebuild the swapchain at a new size can land in full before the thread gets to it,
|
||||
* and would otherwise read as the same window handed over again - nothing rebuilt, and the old
|
||||
* size's buffers scaled onto the rotated or refolded panel. */
|
||||
static int g_req_detached;
|
||||
|
||||
/* Scale mode + alignment (app values, see vk_present.h); written from any thread, read per frame. */
|
||||
static volatile int g_mode = VKP_MODE_STRETCH, g_align = VKP_ALIGN_CENTER;
|
||||
@@ -179,7 +203,7 @@ static int64_t g_swap_retry_at_ns;
|
||||
static int g_swap_fail_logged;
|
||||
|
||||
/* Implemented in waylandcomp_jni.c - notifies Java (dismiss launch overlay). */
|
||||
extern void banner_on_first_frame(void);
|
||||
extern void droiddeck_on_first_frame(void);
|
||||
|
||||
static char g_gpu_name[VK_MAX_PHYSICAL_DEVICE_NAME_SIZE];
|
||||
const char *vkp_gpu_name(void) { return g_gpu_name; }
|
||||
@@ -231,7 +255,12 @@ static void reset_sync(void) {
|
||||
static void destroy_swapchain(void) {
|
||||
g_base_black = 0; /* a new swapchain starts with nothing on it */
|
||||
if (g_dev_state != 1) return;
|
||||
g_vk.DeviceWaitIdle(g_dev);
|
||||
VkResult idle = g_vk.DeviceWaitIdle(g_dev);
|
||||
if (idle != VK_SUCCESS) {
|
||||
if (idle == VK_ERROR_DEVICE_LOST) device_lost("swapchain idle");
|
||||
else quarantine_pending_work(idle, "swapchain idle");
|
||||
return;
|
||||
}
|
||||
reset_sync();
|
||||
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
|
||||
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
|
||||
@@ -252,6 +281,7 @@ void vk_present_set_window(ANativeWindow *window) {
|
||||
if (g_req_pending && g_req_window && g_req_window != window) superseded = g_req_window;
|
||||
g_req_window = window;
|
||||
g_req_pending = 1;
|
||||
if (!window) g_req_detached = 1;
|
||||
pthread_mutex_unlock(&g_req_lock);
|
||||
if (superseded) ANativeWindow_release(superseded);
|
||||
}
|
||||
@@ -261,13 +291,20 @@ int vkp_apply_window_request(void) {
|
||||
pthread_mutex_lock(&g_req_lock);
|
||||
if (!g_req_pending) { pthread_mutex_unlock(&g_req_lock); return 0; }
|
||||
w = g_req_window;
|
||||
const int detached = g_req_detached;
|
||||
g_req_window = NULL;
|
||||
g_req_pending = 0;
|
||||
g_req_detached = 0;
|
||||
pthread_mutex_unlock(&g_req_lock);
|
||||
if (w == g_window) {
|
||||
/* The same window handed over again (ANativeWindow_fromSurface adds a reference each time). */
|
||||
if (w) ANativeWindow_release(w);
|
||||
return 0;
|
||||
if (!w || !detached) return 0;
|
||||
/* ... after a detach: a rebind for a resized surface. Rebuilt at its size on the next frame. */
|
||||
sc_layer_window_gone();
|
||||
destroy_swapchain();
|
||||
droiddeck_log("gpu", "screen surface rebound: rebuilding the swapchain at its new size");
|
||||
return 1;
|
||||
}
|
||||
sc_layer_window_gone(); /* the layer (if any) belongs to the old window */
|
||||
destroy_swapchain(); /* recreated against the new window on the next frame */
|
||||
@@ -276,7 +313,7 @@ int vkp_apply_window_request(void) {
|
||||
g_window = w;
|
||||
g_swap_retry_at_ns = 0;
|
||||
g_swap_fail_logged = 0;
|
||||
banner_log("gpu", w ? "screen surface attached" : "screen surface gone: presenting paused");
|
||||
droiddeck_log("gpu", w ? "screen surface attached" : "screen surface gone: presenting paused");
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -289,6 +326,7 @@ int vkp_has_window(void) {
|
||||
}
|
||||
|
||||
int vkp_device_lost(void) { return g_dev_state == -2; }
|
||||
int vkp_completion_unknown(void) { return g_dev_state == -3; }
|
||||
|
||||
void vk_present_set_scale_mode(int mode, int alignment) {
|
||||
if (mode < VKP_MODE_OFF || mode > VKP_MODE_INTEGER) mode = VKP_MODE_FIT;
|
||||
@@ -353,7 +391,7 @@ static void update_map(int scene_w, int scene_h) {
|
||||
g_map.off_y = (float)(g_map.ry + (int)((g_map.rh - scene_h * aspect) * 0.5f));
|
||||
}
|
||||
g_map.valid = 1;
|
||||
banner_log("screen", "%s, %s: %dx%d scene shown %dx%d at %d,%d on the %dx%d output",
|
||||
droiddeck_log("screen", "%s, %s: %dx%d scene shown %dx%d at %d,%d on the %dx%d output",
|
||||
mode_name(mode), align_name(align), scene_w, scene_h,
|
||||
(int)(scene_w * g_map.kx + 0.5f), (int)(scene_h * g_map.ky + 0.5f),
|
||||
(int)g_map.off_x, (int)g_map.off_y, W, H);
|
||||
@@ -391,10 +429,10 @@ static int dev_init(void) {
|
||||
const char *inst_exts[3] = {VK_KHR_SURFACE_EXTENSION_NAME,
|
||||
VK_KHR_ANDROID_SURFACE_EXTENSION_NAME, NULL};
|
||||
uint32_t n_inst_exts = 2;
|
||||
/* HDR sessions only (banner_color.h): the colour-space extension lets the swapchain carry HDR10 for
|
||||
/* HDR sessions only (droiddeck_color.h): the colour-space extension lets the swapchain carry HDR10 for
|
||||
* frame generation. Asked for only when the loader has it, and only when HDR was asked for, so
|
||||
* every other session creates exactly the instance it always did. */
|
||||
if (banner_color_requested() && g_vk.EnumerateInstanceExtensionProperties) {
|
||||
if (droiddeck_color_requested() && g_vk.EnumerateInstanceExtensionProperties) {
|
||||
uint32_t ne = 0;
|
||||
g_vk.EnumerateInstanceExtensionProperties(NULL, &ne, NULL);
|
||||
VkExtensionProperties *ie = ne ? calloc(ne, sizeof(*ie)) : NULL;
|
||||
@@ -407,14 +445,14 @@ static int dev_init(void) {
|
||||
}
|
||||
}
|
||||
free(ie);
|
||||
banner_log("color", "compositor instance %s VK_EXT_swapchain_colorspace (an HDR10 swapchain for frame "
|
||||
droiddeck_log("color", "compositor instance %s VK_EXT_swapchain_colorspace (an HDR10 swapchain for frame "
|
||||
"generation %s)", g_colorspace_ext ? "enables" : "has no",
|
||||
g_colorspace_ext ? "is possible where the screen surface offers one" : "is not possible: tone-mapped instead");
|
||||
}
|
||||
/* 1.3 like the X11 renderer's instance: the frame-generation probe (framegen_engine.cpp)
|
||||
* queries VkPhysicalDeviceVulkan12Features, and a 1.1 instance may be answered as 1.1. */
|
||||
VkApplicationInfo app = {.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO,
|
||||
.pApplicationName = "banner-wayland-present",
|
||||
.pApplicationName = "droiddeck-wayland-present",
|
||||
.apiVersion = VK_API_VERSION_1_3};
|
||||
VkInstanceCreateInfo ici = {.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO,
|
||||
.pApplicationInfo = &app,
|
||||
@@ -444,27 +482,50 @@ static int dev_init(void) {
|
||||
VkPhysicalDeviceProperties props;
|
||||
g_vk.GetPhysicalDeviceProperties(g_pd, &props);
|
||||
snprintf(g_gpu_name, sizeof(g_gpu_name), "%s", props.deviceName);
|
||||
banner_log("gpu", "compositor renders on %s with %s", props.deviceName,
|
||||
droiddeck_log("gpu", "compositor renders on %s with %s", props.deviceName,
|
||||
g_library_name ? g_library_name : "the system Vulkan driver");
|
||||
if (g_driver_path) banner_log("gpu", "driver folder %s", g_driver_path);
|
||||
if (g_driver_path) droiddeck_log("gpu", "driver folder %s", g_driver_path);
|
||||
}
|
||||
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
|
||||
|
||||
/* Verify the dmabuf-import extensions are present, and log any that are missing. */
|
||||
const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
|
||||
"VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
|
||||
"VK_KHR_image_format_list", NULL, NULL};
|
||||
uint32_t n_dev_exts = 5;
|
||||
/* The dmabuf-import extensions are enabled only when present (David Cimo, Mali through Venus):
|
||||
* a vendor driver may lack one, and naming it would fail vkCreateDevice and leave the session
|
||||
* with no compositor. On an Adreno's Turnip all five are present, so nothing changes there. */
|
||||
static const char *const wanted_exts[5] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "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] = {0};
|
||||
uint32_t n_dev_exts = 0;
|
||||
uint32_t ne = 0;
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
|
||||
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
|
||||
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
|
||||
for (unsigned i = 0; i < 5; i++)
|
||||
if (!has_ext(exts, ne, dev_exts[i]))
|
||||
LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
|
||||
/* The whole list, once, on a driver that is not Turnip: on a vendor driver it is what Venus
|
||||
* and the bridges can offer the session. Several lines, since a log line holds 512 bytes. */
|
||||
if (!g_library_name || !strstr(g_library_name, "freedreno")) {
|
||||
char names[440];
|
||||
size_t len = 0;
|
||||
names[0] = 0;
|
||||
droiddeck_log("gpu", "device extensions: %u", ne);
|
||||
for (uint32_t i = 0; i < ne; i++) {
|
||||
if (len + strlen(exts[i].extensionName) + 2 > sizeof(names)) {
|
||||
droiddeck_log("gpu", " %s", names);
|
||||
len = 0;
|
||||
names[0] = 0;
|
||||
}
|
||||
len += (size_t)snprintf(names + len, sizeof(names) - len, "%s%s", len ? " " : "", exts[i].extensionName);
|
||||
}
|
||||
if (len) droiddeck_log("gpu", " %s", names);
|
||||
}
|
||||
for (unsigned i = 0; i < 5; i++) {
|
||||
if (has_ext(exts, ne, wanted_exts[i]))
|
||||
dev_exts[n_dev_exts++] = wanted_exts[i];
|
||||
else
|
||||
LOGE("present: driver MISSING %s (dmabuf import will fail)", wanted_exts[i]);
|
||||
}
|
||||
/* HDR sessions only: the HDR10 swapchain (frame generation) can carry the game's metadata. */
|
||||
int want_hdr_md = 0;
|
||||
if (banner_color_requested()) {
|
||||
if (droiddeck_color_requested()) {
|
||||
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
|
||||
if (want_hdr_md) dev_exts[n_dev_exts++] = VK_EXT_HDR_METADATA_EXTENSION_NAME;
|
||||
}
|
||||
@@ -472,6 +533,13 @@ static int dev_init(void) {
|
||||
* back to waiting for them on the CPU without it. */
|
||||
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;
|
||||
const int want_ahb = !g_library_name &&
|
||||
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 (want_ahb) {
|
||||
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
|
||||
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
|
||||
}
|
||||
free(exts);
|
||||
|
||||
float prio = 1.0f;
|
||||
@@ -487,7 +555,7 @@ static int dev_init(void) {
|
||||
.enabledExtensionCount = n_dev_exts, .ppEnabledExtensionNames = dev_exts};
|
||||
VkResult dr = g_vk.CreateDevice(g_pd, &dci, NULL, &g_dev);
|
||||
if (dr != VK_SUCCESS && fg_features) {
|
||||
banner_log("framegen", "the driver refused the LSFG feature set (%s); device created without it",
|
||||
droiddeck_log("framegen", "the driver refused the LSFG feature set (%s); device created without it",
|
||||
vk_result_name(dr));
|
||||
dci.pNext = NULL;
|
||||
fg_features = NULL;
|
||||
@@ -498,6 +566,9 @@ static int dev_init(void) {
|
||||
}
|
||||
vk_loader_load_device(g_dev);
|
||||
g_vk.GetDeviceQueue(g_dev, g_qfam, 0, &g_queue);
|
||||
if (want_ahb)
|
||||
g_ahb_properties = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)
|
||||
g_vk.GetDeviceProcAddr(g_dev, "vkGetAndroidHardwareBufferPropertiesANDROID");
|
||||
if (want_sem_fd) {
|
||||
g_import_sem_fd = (PFN_vkImportSemaphoreFdKHR)g_vk.GetDeviceProcAddr(g_dev, "vkImportSemaphoreFdKHR");
|
||||
VkSemaphoreCreateInfo wsci = {.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
|
||||
@@ -506,13 +577,13 @@ static int dev_init(void) {
|
||||
g_wait_sem = VK_NULL_HANDLE;
|
||||
}
|
||||
}
|
||||
banner_log("perf", "layer buffers: the display's release fences are waited for %s",
|
||||
droiddeck_log("perf", "layer buffers: the display's release fences are waited for %s",
|
||||
g_import_sem_fd ? "on the GPU (VK_KHR_external_semaphore_fd)"
|
||||
: "on the CPU (this driver has no VK_KHR_external_semaphore_fd)");
|
||||
if (want_hdr_md)
|
||||
g_set_hdr_metadata = (PFN_vkSetHdrMetadataEXT)g_vk.GetDeviceProcAddr(g_dev, "vkSetHdrMetadataEXT");
|
||||
if (banner_color_requested())
|
||||
banner_log("color", "compositor device %s VK_EXT_hdr_metadata (the HDR10 swapchain for frame generation %s)",
|
||||
if (droiddeck_color_requested())
|
||||
droiddeck_log("color", "compositor device %s VK_EXT_hdr_metadata (the HDR10 swapchain for frame generation %s)",
|
||||
g_set_hdr_metadata ? "enables" : "has no",
|
||||
g_set_hdr_metadata ? "carries the game's mastering metadata" : "goes without the game's metadata");
|
||||
|
||||
@@ -533,6 +604,7 @@ static int dev_init(void) {
|
||||
g_dev_state = 1;
|
||||
reset_sync();
|
||||
init_black_image();
|
||||
if (g_dev_state != 1) return -1;
|
||||
vkp_framegen_device_ready(g_dev, g_queue, g_qfam, fg_features != NULL);
|
||||
return 0;
|
||||
}
|
||||
@@ -544,7 +616,7 @@ static int swap_init_locked(void);
|
||||
static int swap_init(void) {
|
||||
struct timespec ts;
|
||||
int64_t now;
|
||||
if (!g_window) return -1;
|
||||
if (!g_window || g_dev_state != 1) return -1;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
now = (int64_t)ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
if (now < g_swap_retry_at_ns) return -1;
|
||||
@@ -641,7 +713,7 @@ static void log_surface_formats(const VkSurfaceFormatKHR *f, uint32_t n) {
|
||||
vk_colorspace_short(f[i].colorSpace));
|
||||
else hdr_cut++;
|
||||
}
|
||||
banner_log("color", "screen surface lists %u format/colour-space pairs (%s); HDR-capable: %s%s", n, per,
|
||||
droiddeck_log("color", "screen surface lists %u format/colour-space pairs (%s); HDR-capable: %s%s", n, per,
|
||||
hdr_n ? hdr : "none", hdr_cut ? " (+more)" : "");
|
||||
}
|
||||
|
||||
@@ -678,7 +750,7 @@ static int swap_init_locked(void) {
|
||||
}
|
||||
VkSurfaceFormatKHR chosen = fmts[0];
|
||||
const VkSurfaceFormatKHR sdr_choice = fmts[0];
|
||||
if (banner_color_requested() && (!g_surface_formats_said || g_swap_hdr_want)) {
|
||||
if (droiddeck_color_requested() && (!g_surface_formats_said || g_swap_hdr_want)) {
|
||||
g_surface_formats_said = 1;
|
||||
log_surface_formats(fmts, nfmt);
|
||||
}
|
||||
@@ -702,13 +774,13 @@ static int swap_init_locked(void) {
|
||||
g_swap_is_hdr = 1;
|
||||
char fname[24];
|
||||
vk_format_short(chosen.format, fname, sizeof(fname));
|
||||
banner_log("color", "screen swapchain built as HDR10 (format %d %s, HDR10_ST2084): frame-generated HDR "
|
||||
droiddeck_log("color", "screen swapchain built as HDR10 (format %d %s, HDR10_ST2084): frame-generated HDR "
|
||||
"frames reach the display as PQ BT.2020%s", (int)chosen.format, fname,
|
||||
vk_format_bits(chosen.format) <= 8 ? " - an 8-bit swapchain: banding possible in smooth gradients"
|
||||
: "");
|
||||
} else {
|
||||
g_swap_hdr_unavailable = 1;
|
||||
banner_log("color", "the screen surface lists no HDR10 swapchain format among its %u format/colour-space "
|
||||
droiddeck_log("color", "the screen surface lists no HDR10 swapchain format among its %u format/colour-space "
|
||||
"pairs (see the line above): frames with frame generation are tone-mapped to SDR instead",
|
||||
nfmt);
|
||||
}
|
||||
@@ -748,7 +820,7 @@ static int swap_init_locked(void) {
|
||||
if (cr != VK_SUCCESS && g_swap_is_hdr) {
|
||||
/* The surface listed the HDR10 pair but refused the swapchain: say so, never ask again this
|
||||
* surface, and build the ordinary one now (frames tone-mapped) - never a black screen. */
|
||||
banner_log("color", "the driver refused the HDR10 swapchain (%s): frames with frame generation are "
|
||||
droiddeck_log("color", "the driver refused the HDR10 swapchain (%s): frames with frame generation are "
|
||||
"tone-mapped to SDR instead", vk_result_name(cr));
|
||||
g_swap_is_hdr = 0;
|
||||
g_swap_hdr_unavailable = 1;
|
||||
@@ -767,7 +839,7 @@ static int swap_init_locked(void) {
|
||||
g_images = calloc(g_nimg, sizeof(VkImage));
|
||||
g_vk.GetSwapchainImagesKHR(g_dev, g_swapchain, &g_nimg, g_images);
|
||||
|
||||
banner_log("gpu", "screen output %ux%u, %u buffers, vsync%s", g_extent.width, g_extent.height, g_nimg,
|
||||
droiddeck_log("gpu", "screen output %ux%u, %u buffers, vsync%s", g_extent.width, g_extent.height, g_nimg,
|
||||
g_swap_extra ? " (frame generation: several presents per frame)" : "");
|
||||
return 0;
|
||||
}
|
||||
@@ -829,11 +901,16 @@ static void init_black_image(void) {
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
|
||||
g_vk.ResetFences(g_dev, 1, &g_fence);
|
||||
if (g_vk.QueueSubmit(g_queue, 1, &si, g_fence) == VK_SUCCESS &&
|
||||
g_vk.WaitForFences(g_dev, 1, &g_fence, VK_TRUE, 1000000000ULL) == VK_SUCCESS)
|
||||
g_black_state = 1;
|
||||
else
|
||||
banner_log("gpu", "letterbox black image unavailable: the whole output is cleared every copy-path frame");
|
||||
VkResult qr = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
if (qr == VK_SUCCESS) {
|
||||
VkResult fr = timed_wait(g_fence, 1000000000ULL);
|
||||
if (fr == VK_SUCCESS) g_black_state = 1;
|
||||
else if (fr == VK_ERROR_DEVICE_LOST) device_lost("black image");
|
||||
} else if (qr == VK_ERROR_DEVICE_LOST) {
|
||||
device_lost("black image submit");
|
||||
}
|
||||
if (g_black_state != 1)
|
||||
droiddeck_log("gpu", "letterbox black image unavailable: the whole output is cleared every copy-path frame");
|
||||
}
|
||||
|
||||
/* Blit the black image over everything of swapchain image `img` (in TRANSFER_DST_OPTIMAL) OUTSIDE the
|
||||
@@ -936,7 +1013,98 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
|
||||
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
|
||||
}
|
||||
|
||||
int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
|
||||
/* Return client sources to FOREIGN after their final read. The consuming paths
|
||||
* wait for our fence before Wayland can release an ordinary dma-buf or an
|
||||
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
|
||||
* these image-layout and ownership transfers. */
|
||||
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
|
||||
struct vkp_external_client_barrier_pair pair;
|
||||
if (!img || !vkp_external_client_barrier_pair(
|
||||
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
|
||||
return;
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
|
||||
}
|
||||
|
||||
static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
|
||||
for (int i = 0; i < count; i++) {
|
||||
int seen = 0;
|
||||
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
|
||||
if (!seen) release_external_client_image(cmd, draws[i].img);
|
||||
}
|
||||
}
|
||||
|
||||
int vkp_image_is_dmabuf(const struct vkp_image *img) {
|
||||
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
|
||||
}
|
||||
|
||||
int vkp_android_buffer_supported(void) {
|
||||
return dev_init() == 0 && g_ahb_properties != NULL;
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
|
||||
if (!buffer || !vkp_android_buffer_supported()) return NULL;
|
||||
AHardwareBuffer_Desc desc;
|
||||
AHardwareBuffer_describe(buffer, &desc);
|
||||
if (!desc.width || !desc.height || desc.layers != 1 ||
|
||||
(desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
|
||||
!(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
|
||||
VkAndroidHardwareBufferFormatPropertiesANDROID format = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
|
||||
VkAndroidHardwareBufferPropertiesANDROID props = {
|
||||
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
|
||||
VkResult result = g_ahb_properties(g_dev, buffer, &props);
|
||||
if (result != VK_SUCCESS ||
|
||||
(format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
|
||||
format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
|
||||
!props.memoryTypeBits ||
|
||||
!(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
|
||||
LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
|
||||
vk_result_name(result), format.format);
|
||||
return NULL;
|
||||
}
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
img->w = (int)desc.width; img->h = (int)desc.height;
|
||||
img->fmt = format.format; img->dmabuf = 1;
|
||||
const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
|
||||
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
|
||||
img->sampled = (format.formatFeatures & sampled) == sampled;
|
||||
VkExternalMemoryImageCreateInfo external = {
|
||||
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
|
||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
|
||||
VkImageCreateInfo create = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
|
||||
.extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
/* AHB image requirements are not queryable before binding. The AHB query supplies them. */
|
||||
uint32_t memory_type = 0;
|
||||
while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
|
||||
VkImportAndroidHardwareBufferInfoANDROID import = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
|
||||
VkMemoryDedicatedAllocateInfo dedicated = {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
|
||||
.pNext = &import, .image = img->image};
|
||||
VkMemoryAllocateInfo allocate = {
|
||||
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
|
||||
.allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
|
||||
result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
|
||||
if (result != VK_SUCCESS) goto fail;
|
||||
AHardwareBuffer_acquire(buffer);
|
||||
img->android_buffer = buffer;
|
||||
return img;
|
||||
fail:
|
||||
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
|
||||
vkp_image_destroy(img);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
|
||||
uint32_t stride, uint32_t offset, int as_blit_dst) {
|
||||
@@ -950,7 +1118,27 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
|
||||
img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
|
||||
modifier_importable(img->fmt, modifier, sampled_usage);
|
||||
/* Each new format/modifier/size a client hands over, once, for the graphics report: a colour
|
||||
* or swizzle mismatch on a non-Adreno driver shows up as the pair it arrived as. */
|
||||
{
|
||||
static struct { uint32_t fmt; uint64_t mod; int w, h; } seen[32];
|
||||
static int nseen;
|
||||
int known = 0;
|
||||
for (int i = 0; i < nseen; i++)
|
||||
if (seen[i].fmt == drm_format && seen[i].mod == modifier && seen[i].w == w && seen[i].h == h) known = 1;
|
||||
if (!known && nseen < 32) {
|
||||
seen[nseen].fmt = drm_format; seen[nseen].mod = modifier; seen[nseen].w = w; seen[nseen].h = h; nseen++;
|
||||
droiddeck_log("gpu", "dmabuf import: %c%c%c%c %s %dx%d stride %u offset %u -> vk format %d, %s%s",
|
||||
drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff, (drm_format >> 24) & 0xff,
|
||||
vkp_modifier_name(modifier), w, h, stride, offset, (int)img->fmt,
|
||||
img->sampled ? "sampled" : "copied", as_blit_dst ? ", blit target" : "");
|
||||
}
|
||||
}
|
||||
|
||||
/* Venus reports a row pitch of 0 for gamescope's 1x1 root buffer, and a zero pitch fails
|
||||
* vkCreateImage, which left the whole window unshown (David Cimo). One packed, 64-byte aligned
|
||||
* row is what a linear buffer that small holds. */
|
||||
if (stride == 0 && modifier == 0) stride = ((uint32_t)w * 4 + 63) & ~63u;
|
||||
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
|
||||
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_DRM_FORMAT_MODIFIER_EXPLICIT_CREATE_INFO_EXT,
|
||||
@@ -971,7 +1159,7 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
LOGE("%s: vkCreateImage(%s, %dx%d, pitch %u, offset %u) -> %s%s", as_blit_dst ? "layer" : "dmabuf",
|
||||
vkp_modifier_name(modifier), w, h, stride, offset, vk_result_name(cr),
|
||||
(!as_blit_dst && modifier == VKP_MOD_QCOM_COMPRESSED)
|
||||
? ": the game's UBWC layout was refused; BANNER_WAYLAND_UBWC=0 forces linear buffers" : "");
|
||||
? ": the game's UBWC layout was refused; DROIDDECK_WAYLAND_UBWC=0 forces linear buffers" : "");
|
||||
free(img); return NULL;
|
||||
}
|
||||
|
||||
@@ -1071,10 +1259,10 @@ struct vkp_image *vkp_image_create_shm(int w, int h) {
|
||||
return img;
|
||||
}
|
||||
|
||||
/* Renders are synchronous (we wait for the frame's fence), so writing between frames
|
||||
* never races the GPU. */
|
||||
/* Between successfully completed frames the GPU is idle. After an unconfirmed
|
||||
* wait, retain the mapped bytes too: the previous submit may still read them. */
|
||||
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride) {
|
||||
if (!img || !img->map || !data) return;
|
||||
if (g_dev_state != 1 || !img || !img->map || !data) return;
|
||||
size_t rowbytes = (size_t)img->w * 4;
|
||||
if ((size_t)stride < rowbytes) rowbytes = (size_t)stride;
|
||||
for (int y = 0; y < img->h; y++)
|
||||
@@ -1087,12 +1275,14 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; }
|
||||
|
||||
void vkp_image_destroy(struct vkp_image *img) {
|
||||
if (!img) return;
|
||||
if (g_dev_state == -3) return; /* completion unknown: retain GPU ownership */
|
||||
if (g_dev) {
|
||||
blendp_forget_image(img->image);
|
||||
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
|
||||
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
|
||||
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
|
||||
}
|
||||
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
|
||||
free(img);
|
||||
}
|
||||
|
||||
@@ -1142,15 +1332,19 @@ 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);
|
||||
}
|
||||
|
||||
static void destroy_scene_image(void) {
|
||||
if (g_scene.img) vkp_effects_forget_image(g_scene.img);
|
||||
if (g_scene.img) hdrc_forget_image(g_scene.img); /* the HDR pass may have drawn into it */
|
||||
if (g_scene.img) blendp_forget_image(g_scene.img);
|
||||
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
|
||||
@@ -1182,7 +1376,7 @@ static int ensure_scene_image(int w, int h) {
|
||||
if (r != VK_SUCCESS) { LOGE("effects: scene image %dx%d: vkAllocateMemory %s", w, h, vk_result_name(r)); destroy_scene_image(); return -1; }
|
||||
g_vk.BindImageMemory(g_dev, g_scene.img, g_scene.mem, 0);
|
||||
g_scene.w = w; g_scene.h = h;
|
||||
banner_log("effects", "scene image %dx%d for the effect chain", w, h);
|
||||
droiddeck_log("effects", "scene image %dx%d for the effect chain", w, h);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1190,6 +1384,7 @@ static int ensure_scene_image(int w, int h) {
|
||||
static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImageUsageFlags usage, const char *what) {
|
||||
if (s->img && s->w == w && s->h == h && s->fmt == fmt) return 0;
|
||||
if (s->img) hdrc_forget_image(s->img);
|
||||
if (s->img) vkp_effects_forget_image(s->img);
|
||||
if (s->img) blendp_forget_image(s->img);
|
||||
if (s->img) g_vk.DestroyImage(g_dev, s->img, NULL);
|
||||
if (s->mem) g_vk.FreeMemory(g_dev, s->mem, NULL);
|
||||
@@ -1218,7 +1413,7 @@ static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImag
|
||||
s->w = w; s->h = h; s->fmt = fmt;
|
||||
char fname[24];
|
||||
vk_format_short(fmt, fname, sizeof(fname));
|
||||
banner_log("color", "%s image %dx%d (%s)", what, w, h, fname);
|
||||
droiddeck_log("color", "%s image %dx%d (%s)", what, w, h, fname);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1249,7 +1444,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
|
||||
.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT};
|
||||
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &mb, 0, NULL, 0, NULL);
|
||||
|
||||
struct hdrc_params p = {.mode = mode, .sdr_white_nits = banner_color_sdr_white(),
|
||||
struct hdrc_params p = {.mode = mode, .sdr_white_nits = droiddeck_color_sdr_white(),
|
||||
.peak_nits = hf->peak_nits > 0.0f ? hf->peak_nits : 1000.0f};
|
||||
int lowest_hdr = -1;
|
||||
for (int i = 0; i < n; i++) {
|
||||
@@ -1272,7 +1467,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
|
||||
}
|
||||
if (i >= lowest_hdr && !truncated_said) {
|
||||
truncated_said = 1;
|
||||
banner_log("color", "HDR composition: more than %d windows are stacked over the HDR game - the lowest "
|
||||
droiddeck_log("color", "HDR composition: more than %d windows are stacked over the HDR game - the lowest "
|
||||
"ones are treated as SDR", HDRC_MAX_RECTS);
|
||||
}
|
||||
}
|
||||
@@ -1287,7 +1482,7 @@ static void device_lost(const char *where) {
|
||||
g_dev_state = -2;
|
||||
g_base_black = 0;
|
||||
vkp_framegen_device_lost();
|
||||
banner_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
|
||||
droiddeck_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
|
||||
"restart the session", where);
|
||||
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
|
||||
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
|
||||
@@ -1376,6 +1571,7 @@ static void record_screen_blit(VkCommandBuffer cmd, VkImage src, int src_w, int
|
||||
* so they never rebuild; they fail and the frame ends early. 0 on success. */
|
||||
static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
|
||||
for (int attempt = 0; ; attempt++) {
|
||||
if (g_dev_state != 1) return -1;
|
||||
if (!g_swapchain && (!first || swap_init() != 0)) return -1;
|
||||
/* A bounded wait: a surface that went away without telling us must not park the
|
||||
* compositor thread forever (clients are paced from this thread). */
|
||||
@@ -1385,12 +1581,12 @@ static int acquire_image(int k, int first, uint32_t *img, VkResult *ar_out) {
|
||||
if (ar == VK_SUCCESS || ar == VK_SUBOPTIMAL_KHR) { *ar_out = ar; return 0; }
|
||||
if (ar == VK_ERROR_DEVICE_LOST) { device_lost("acquire"); return -1; }
|
||||
if (ar == VK_ERROR_OUT_OF_DATE_KHR || ar == VK_ERROR_SURFACE_LOST_KHR) {
|
||||
banner_log("gpu", "screen surface %s on acquire: rebuilding the swapchain", vk_result_name(ar));
|
||||
droiddeck_log("gpu", "screen surface %s on acquire: rebuilding the swapchain", vk_result_name(ar));
|
||||
destroy_swapchain();
|
||||
if (first && attempt == 0) continue;
|
||||
if (first && attempt == 0 && g_dev_state == 1) continue;
|
||||
return -1;
|
||||
}
|
||||
banner_log("error", "present: acquire %d failed (%s %d)", k, vk_result_name(ar), (int)ar);
|
||||
droiddeck_log("error", "present: acquire %d failed (%s %d)", k, vk_result_name(ar), (int)ar);
|
||||
if (ar == VK_TIMEOUT || ar == VK_NOT_READY) return -1;
|
||||
destroy_swapchain(); /* anything else: start over next frame */
|
||||
return -1;
|
||||
@@ -1422,7 +1618,7 @@ static void check_surface_changed(void) {
|
||||
if (caps.currentExtent.width == g_caps_extent.width && caps.currentExtent.height == g_caps_extent.height &&
|
||||
caps.currentTransform == g_surface_transform)
|
||||
return;
|
||||
banner_log("gpu", "screen surface changed (%ux%u -> %ux%u, transform %d -> %d): rebuilding the swapchain",
|
||||
droiddeck_log("gpu", "screen surface changed (%ux%u -> %ux%u, transform %d -> %d): rebuilding the swapchain",
|
||||
g_caps_extent.width, g_caps_extent.height, caps.currentExtent.width, caps.currentExtent.height,
|
||||
(int)g_surface_transform, (int)caps.currentTransform);
|
||||
destroy_swapchain();
|
||||
@@ -1464,7 +1660,7 @@ static int take_wait_fd(int fd) {
|
||||
static int said;
|
||||
if (!said) {
|
||||
said = 1;
|
||||
banner_log("perf", "layer buffers: importing a release fence as a GPU wait failed; waiting for it on the CPU");
|
||||
droiddeck_log("perf", "layer buffers: importing a release fence as a GPU wait failed; waiting for it on the CPU");
|
||||
}
|
||||
}
|
||||
struct pollfd p = {.fd = fd, .events = POLLIN};
|
||||
@@ -1476,18 +1672,18 @@ static int take_wait_fd(int fd) {
|
||||
|
||||
/* The HDR10 swapchain's metadata: the game's SMPTE 2086 / CTA-861.3 values (its image description) via
|
||||
* VK_EXT_hdr_metadata, once per swapchain and description. A game that gave none gets none. */
|
||||
static void send_hdr_metadata(const struct banner_color *c) {
|
||||
static void send_hdr_metadata(const struct droiddeck_color *c) {
|
||||
static int said_none, said_nodesc;
|
||||
if (!c) return;
|
||||
if (!g_set_hdr_metadata) {
|
||||
if (!said_none) { said_none = 1; banner_log("color", "HDR10 swapchain without the game's metadata: this device "
|
||||
if (!said_none) { said_none = 1; droiddeck_log("color", "HDR10 swapchain without the game's metadata: this device "
|
||||
"has no VK_EXT_hdr_metadata (the display uses its defaults)"); }
|
||||
return;
|
||||
}
|
||||
if (!c->has_st2086 && !c->has_cta861) {
|
||||
if (said_nodesc != (int)c->identity) {
|
||||
said_nodesc = (int)c->identity;
|
||||
banner_log("color", "HDR10 swapchain: image description #%u carries no HDR metadata (the game sent none), "
|
||||
droiddeck_log("color", "HDR10 swapchain: image description #%u carries no HDR metadata (the game sent none), "
|
||||
"so none is set - the display uses its defaults", c->identity);
|
||||
}
|
||||
return;
|
||||
@@ -1506,7 +1702,7 @@ static void send_hdr_metadata(const struct banner_color *c) {
|
||||
md.maxFrameAverageLightLevel = c->max_fall;
|
||||
}
|
||||
g_set_hdr_metadata(g_dev, 1, &g_swapchain, &md);
|
||||
banner_log("color", "HDR10 swapchain: the game's metadata set via VK_EXT_hdr_metadata (image description #%u: %s)",
|
||||
droiddeck_log("color", "HDR10 swapchain: the game's metadata set via VK_EXT_hdr_metadata (image description #%u: %s)",
|
||||
c->identity, c->text);
|
||||
}
|
||||
|
||||
@@ -1515,14 +1711,16 @@ static void send_hdr_metadata(const struct banner_color *c) {
|
||||
static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, int n,
|
||||
const struct vkp_hdr_frame *hf, int *how) {
|
||||
if (how) *how = 0;
|
||||
if (g_dev_state < 0) return -1;
|
||||
vkp_apply_window_request();
|
||||
check_surface_changed(); /* a rotation or a fold the rebind did not cover: rebuild at the new size */
|
||||
if (g_dev_state == -2) return -1;
|
||||
if (dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
|
||||
/* Frame generation queues several presents per scene frame and needs swapchain images for
|
||||
* them: rebuild when that changes (armed, disarmed, another multiplier). */
|
||||
if (g_swapchain && vkp_framegen_extra_images() != g_swap_extra) {
|
||||
banner_log("gpu", "frame generation now wants %d present%s per frame: rebuilding the swapchain",
|
||||
droiddeck_log("gpu", "frame generation now wants %d present%s per frame: rebuilding the swapchain",
|
||||
1 + vkp_framegen_extra_images(), vkp_framegen_extra_images() ? "s" : "");
|
||||
destroy_swapchain();
|
||||
}
|
||||
@@ -1531,11 +1729,12 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
* swapchain (only in HDR sessions: g_colorspace_ext). */
|
||||
const int want_hdr = hf && !hf->tonemap && g_colorspace_ext && !g_swap_hdr_unavailable;
|
||||
if (g_swapchain && want_hdr != g_swap_is_hdr) {
|
||||
banner_log("color", want_hdr ? "HDR frames with frame generation: rebuilding the screen swapchain as HDR10"
|
||||
droiddeck_log("color", want_hdr ? "HDR frames with frame generation: rebuilding the screen swapchain as HDR10"
|
||||
: hf ? "HDR output switched off: rebuilding the screen swapchain as SDR (frames tone-mapped)"
|
||||
: "no HDR frames through the screen swapchain any more: rebuilding it as SDR");
|
||||
destroy_swapchain();
|
||||
}
|
||||
if (g_dev_state != 1) return -1;
|
||||
g_swap_hdr_want = want_hdr;
|
||||
|
||||
uint32_t img = 0;
|
||||
@@ -1570,10 +1769,10 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
char sw[24];
|
||||
vk_format_short(g_swap_fmt, sw, sizeof(sw));
|
||||
if (deep)
|
||||
banner_log("color", "frame generation runs on the HDR picture in FP16 (RGBA16F): more than 8 bits of PQ "
|
||||
droiddeck_log("color", "frame generation runs on the HDR picture in FP16 (RGBA16F): more than 8 bits of PQ "
|
||||
"through interpolation, into the HDR10 swapchain (%s)", sw);
|
||||
else
|
||||
banner_log("color", "frame generation runs on the HDR picture in 8 bits (the engine cannot take FP16 here), "
|
||||
droiddeck_log("color", "frame generation runs on the HDR picture in 8 bits (the engine cannot take FP16 here), "
|
||||
"into the HDR10 swapchain (%s): banding possible in smooth gradients", sw);
|
||||
}
|
||||
}
|
||||
@@ -1609,13 +1808,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,
|
||||
@@ -1682,6 +1879,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;
|
||||
@@ -1746,7 +1944,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
if (k > 0) {
|
||||
VkResult ark;
|
||||
if (acquire_image(k, 0, &img, &ark) != 0) {
|
||||
banner_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents);
|
||||
/* Teardown may have retained this frame's pending work, or
|
||||
* acquire may have reported real device loss. Neither permits
|
||||
* a completion-marker submit or another fence wait. */
|
||||
if (g_dev_state != 1) return -1;
|
||||
droiddeck_log("framegen", "present %d/%d: no swapchain image; the frame ends early", k + 1, presents);
|
||||
pr = VK_ERROR_OUT_OF_DATE_KHR;
|
||||
break;
|
||||
}
|
||||
@@ -1778,20 +1980,27 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
pr = g_vk.QueuePresentKHR(g_queue, &pi);
|
||||
perf_add(&g_perf.present_ns, &g_perf.present_max_ns, &g_perf.presents, perf_now() - t_pres);
|
||||
if (k < ngen) presented_gen++;
|
||||
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR || pr == VK_ERROR_DEVICE_LOST) break;
|
||||
if (pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
|
||||
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) break;
|
||||
}
|
||||
if (!fence_submitted) {
|
||||
/* Ended early: an empty submit carrying the fence is ordered after everything queued
|
||||
* above, so the wait below still means "this frame's work is done". */
|
||||
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO};
|
||||
g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
VkResult marker = g_vk.QueueSubmit(g_queue, 1, &si, g_fence);
|
||||
if (marker != VK_SUCCESS) {
|
||||
if (marker == VK_ERROR_DEVICE_LOST) device_lost("frame completion submit");
|
||||
else quarantine_pending_work(marker, "frame completion submit");
|
||||
return -1; /* no fence was submitted; never wait on its unsignalled state */
|
||||
}
|
||||
}
|
||||
VkResult fr = timed_wait(g_fence, UINT64_MAX);
|
||||
if (fg) vkp_framegen_presented(presented_gen);
|
||||
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
|
||||
if (fr != VK_SUCCESS) return -1;
|
||||
if (fg) vkp_framegen_presented(presented_gen);
|
||||
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) {
|
||||
/* The surface changed or went away under this frame: rebuild before the next one. */
|
||||
banner_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr));
|
||||
droiddeck_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr));
|
||||
destroy_swapchain();
|
||||
return -1;
|
||||
} else if (pr == VK_SUBOPTIMAL_KHR || ar == VK_SUBOPTIMAL_KHR) {
|
||||
@@ -1799,9 +2008,9 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
* swap_init), so a rotated panel reports SUBOPTIMAL on every frame. Rebuilding would change
|
||||
* nothing (and a rebuild per frame would be far worse), so present as is; say so once. */
|
||||
static int said;
|
||||
if (!said) { said = 1; banner_log("gpu", "surface reports SUBOPTIMAL (panel rotation); presenting as is"); }
|
||||
if (!said) { said = 1; droiddeck_log("gpu", "surface reports SUBOPTIMAL (panel rotation); presenting as is"); }
|
||||
} else if (pr != VK_SUCCESS) {
|
||||
banner_log("error", "present: vkQueuePresentKHR failed (%s %d)", vk_result_name(pr), (int)pr);
|
||||
droiddeck_log("error", "present: vkQueuePresentKHR failed (%s %d)", vk_result_name(pr), (int)pr);
|
||||
destroy_swapchain();
|
||||
return -1;
|
||||
}
|
||||
@@ -1815,7 +2024,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
* launch/preloader overlay can dismiss (wayland has no XServer window-content hook). */
|
||||
if (drawn && !g_first_frame_done) {
|
||||
g_first_frame_done = 1;
|
||||
banner_on_first_frame();
|
||||
droiddeck_on_first_frame();
|
||||
}
|
||||
if (how) *how = hdr_how;
|
||||
return 0;
|
||||
@@ -1856,12 +2065,13 @@ void vkp_reset_first_frame(void) {
|
||||
void vkp_signal_first_frame(void) {
|
||||
if (g_first_frame_done) return;
|
||||
g_first_frame_done = 1;
|
||||
banner_on_first_frame();
|
||||
droiddeck_on_first_frame();
|
||||
}
|
||||
|
||||
int vkp_update_map(int scene_w, int scene_h) {
|
||||
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
check_surface_changed(); /* layer mode may present nothing on the base surface for a long time */
|
||||
if (g_dev_state != 1) return -1;
|
||||
if (!g_swapchain && swap_init() != 0) return -1;
|
||||
update_map(scene_w, scene_h);
|
||||
return g_map.valid ? 0 : -1;
|
||||
@@ -1887,7 +2097,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
|
||||
* owned by the "foreign" queue family (the game's driver / the display) between our uses, so each
|
||||
* use acquires them and the destination is released back for the display to read. */
|
||||
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;
|
||||
}
|
||||
@@ -1900,17 +2110,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) { /* shm image: host-written, GENERAL */
|
||||
if (!src_external) { /* shm image: host-written, GENERAL */
|
||||
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;
|
||||
@@ -1924,8 +2138,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,
|
||||
@@ -1960,7 +2175,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
|
||||
static struct vkp_image *g_rb; /* the readback image, kept for the next shape */
|
||||
|
||||
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; }
|
||||
@@ -2001,11 +2216,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,
|
||||
@@ -2023,16 +2242,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},
|
||||
/* the client's buffer goes back to it */
|
||||
{.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);
|
||||
@@ -2099,6 +2322,8 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
const struct vkp_hdr_frame *hf, int *rw, int *rh) {
|
||||
if (g_pass.active) vkp_pass_abort();
|
||||
if (g_dev_state == -2 || dev_init() != 0 || !g_window || scene_w <= 0 || scene_h <= 0) return -1;
|
||||
check_surface_changed(); /* as in render_impl: the effects pass maps onto the output's size */
|
||||
if (g_dev_state != 1) return -1;
|
||||
if (!g_swapchain && swap_init() != 0) return -1; /* the mapping is in output pixels */
|
||||
update_map(scene_w, scene_h);
|
||||
if (!g_map.valid) return -1;
|
||||
@@ -2134,13 +2359,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,
|
||||
@@ -2181,6 +2404,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,
|
||||
@@ -2194,8 +2418,9 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
|
||||
if (!g_pass.active) { if (wait_fd >= 0) close(wait_fd); return -1; }
|
||||
g_pass.active = 0;
|
||||
if (g_dev_state != 1) { if (wait_fd >= 0) close(wait_fd); return -1; }
|
||||
VkCommandBuffer cmd = g_cmds[0];
|
||||
if (!dst || !dst->blit_dst || g_dev_state == -2) {
|
||||
if (!dst || !dst->blit_dst) {
|
||||
if (wait_fd >= 0) close(wait_fd);
|
||||
g_vk.EndCommandBuffer(cmd);
|
||||
return -1;
|
||||
@@ -2250,5 +2475,6 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd) {
|
||||
void vkp_pass_abort(void) {
|
||||
if (!g_pass.active) return;
|
||||
g_pass.active = 0;
|
||||
g_vk.EndCommandBuffer(g_cmds[0]); /* never submitted; the buffer is reset before its next use */
|
||||
if (g_dev_state == 1)
|
||||
g_vk.EndCommandBuffer(g_cmds[0]); /* never submitted; reset before its next use */
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#define VK_PRESENT_H
|
||||
#include <stdint.h>
|
||||
#include <android/native_window.h>
|
||||
#include <android/hardware_buffer.h>
|
||||
/*
|
||||
* Android-surface render backend for the embedded Wayland compositor.
|
||||
* Owns a Turnip VkDevice + a swapchain on the SurfaceView's ANativeWindow. Each
|
||||
@@ -39,6 +40,11 @@ void vkp_output_size(int *w, int *h);
|
||||
|
||||
struct vkp_image;
|
||||
|
||||
/* android_wlegl clients share complete Android buffer handles, not guessed DMA-BUF layouts.
|
||||
* The image retains its own AHB reference. Call only from the compositor thread. */
|
||||
int vkp_android_buffer_supported(void);
|
||||
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
|
||||
|
||||
/* DRM format modifiers this backend knows the memory layout of (both single-plane on Adreno):
|
||||
* LINEAR, and QCOM_COMPRESSED = UBWC (drm_fourcc.h: fourcc_mod_code(QCOM = 0x05, 1)). */
|
||||
#define VKP_MOD_LINEAR 0x0000000000000000ULL
|
||||
@@ -91,6 +97,10 @@ int vkp_ready(void);
|
||||
int vkp_has_window(void);
|
||||
/* 1 once the Vulkan device was lost: nothing is presented any more (the session must restart). */
|
||||
int vkp_device_lost(void);
|
||||
/* Compositor thread only. Submitted reads may still be pending: retain imported
|
||||
* buffer references and withhold DMA-BUF releases until the app process exits.
|
||||
* This terminal state is distinct from genuine device loss. */
|
||||
int vkp_completion_unknown(void);
|
||||
|
||||
// Clear to black, blit the draws in order (first = bottom) and present.
|
||||
// Returns 0 on success, -1 if nothing could be presented (no window yet, etc.).
|
||||
@@ -122,12 +132,12 @@ int vkp_can_wait_sync_fd(void);
|
||||
|
||||
/* ---- HDR composition (hdr_compose.h) ----
|
||||
* An HDR game that cannot be alone on its display layer: the scene is composed into ONE encoding. */
|
||||
struct banner_color;
|
||||
struct droiddeck_color;
|
||||
struct vkp_hdr_frame {
|
||||
const unsigned char *is_hdr; /* per draw: 1 = its image holds PQ BT.2020 (the surface's description) */
|
||||
float peak_nits; /* the HDR content's peak, for a tone-map (max CLL / mastering max; 0 = 1000) */
|
||||
int tonemap; /* 1 = the drawer's HDR output switch is off: tone-map to SDR, never PQ */
|
||||
const struct banner_color *color; /* the topmost HDR draw's description: an HDR10 swapchain's metadata */
|
||||
const struct droiddeck_color *color; /* the topmost HDR draw's description: an HDR10 swapchain's metadata */
|
||||
};
|
||||
/* vkp_render for a scene with HDR draws (frame generation): composed into PQ and presented through an
|
||||
* HDR10 swapchain where the surface offers one (and hf->tonemap is 0), else tone-mapped into the ordinary
|
||||
@@ -184,6 +194,6 @@ int vkp_pass_copy_to(struct vkp_image *dst, int wait_fd);
|
||||
void vkp_pass_abort(void);
|
||||
|
||||
// Session log (compositor.c): one line to Download/Wayland-logs and logcat.
|
||||
void banner_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
|
||||
void droiddeck_log(const char *tag, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
|
||||
|
||||
#endif
|
||||
@@ -16,20 +16,21 @@
|
||||
#include <android/log.h>
|
||||
#include <android/native_window_jni.h>
|
||||
#include "vk_present.h"
|
||||
#include "banner_ext.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "sc_layer.h"
|
||||
#include "effects_chain.h"
|
||||
#include "banner_color.h"
|
||||
#include "droiddeck_color.h"
|
||||
|
||||
extern int banner_wayland_run(void);
|
||||
extern void banner_wayland_send_pointer(int action, int x, int y);
|
||||
extern void banner_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||
extern int banner_cursor_snapshot(int *out, int cap);
|
||||
extern int banner_cursor_serial(void);
|
||||
extern void banner_wayland_send_key(int evdev, int state);
|
||||
extern void banner_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void banner_wayland_vsync(int64_t frame_time_ns);
|
||||
extern int droiddeck_wayland_run(void);
|
||||
extern void droiddeck_wayland_send_pointer(int action, int x, int y);
|
||||
extern void droiddeck_wayland_send_touch(int action, int pointer_id, int x, int y);
|
||||
extern int droiddeck_cursor_snapshot(int *out, int cap);
|
||||
extern int droiddeck_cursor_serial(void);
|
||||
extern void droiddeck_wayland_send_key(int evdev, int state);
|
||||
extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
|
||||
extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
|
||||
extern void droiddeck_wayland_output_resized(void);
|
||||
extern volatile int g_fps_limit;
|
||||
extern volatile int g_hide_shell;
|
||||
extern volatile int g_zero_copy;
|
||||
@@ -39,7 +40,7 @@ extern volatile int g_no_render_node;
|
||||
extern volatile int g_output_refresh_mhz;
|
||||
extern volatile int g_output_w, g_output_h;
|
||||
|
||||
#define TAG "BannerWayland"
|
||||
#define TAG "DroidDeckWayland"
|
||||
|
||||
static JavaVM *g_jvm;
|
||||
static volatile pid_t g_comp_tid; /* the compositor thread, for the app's ADPF hint session */
|
||||
@@ -80,7 +81,7 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
|
||||
/* Called from vk_present.c on the compositor thread when the first client frame is
|
||||
* presented. Attaches to the JVM (this thread is a bare pthread) and calls back into
|
||||
* Java so the launch overlay can dismiss. Fires exactly once. */
|
||||
void banner_on_first_frame(void) {
|
||||
void droiddeck_on_first_frame(void) {
|
||||
if (!g_jvm || !g_compositor_cls || !g_on_first_frame) return;
|
||||
JNIEnv *env = NULL;
|
||||
int attached = 0;
|
||||
@@ -111,7 +112,7 @@ static JNIEnv *thread_env(void) {
|
||||
}
|
||||
|
||||
/* A window started presenting GPU frames (window = its description), or NULL when it closed. */
|
||||
void banner_on_game_surface(const char *window, const char *gpu) {
|
||||
void droiddeck_on_game_surface(const char *window, const char *gpu) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_game_surface || !(env = thread_env())) return;
|
||||
jstring jw = window ? (*env)->NewStringUTF(env, window) : NULL;
|
||||
@@ -124,7 +125,7 @@ void banner_on_game_surface(const char *window, const char *gpu) {
|
||||
|
||||
/* The program behind the game window that just started presenting: its Linux pid and executable name
|
||||
* ("" = unknown). The app arms its launch-time CPU affinity on it. Compositor thread. */
|
||||
void banner_on_game_program(int pid, const char *program) {
|
||||
void droiddeck_on_game_program(int pid, const char *program) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_game_program || !(env = thread_env())) return;
|
||||
jstring jp = (*env)->NewStringUTF(env, program ? program : "");
|
||||
@@ -134,7 +135,7 @@ void banner_on_game_program(int pid, const char *program) {
|
||||
}
|
||||
|
||||
/* One GPU frame from that window. */
|
||||
void banner_on_game_frame(void) {
|
||||
void droiddeck_on_game_frame(void) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_game_frame || !(env = thread_env())) return;
|
||||
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_game_frame);
|
||||
@@ -144,7 +145,7 @@ void banner_on_game_frame(void) {
|
||||
/* A program locked the pointer (locked = 1; the app's input path switches to deltas) or the lock
|
||||
* ended (locked = 0; x,y = where the pointer is now, in scene coordinates, for the app to re-sync
|
||||
* its own pointer to). Compositor thread. */
|
||||
void banner_on_pointer_lock(int locked, int x, int y) {
|
||||
void droiddeck_on_pointer_lock(int locked, int x, int y) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_pointer_lock || !(env = thread_env())) return;
|
||||
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_pointer_lock, (jboolean)(locked != 0), (jint)x, (jint)y);
|
||||
@@ -153,7 +154,7 @@ void banner_on_pointer_lock(int locked, int x, int y) {
|
||||
|
||||
/* A program copied text (UTF-8, not NUL-terminated for the app's sake - a byte[] so emoji and
|
||||
* NULs survive JNI). Compositor thread. */
|
||||
void banner_on_clipboard_text(const char *utf8, int len) {
|
||||
void droiddeck_on_clipboard_text(const char *utf8, int len) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_clipboard || !(env = thread_env())) return;
|
||||
jbyteArray arr = (*env)->NewByteArray(env, len);
|
||||
@@ -166,7 +167,7 @@ void banner_on_clipboard_text(const char *utf8, int len) {
|
||||
|
||||
/* A program started (enabled) or stopped accepting IME text; x,y,w,h = its caret rectangle in
|
||||
* scene pixels (all 0 = unknown). Compositor thread. */
|
||||
void banner_on_text_input(int enabled, const char *program, int x, int y, int w, int h) {
|
||||
void droiddeck_on_text_input(int enabled, const char *program, int x, int y, int w, int h) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_text_input || !(env = thread_env())) return;
|
||||
jstring jp = (*env)->NewStringUTF(env, program ? program : "");
|
||||
@@ -195,11 +196,11 @@ static void *comp_thread(void *arg) {
|
||||
if (before > COMPOSITOR_NICE && setpriority(PRIO_PROCESS, tid, COMPOSITOR_NICE) != 0) refused = errno ? errno : -1;
|
||||
const int after = getpriority(PRIO_PROCESS, tid);
|
||||
if (refused)
|
||||
banner_log("perf", "compositor thread %d \"wl-compositor\": stays at nice %d, a higher priority was refused (%s)",
|
||||
droiddeck_log("perf", "compositor thread %d \"wl-compositor\": stays at nice %d, a higher priority was refused (%s)",
|
||||
(int)tid, after, refused > 0 ? strerror(refused) : "?");
|
||||
else
|
||||
banner_log("perf", "compositor thread %d \"wl-compositor\": nice %d -> %d", (int)tid, before, after);
|
||||
banner_wayland_run();
|
||||
droiddeck_log("perf", "compositor thread %d \"wl-compositor\": nice %d -> %d", (int)tid, before, after);
|
||||
droiddeck_wayland_run();
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "compositor thread exited");
|
||||
if (t_attached) (*g_jvm)->DetachCurrentThread(g_jvm);
|
||||
t_env = NULL; t_attached = 0;
|
||||
@@ -272,13 +273,13 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStartWithSurface(
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendPointer(
|
||||
JNIEnv *env, jclass clazz, jint action, jint x, jint y) {
|
||||
banner_wayland_send_pointer(action, x, y);
|
||||
droiddeck_wayland_send_pointer(action, x, y);
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendTouch(
|
||||
JNIEnv *env, jclass clazz, jint action, jint pointer_id, jint x, jint y) {
|
||||
banner_wayland_send_touch(action, pointer_id, x, y);
|
||||
droiddeck_wayland_send_touch(action, pointer_id, x, y);
|
||||
}
|
||||
|
||||
/* The client's pointer image and whether it wants one at all (wl_pointer.set_cursor).
|
||||
@@ -291,7 +292,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||
jint cap = (*env)->GetArrayLength(env, out);
|
||||
jint *buf = (*env)->GetIntArrayElements(env, out, NULL);
|
||||
if (!buf) return 0;
|
||||
int n = banner_cursor_snapshot((int *)buf, (int)cap);
|
||||
int n = droiddeck_cursor_snapshot((int *)buf, (int)cap);
|
||||
(*env)->ReleaseIntArrayElements(env, out, buf, 0);
|
||||
return n;
|
||||
}
|
||||
@@ -300,27 +301,27 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSnapshot(
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeCursorSerial(JNIEnv *env, jclass clazz) {
|
||||
(void)env; (void)clazz;
|
||||
return banner_cursor_serial();
|
||||
return droiddeck_cursor_serial();
|
||||
}
|
||||
|
||||
/* Inject a key event. evdev = Linux input keycode (KEY_A=30…); state 1=down 0=up. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendKey(
|
||||
JNIEnv *env, jclass clazz, jint evdev, jint state) {
|
||||
banner_wayland_send_key(evdev, state);
|
||||
droiddeck_wayland_send_key(evdev, state);
|
||||
}
|
||||
|
||||
/* App X-server input in scene (virtual desktop) coordinates; see banner_wayland_send_scene_input. */
|
||||
/* App X-server input in scene (virtual desktop) coordinates; see droiddeck_wayland_send_scene_input. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSendSceneInput(
|
||||
JNIEnv *env, jclass clazz, jint type, jint a, jint b) {
|
||||
banner_wayland_send_scene_input(type, a, b);
|
||||
droiddeck_wayland_send_scene_input(type, a, b);
|
||||
}
|
||||
|
||||
/* One screen refresh (Choreographer frame callback, UI thread): the compositor draws once. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeVsync(JNIEnv *env, jclass clazz, jlong frameTimeNanos) {
|
||||
banner_wayland_vsync((int64_t)frameTimeNanos);
|
||||
droiddeck_wayland_vsync((int64_t)frameTimeNanos);
|
||||
}
|
||||
|
||||
/* Shortcut launches: don't draw explorer's windows (desktop, taskbar), like X11's unviewable classes. */
|
||||
@@ -329,15 +330,15 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHideShell(JNIEnv
|
||||
g_hide_shell = hide ? 1 : 0;
|
||||
}
|
||||
|
||||
/* Zero-copy layer mode (BANNER_WAYLAND_ZERO_COPY=1 at launch, the drawer's switch live): one fullscreen
|
||||
/* Zero-copy layer mode (DROIDDECK_WAYLAND_ZERO_COPY=1 at launch, the drawer's switch live): one fullscreen
|
||||
* window on its own Android layer instead of the swapchain blit (sc_layer.c / ahb_swapchain.c). Any
|
||||
* thread, any time: before the compositor starts it is the launch default; afterwards the compositor
|
||||
* thread flips the state, tells the bound games to rebuild their swapchains for it and redraws. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetZeroCopy(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
int live = banner_get_display() != NULL;
|
||||
int live = droiddeck_get_display() != NULL;
|
||||
if (!live) g_zero_copy = on ? 1 : 0; /* read by ahb_swapchain_init before the queue drains */
|
||||
banner_host_zero_copy(on ? 1 : 0, live);
|
||||
droiddeck_host_zero_copy(on ? 1 : 0, live);
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "zero-copy layer mode %s%s", on ? "on" : "off", live ? " (live)" : "");
|
||||
}
|
||||
|
||||
@@ -355,7 +356,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeZeroCopyFrames(JNIEn
|
||||
}
|
||||
|
||||
/* Compressed (UBWC) game buffers: advertise DRM_FORMAT_MOD_QCOM_COMPRESSED on zwp_linux_dmabuf_v1 when
|
||||
* the renderer's driver imports it (default on; BANNER_WAYLAND_UBWC=0 = off). Set before the compositor
|
||||
* the renderer's driver imports it (default on; DROIDDECK_WAYLAND_UBWC=0 = off). Set before the compositor
|
||||
* starts. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetUbwc(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
@@ -363,7 +364,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetUbwc(JNIEnv *env,
|
||||
__android_log_print(ANDROID_LOG_INFO, TAG, "compressed (UBWC) game buffers %s", on ? "on" : "off");
|
||||
}
|
||||
|
||||
/* Debug: name no DRM device in the dma-buf feedback (BANNER_WAYLAND_NO_RENDER_NODE=1), the way a
|
||||
/* Debug: name no DRM device in the dma-buf feedback (DROIDDECK_WAYLAND_NO_RENDER_NODE=1), the way a
|
||||
* phone that exposes no /dev/dri node to apps does. Set before the compositor starts. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetNoRenderNode(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
@@ -401,6 +402,17 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetOutputSize(JNIEnv
|
||||
g_output_h = h > 0 ? h : 0;
|
||||
}
|
||||
|
||||
/* The output's size changed while the compositor runs (a foldable opening or closing with the
|
||||
* session following the screen): store it and have the compositor thread tell the clients. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeResizeOutput(JNIEnv *env, jclass clazz, jint w, jint h) {
|
||||
(void)env; (void)clazz;
|
||||
if (w <= 0 || h <= 0) return;
|
||||
g_output_w = w;
|
||||
g_output_h = h;
|
||||
droiddeck_wayland_output_resized();
|
||||
}
|
||||
|
||||
/* Fullscreen mode + screen alignment (Container.FULLSCREEN_* / ALIGN_* values): how the scene is
|
||||
* fitted onto the output. Any thread, any time; the next frame uses it. */
|
||||
JNIEXPORT void JNICALL
|
||||
@@ -452,12 +464,12 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetScreenEffects(JNI
|
||||
}
|
||||
|
||||
/* One "display" line in the session log, written from Java: facts that live in the Android
|
||||
* framework (the panel's HDR capability) rather than in the compositor. banner_log() mirrors to
|
||||
* framework (the panel's HDR capability) rather than in the compositor. droiddeck_log() mirrors to
|
||||
* logcat and appends to the session file when one is open, so this is safe at any point. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeLogDisplay(JNIEnv *env, jclass clazz, jstring message) {
|
||||
char *s = dup_jstr(env, message);
|
||||
if (s) banner_log("display", "%s", s);
|
||||
if (s) droiddeck_log("display", "%s", s);
|
||||
free(s);
|
||||
}
|
||||
|
||||
@@ -466,18 +478,18 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeLogDisplay(JNIEnv *e
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeLogPerf(JNIEnv *env, jclass clazz, jstring message) {
|
||||
char *s = dup_jstr(env, message);
|
||||
if (s) banner_log("perf", "%s", s);
|
||||
if (s) droiddeck_log("perf", "%s", s);
|
||||
free(s);
|
||||
}
|
||||
|
||||
/* ---- HDR10 output, round 1 (banner_color.h / wl_color_mgmt.c) ---- */
|
||||
/* ---- HDR10 output, round 1 (droiddeck_color.h / wl_color_mgmt.c) ---- */
|
||||
|
||||
/* The opt-in: mode 0 off, 1 BANNER_WAYLAND_HDR=1, 2 =force (testing). Before the compositor starts. */
|
||||
/* The opt-in: mode 0 off, 1 DROIDDECK_WAYLAND_HDR=1, 2 =force (testing). Before the compositor starts. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHdrRequest(JNIEnv *env, jclass clazz, jint mode,
|
||||
jstring source, jboolean dxvkHdr, jboolean zeroCopyForced) {
|
||||
char *s = dup_jstr(env, source);
|
||||
banner_color_set_request((int)mode, s, dxvkHdr ? 1 : 0, zeroCopyForced ? 1 : 0);
|
||||
droiddeck_color_set_request((int)mode, s, dxvkHdr ? 1 : 0, zeroCopyForced ? 1 : 0);
|
||||
free(s);
|
||||
}
|
||||
|
||||
@@ -487,7 +499,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHdrDisplay(JNIEnv
|
||||
jstring formats, jboolean hdr10, jfloat maxLum, jfloat maxAvg, jfloat minLum, jboolean ratioAvailable,
|
||||
jfloat ratio, jint api) {
|
||||
char *n = dup_jstr(env, name), *f = dup_jstr(env, formats);
|
||||
banner_color_set_display((int)id, n, f, hdr10 ? 1 : 0, (float)maxLum, (float)maxAvg, (float)minLum,
|
||||
droiddeck_color_set_display((int)id, n, f, hdr10 ? 1 : 0, (float)maxLum, (float)maxAvg, (float)minLum,
|
||||
ratioAvailable ? 1 : 0, (float)ratio, (int)api);
|
||||
free(n); free(f);
|
||||
}
|
||||
@@ -496,38 +508,38 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHdrDisplay(JNIEnv
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrSdrRatioSample(JNIEnv *env, jclass clazz, jfloat ratio,
|
||||
jboolean listener) {
|
||||
banner_color_ratio_sample((float)ratio, listener ? 1 : 0);
|
||||
droiddeck_color_ratio_sample((float)ratio, listener ? 1 : 0);
|
||||
}
|
||||
|
||||
/* ms since an HDR frame last reached a display layer, -1 = never this session. Any thread. */
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrLastFrameAgeMs(JNIEnv *env, jclass clazz) {
|
||||
return (jint)banner_color_last_frame_age_ms();
|
||||
return (jint)droiddeck_color_last_frame_age_ms();
|
||||
}
|
||||
|
||||
/* -1 = not decided yet, 0 = closed, 1 = open. Any thread. */
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrGateState(JNIEnv *env, jclass clazz) {
|
||||
return (jint)banner_color_gate_state();
|
||||
return (jint)droiddeck_color_gate_state();
|
||||
}
|
||||
|
||||
/* The session is ending: the "HDR on screen: ..." summary line. Any thread, once. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrSessionEnd(JNIEnv *env, jclass clazz) {
|
||||
banner_color_session_end();
|
||||
droiddeck_color_session_end();
|
||||
}
|
||||
|
||||
/* HDR frames really on screen right now (the HUD badge). Any thread. */
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrOnScreen(JNIEnv *env, jclass clazz) {
|
||||
return banner_color_hdr_on_screen() ? JNI_TRUE : JNI_FALSE;
|
||||
return droiddeck_color_hdr_on_screen() ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
/* One "color" line in the session log from Java. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeLogColor(JNIEnv *env, jclass clazz, jstring message) {
|
||||
char *s = dup_jstr(env, message);
|
||||
if (s) banner_log("color", "%s", s);
|
||||
if (s) droiddeck_log("color", "%s", s);
|
||||
free(s);
|
||||
}
|
||||
|
||||
@@ -536,7 +548,7 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeLogColor(JNIEnv *env
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeLog(JNIEnv *env, jclass clazz, jstring area, jstring message) {
|
||||
char *a = dup_jstr(env, area), *s = dup_jstr(env, message);
|
||||
if (s) banner_log(a && a[0] ? a : "app", "%s", s);
|
||||
if (s) droiddeck_log(a && a[0] ? a : "app", "%s", s);
|
||||
free(a);
|
||||
free(s);
|
||||
}
|
||||
@@ -544,65 +556,65 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeLog(JNIEnv *env, jcl
|
||||
/* SDR content's level inside an HDR picture, in nits (default 203). */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHdrSdrWhite(JNIEnv *env, jclass clazz, jfloat nits) {
|
||||
banner_color_set_sdr_white((float)nits);
|
||||
droiddeck_color_set_sdr_white((float)nits);
|
||||
}
|
||||
|
||||
/* The drawer's live HDR output switch: on = HDR frames as HDR, off = the same frames tone-mapped to SDR.
|
||||
* Applied on the compositor thread (logged there, with a redraw). */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHdrOutput(JNIEnv *env, jclass clazz, jboolean on) {
|
||||
if (banner_get_display()) banner_host_hdr_output(on ? 1 : 0);
|
||||
else banner_color_set_output(on ? 1 : 0); /* no compositor thread yet: nothing is drawing either */
|
||||
if (droiddeck_get_display()) droiddeck_host_hdr_output(on ? 1 : 0);
|
||||
else droiddeck_color_set_output(on ? 1 : 0); /* no compositor thread yet: nothing is drawing either */
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrOutput(JNIEnv *env, jclass clazz) {
|
||||
return banner_color_output() ? JNI_TRUE : JNI_FALSE;
|
||||
return droiddeck_color_output() ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
/* Device evidence for the HDR lines: thermal status + headroom, brightness + mode. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrEnvSample(JNIEnv *env, jclass clazz, jint thermal,
|
||||
jfloat headroom, jint brightness, jint mode) {
|
||||
banner_color_env_sample((int)thermal, (float)headroom != (float)headroom ? -1.0f : (float)headroom,
|
||||
droiddeck_color_env_sample((int)thermal, (float)headroom != (float)headroom ? -1.0f : (float)headroom,
|
||||
(int)brightness, (int)mode);
|
||||
}
|
||||
|
||||
/* Display.getHighestHdrSdrRatio() (Android 16+), <= 0 = not reported. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetHdrHighestRatio(JNIEnv *env, jclass clazz, jfloat ratio) {
|
||||
banner_color_set_highest_ratio((float)ratio == (float)ratio ? (float)ratio : -1.0f);
|
||||
droiddeck_color_set_highest_ratio((float)ratio == (float)ratio ? (float)ratio : -1.0f);
|
||||
}
|
||||
|
||||
/* The HDR headroom the screen surface should ask for (HDR10 swapchain frames in the last 1.5 s), 0 = none. */
|
||||
JNIEXPORT jfloat JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrScreenHeadroom(JNIEnv *env, jclass clazz) {
|
||||
return (jfloat)banner_color_screen_headroom(NULL, 0);
|
||||
return (jfloat)droiddeck_color_screen_headroom(NULL, 0);
|
||||
}
|
||||
|
||||
JNIEXPORT jstring JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrScreenHeadroomWhy(JNIEnv *env, jclass clazz) {
|
||||
char why[200];
|
||||
banner_color_screen_headroom(why, sizeof(why));
|
||||
droiddeck_color_screen_headroom(why, sizeof(why));
|
||||
return (*env)->NewStringUTF(env, why);
|
||||
}
|
||||
|
||||
/* The app's screen-surface request, for the no-headroom lines: > 0 asked, 0 cleared, -1 not possible. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrNoteHeadroomRequest(JNIEnv *env, jclass clazz, jfloat ratio) {
|
||||
banner_color_note_headroom_request((float)ratio);
|
||||
droiddeck_color_note_headroom_request((float)ratio);
|
||||
}
|
||||
|
||||
/* 0 none, 1 HDR frames on screen with headroom, 2 HDR frames on screen without headroom for 5 s+. */
|
||||
JNIEXPORT jint JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrState(JNIEnv *env, jclass clazz) {
|
||||
return (jint)banner_color_hdr_state();
|
||||
return (jint)droiddeck_color_hdr_state();
|
||||
}
|
||||
|
||||
/* An HDR game's frames were shown tone-mapped to SDR in the last 1.5 s (the drawer's status line). */
|
||||
JNIEXPORT jboolean JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeHdrToneMappedOnScreen(JNIEnv *env, jclass clazz) {
|
||||
return banner_color_tonemapped_on_screen() ? JNI_TRUE : JNI_FALSE;
|
||||
return droiddeck_color_tonemapped_on_screen() ? JNI_TRUE : JNI_FALSE;
|
||||
}
|
||||
|
||||
/* The Look the controls currently match (null = Custom) - only named in the session log. */
|
||||
@@ -651,7 +663,7 @@ JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetClipboardText(JNIEnv *env, jclass clazz, jbyteArray utf8) {
|
||||
int len;
|
||||
char *buf = dup_bytes(env, utf8, &len);
|
||||
banner_host_clipboard_text(buf ? buf : "", len);
|
||||
droiddeck_host_clipboard_text(buf ? buf : "", len);
|
||||
free(buf);
|
||||
}
|
||||
|
||||
@@ -660,7 +672,7 @@ JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputCommit(JNIEnv *env, jclass clazz, jbyteArray utf8) {
|
||||
int len;
|
||||
char *buf = dup_bytes(env, utf8, &len);
|
||||
if (buf && len) banner_host_text_commit(buf, len);
|
||||
if (buf && len) droiddeck_host_text_commit(buf, len);
|
||||
free(buf);
|
||||
}
|
||||
|
||||
@@ -670,14 +682,14 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputPreedit(JNI
|
||||
jint cursorBegin, jint cursorEnd) {
|
||||
int len;
|
||||
char *buf = dup_bytes(env, utf8, &len);
|
||||
banner_host_text_preedit(buf ? buf : "", len, cursorBegin, cursorEnd);
|
||||
droiddeck_host_text_preedit(buf ? buf : "", len, cursorBegin, cursorEnd);
|
||||
free(buf);
|
||||
}
|
||||
|
||||
/* The IME deleted characters around the caret. */
|
||||
JNIEXPORT void JNICALL
|
||||
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeTextInputDelete(JNIEnv *env, jclass clazz, jint before, jint after) {
|
||||
banner_host_text_delete(before, after);
|
||||
droiddeck_host_text_delete(before, after);
|
||||
}
|
||||
|
||||
/* KGSL's power control, off (the GPU held at its top clock) or back on. The property is the
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -16,7 +16,7 @@
|
||||
*
|
||||
* Guest → Android: when a program sets a selection with a text mime, the compositor asks for it
|
||||
* once over a pipe on the event loop (non-blocking, 1 MiB cap, 3 s timeout) and hands the text
|
||||
* to the app (banner_on_clipboard_text → ClipboardManager). Android → guest: the app's text
|
||||
* to the app (droiddeck_on_clipboard_text → ClipboardManager). Android → guest: the app's text
|
||||
* becomes the HOST selection; receive requests are answered with a non-blocking writer.
|
||||
*/
|
||||
#define _GNU_SOURCE 1
|
||||
@@ -25,7 +25,7 @@
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include "banner_ext.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "wlr-data-control-unstable-v1-server-protocol.h"
|
||||
|
||||
#define CLIP_MAX_BYTES (1024 * 1024)
|
||||
@@ -130,7 +130,7 @@ static int on_writer_writable(int fd, uint32_t mask, void *data) {
|
||||
|
||||
static int on_writer_timeout(void *data) {
|
||||
struct writer *w = data;
|
||||
banner_log("clipboard", "a program never read the clipboard text it asked for; giving up");
|
||||
droiddeck_log("clipboard", "a program never read the clipboard text it asked for; giving up");
|
||||
writer_free(w);
|
||||
return 0;
|
||||
}
|
||||
@@ -179,11 +179,11 @@ static void reader_finish(struct reader *r) {
|
||||
free(g_last_guest_text);
|
||||
g_last_guest_text = copy;
|
||||
g_last_guest_len = r->len;
|
||||
banner_log("clipboard", "guest copied %zu bytes (%s)", r->len, r->mime);
|
||||
banner_on_clipboard_text(copy, (int)r->len);
|
||||
droiddeck_log("clipboard", "guest copied %zu bytes (%s)", r->len, r->mime);
|
||||
droiddeck_on_clipboard_text(copy, (int)r->len);
|
||||
}
|
||||
} else {
|
||||
banner_log("clipboard", "guest copied an empty text; Android clipboard left alone");
|
||||
droiddeck_log("clipboard", "guest copied an empty text; Android clipboard left alone");
|
||||
}
|
||||
reader_free(r);
|
||||
}
|
||||
@@ -192,7 +192,7 @@ static int on_reader_readable(int fd, uint32_t mask, void *data) {
|
||||
struct reader *r = data;
|
||||
for (;;) {
|
||||
if (r->len >= CLIP_MAX_BYTES) {
|
||||
banner_log("clipboard", "guest text exceeds %d bytes; dropped", CLIP_MAX_BYTES);
|
||||
droiddeck_log("clipboard", "guest text exceeds %d bytes; dropped", CLIP_MAX_BYTES);
|
||||
reader_free(r);
|
||||
return 0;
|
||||
}
|
||||
@@ -215,7 +215,7 @@ static int on_reader_readable(int fd, uint32_t mask, void *data) {
|
||||
|
||||
static int on_reader_timeout(void *data) {
|
||||
struct reader *r = data;
|
||||
banner_log("clipboard", "timed out reading the guest's clipboard text (%zu bytes so far)", r->len);
|
||||
droiddeck_log("clipboard", "timed out reading the guest's clipboard text (%zu bytes so far)", r->len);
|
||||
reader_free(r);
|
||||
return 0;
|
||||
}
|
||||
@@ -251,7 +251,7 @@ static void offer_receive(struct wl_client *c, struct wl_resource *r, const char
|
||||
if (!o || o->gen != g_gen) { close(fd); return; } /* stale offer */
|
||||
if (g_owner == OWNER_HOST) {
|
||||
if (is_text_mime(mime)) {
|
||||
banner_log("clipboard", "Android clipboard → guest (%zu bytes) for %s", g_host_len, banner_client_name(c));
|
||||
droiddeck_log("clipboard", "Android clipboard → guest (%zu bytes) for %s", g_host_len, droiddeck_client_name(c));
|
||||
writer_start(fd, g_host_text, g_host_len);
|
||||
} else {
|
||||
close(fd);
|
||||
@@ -327,7 +327,7 @@ static void broadcast_selection(void) {
|
||||
wl_display_flush_clients(g_disp);
|
||||
}
|
||||
|
||||
void banner_clipboard_keyboard_focus(struct wl_client *client) {
|
||||
void droiddeck_clipboard_keyboard_focus(struct wl_client *client) {
|
||||
struct device *d;
|
||||
if (client == g_kb_client) return;
|
||||
g_kb_client = client;
|
||||
@@ -345,7 +345,7 @@ static void source_res_destroy(struct wl_resource *r) {
|
||||
g_src = NULL;
|
||||
g_owner = OWNER_NONE;
|
||||
if (g_reader) reader_free(g_reader);
|
||||
banner_log("clipboard", "%s withdrew its clipboard contents", banner_client_name(wl_resource_get_client(r)));
|
||||
droiddeck_log("clipboard", "%s withdrew its clipboard contents", droiddeck_client_name(wl_resource_get_client(r)));
|
||||
broadcast_selection();
|
||||
}
|
||||
for (int i = 0; i < s->nmimes; i++) free(s->mimes[i]);
|
||||
@@ -396,9 +396,9 @@ static void set_selection(struct wl_client *c, struct wl_resource *source_res) {
|
||||
if (*list) strncat(list, ", ", sizeof(list) - strlen(list) - 1);
|
||||
strncat(list, s->mimes[i], sizeof(list) - strlen(list) - 1);
|
||||
}
|
||||
banner_log("clipboard", "selection set by %s (%s)", banner_client_name(c), *list ? list : "no mime types");
|
||||
droiddeck_log("clipboard", "selection set by %s (%s)", droiddeck_client_name(c), *list ? list : "no mime types");
|
||||
} else {
|
||||
banner_log("clipboard", "%s cleared the clipboard", banner_client_name(c));
|
||||
droiddeck_log("clipboard", "%s cleared the clipboard", droiddeck_client_name(c));
|
||||
}
|
||||
broadcast_selection();
|
||||
read_client_text();
|
||||
@@ -415,7 +415,7 @@ static void device_res_destroy(struct wl_resource *r) {
|
||||
|
||||
static void device_start_drag(struct wl_client *c, struct wl_resource *r, struct wl_resource *source,
|
||||
struct wl_resource *origin, struct wl_resource *icon, uint32_t serial) {
|
||||
banner_log("clipboard", "%s started a drag and drop; not supported, cancelled", banner_client_name(c));
|
||||
droiddeck_log("clipboard", "%s started a drag and drop; not supported, cancelled", droiddeck_client_name(c));
|
||||
if (source) {
|
||||
struct source *s = wl_resource_get_user_data(source);
|
||||
if (s && s != g_src) source_send_cancelled(s);
|
||||
@@ -512,7 +512,7 @@ void clipboard_host_text(char *utf8, size_t len) {
|
||||
if (!len) free(utf8);
|
||||
g_host_len = len;
|
||||
g_owner = len ? OWNER_HOST : OWNER_NONE;
|
||||
banner_log("clipboard", len ? "Android clipboard → guest (%zu bytes)" : "Android clipboard cleared (%zu bytes)", len);
|
||||
droiddeck_log("clipboard", len ? "Android clipboard → guest (%zu bytes)" : "Android clipboard cleared (%zu bytes)", len);
|
||||
broadcast_selection();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
* wp_color_manager_v1 (wayland-protocols staging color-management-v1, version 1) - the subset Mesa's
|
||||
* Wayland WSI binds - plus the HDR gate, the per-surface image descriptions and the session log's
|
||||
* HDR evidence. See banner_color.h for the design and HDR_RECON.md for why it is shaped this way.
|
||||
* HDR evidence. See droiddeck_color.h for the design and HDR_RECON.md for why it is shaped this way.
|
||||
*
|
||||
* Strictness policy. A protocol error disconnects the client, and the client here is a GAME, so
|
||||
* errors are only raised where the protocol leaves no choice and a conforming client can never hit
|
||||
@@ -12,8 +12,8 @@
|
||||
* for the same surface replaces the first, a request on an inert object is ignored.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include "banner_color.h"
|
||||
#include "banner_ext.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "ahb_swapchain.h"
|
||||
#include "sc_layer.h"
|
||||
#include "color-management-v1-server-protocol.h"
|
||||
@@ -30,7 +30,7 @@ extern volatile int g_zero_copy;
|
||||
#define TAG "color"
|
||||
|
||||
/* AHARDWAREBUFFER_FORMAT_* (android/hardware_buffer.h), for the log only. */
|
||||
const char *banner_ahb_format_name(uint32_t f) {
|
||||
const char *droiddeck_ahb_format_name(uint32_t f) {
|
||||
static char other[32];
|
||||
switch (f) {
|
||||
case 1: return "RGBA8888 (8-bit)";
|
||||
@@ -73,9 +73,9 @@ static const char *tf_name(uint32_t tf) {
|
||||
|
||||
static const char *dataspace_name(int32_t ds) {
|
||||
switch (ds) {
|
||||
case BANNER_ADATASPACE_BT2020_PQ: return "BT2020_PQ";
|
||||
case BANNER_ADATASPACE_BT2020_HLG: return "BT2020_HLG";
|
||||
case BANNER_ADATASPACE_UNKNOWN: return "UNKNOWN (sRGB)";
|
||||
case DROIDDECK_ADATASPACE_BT2020_PQ: return "BT2020_PQ";
|
||||
case DROIDDECK_ADATASPACE_BT2020_HLG: return "BT2020_HLG";
|
||||
case DROIDDECK_ADATASPACE_UNKNOWN: return "UNKNOWN (sRGB)";
|
||||
default: return "other";
|
||||
}
|
||||
}
|
||||
@@ -99,7 +99,7 @@ static _Atomic int g_gate = -1; /* -1 undecided, 0 closed, 1 open */
|
||||
static char g_gate_why[320]; /* the closed gate's reason (for the summary) */
|
||||
static _Atomic int g_output_on = 1; /* the drawer's HDR output switch (per session, starts on) */
|
||||
|
||||
void banner_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced) {
|
||||
void droiddeck_color_set_request(int mode, const char *source, int dxvk_hdr, int zero_copy_forced) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
g_req.mode = mode < 0 ? 0 : mode > 2 ? 2 : mode;
|
||||
snprintf(g_req.source, sizeof(g_req.source), "%s", source ? source : "environment");
|
||||
@@ -109,7 +109,7 @@ void banner_color_set_request(int mode, const char *source, int dxvk_hdr, int ze
|
||||
atomic_store(&g_output_on, 1); /* the drawer's switch is per session and starts on */
|
||||
}
|
||||
|
||||
void banner_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum,
|
||||
void droiddeck_color_set_display(int id, const char *name, const char *formats, int hdr10, float max_lum,
|
||||
float max_avg, float min_lum, int ratio_available, float ratio, int api) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
int was_known = g_req.display_known, was_hdr10 = g_req.hdr10, was_id = g_req.display_id;
|
||||
@@ -127,17 +127,17 @@ void banner_color_set_display(int id, const char *name, const char *formats, int
|
||||
* session is recorded, and what it means is said out loud. */
|
||||
if (was_known && atomic_load(&g_gate) >= 0 && (was_hdr10 != (hdr10 ? 1 : 0) || was_id != id)) {
|
||||
if (atomic_load(&g_gate) == 1 && !hdr10)
|
||||
banner_log(TAG, "the game is now on \"%s\" (display %d), which reports no HDR10: HDR frames stay tagged "
|
||||
droiddeck_log(TAG, "the game is now on \"%s\" (display %d), which reports no HDR10: HDR frames stay tagged "
|
||||
"BT2020_PQ and SurfaceFlinger tone-maps them for this display (the offer to games is fixed "
|
||||
"for the session)", name ? name : "?", id);
|
||||
else if (atomic_load(&g_gate) == 0 && hdr10)
|
||||
banner_log(TAG, "the game is now on \"%s\" (display %d), which reports HDR10 - HDR stays off for this "
|
||||
droiddeck_log(TAG, "the game is now on \"%s\" (display %d), which reports HDR10 - HDR stays off for this "
|
||||
"session (the gate is decided when the compositor starts); relaunch to use it", name ? name : "?", id);
|
||||
}
|
||||
}
|
||||
|
||||
int banner_color_gate_state(void) { return atomic_load(&g_gate); }
|
||||
int banner_color_hdr_open(void) { return atomic_load(&g_gate) == 1; }
|
||||
int droiddeck_color_gate_state(void) { return atomic_load(&g_gate); }
|
||||
int droiddeck_color_hdr_open(void) { return atomic_load(&g_gate) == 1; }
|
||||
|
||||
/* ---------------------------------------------------------------- HDR evidence (summary) */
|
||||
|
||||
@@ -170,7 +170,7 @@ static struct {
|
||||
static _Atomic int64_t g_last_frame_ns;
|
||||
static _Atomic int64_t g_last_tm_ns; /* the last HDR frame shown tone-mapped to SDR */
|
||||
|
||||
/* What the device says beside the headroom (the app, non-root APIs; banner_color_env_*). The Fold showed
|
||||
/* What the device says beside the headroom (the app, non-root APIs; droiddeck_color_env_*). The Fold showed
|
||||
* three ways to lose HDR headroom with HDR frames on screen - a screen recording, heat under load, and
|
||||
* (plausibly) the brightness slider at maximum - so every no-headroom line carries this. Under g_mu. */
|
||||
static struct {
|
||||
@@ -241,20 +241,20 @@ static _Atomic int g_screen_hr_x1000; /* the screen surface's wanted headr
|
||||
static _Atomic int64_t g_screen_hr_ns; /* the last HDR10-swapchain frame */
|
||||
static char g_screen_hr_why[200]; /* under g_mu */
|
||||
|
||||
static float peak_of(const struct banner_color *c, float disp_max, const char **src) {
|
||||
static float peak_of(const struct droiddeck_color *c, float disp_max, const char **src) {
|
||||
if (c->max_cll > 0.0f) { *src = "max CLL"; return c->max_cll; }
|
||||
if (c->has_st2086 && c->max_lum > 0.0f) { *src = "mastering max"; return c->max_lum; }
|
||||
if (disp_max > 0.0f) { *src = "the display's peak"; return disp_max; }
|
||||
*src = "assumed"; return 1000.0f;
|
||||
}
|
||||
|
||||
float banner_color_desired_headroom(const struct banner_color *c, char *why, size_t n) {
|
||||
float droiddeck_color_desired_headroom(const struct droiddeck_color *c, char *why, size_t n) {
|
||||
if (!c || !c->dataspace) { if (why && n) why[0] = 0; return 0.0f; }
|
||||
pthread_mutex_lock(&g_mu);
|
||||
const float disp_max = g_req.max_lum, highest = g_req.highest_ratio;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
const char *src;
|
||||
const float peak = peak_of(c, disp_max, &src), white = banner_color_sdr_white();
|
||||
const float peak = peak_of(c, disp_max, &src), white = droiddeck_color_sdr_white();
|
||||
if (highest > 0.0f && highest <= 1.01f) {
|
||||
if (why && n) snprintf(why, n, "the display reports its highest HDR/SDR ratio as %.2f: no app can get a "
|
||||
"boost here, so nothing is asked", highest);
|
||||
@@ -273,24 +273,24 @@ float banner_color_desired_headroom(const struct banner_color *c, char *why, siz
|
||||
return r;
|
||||
}
|
||||
|
||||
void banner_color_note_headroom_request(float ratio) {
|
||||
void droiddeck_color_note_headroom_request(float ratio) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
g_env.requested = ratio;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
|
||||
void banner_color_set_highest_ratio(float ratio) {
|
||||
void droiddeck_color_set_highest_ratio(float ratio) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
const float was = g_req.highest_ratio;
|
||||
g_req.highest_ratio = ratio > 0.0f ? ratio : -1.0f;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (ratio > 0.0f && (was < 0.0f || was != ratio) && atomic_load(&g_gate) == 1)
|
||||
banner_log(TAG, "the display's highest HDR/SDR ratio is %.2f%s", ratio,
|
||||
droiddeck_log(TAG, "the display's highest HDR/SDR ratio is %.2f%s", ratio,
|
||||
ratio <= 1.01f ? " - it reports no HDR boost at all: no app can raise HDR highlights above SDR white here"
|
||||
: " (the most HDR headroom it can give)");
|
||||
}
|
||||
|
||||
float banner_color_screen_headroom(char *why, size_t n) {
|
||||
float droiddeck_color_screen_headroom(char *why, size_t n) {
|
||||
const int64_t t = atomic_load(&g_screen_hr_ns);
|
||||
if (!t || now_ns() - t > 1500000000LL) { if (why && n) why[0] = 0; return 0.0f; }
|
||||
if (why && n) {
|
||||
@@ -301,7 +301,7 @@ float banner_color_screen_headroom(char *why, size_t n) {
|
||||
return atomic_load(&g_screen_hr_x1000) / 1000.0f;
|
||||
}
|
||||
|
||||
int banner_color_last_frame_age_ms(void) {
|
||||
int droiddeck_color_last_frame_age_ms(void) {
|
||||
int64_t t = atomic_load(&g_last_frame_ns);
|
||||
if (!t) return -1;
|
||||
int64_t age = (now_ns() - t) / 1000000LL;
|
||||
@@ -408,34 +408,34 @@ static void log_verdict(int force) {
|
||||
int changed = strcmp(v, g_hdr.verdict) != 0;
|
||||
if (changed) snprintf(g_hdr.verdict, sizeof(g_hdr.verdict), "%s", v);
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (changed || force) banner_log(TAG, "HDR on screen: %s", v);
|
||||
if (changed || force) droiddeck_log(TAG, "HDR on screen: %s", v);
|
||||
}
|
||||
|
||||
void banner_color_frame_shown(const struct banner_color *c, int path, uint32_t ahb_format) {
|
||||
void droiddeck_color_frame_shown(const struct droiddeck_color *c, int path, uint32_t ahb_format) {
|
||||
if (!c || !c->dataspace) return;
|
||||
int first8 = 0;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
switch (path) {
|
||||
case BANNER_HDR_ZERO_COPY:
|
||||
case DROIDDECK_HDR_ZERO_COPY:
|
||||
if (ahb_format == 0x2b) g_hdr.layer_10bit++;
|
||||
g_hdr.win_zc++;
|
||||
snprintf(g_hdr.layer_fmt, sizeof(g_hdr.layer_fmt), "%s", banner_ahb_format_name(ahb_format));
|
||||
snprintf(g_hdr.layer_fmt, sizeof(g_hdr.layer_fmt), "%s", droiddeck_ahb_format_name(ahb_format));
|
||||
break;
|
||||
case BANNER_HDR_LAYER_COPY:
|
||||
case DROIDDECK_HDR_LAYER_COPY:
|
||||
if (!g_hdr.layer_copy8) first8 = 1;
|
||||
g_hdr.layer_copy8++; g_hdr.win_copy8++;
|
||||
snprintf(g_hdr.layer_fmt, sizeof(g_hdr.layer_fmt), "RGBA8888 layer copy");
|
||||
break;
|
||||
case BANNER_HDR_COMPOSED:
|
||||
case DROIDDECK_HDR_COMPOSED:
|
||||
g_hdr.composed++; g_hdr.win_composed++;
|
||||
snprintf(g_hdr.layer_fmt, sizeof(g_hdr.layer_fmt), "composed %s", banner_ahb_format_name(ahb_format));
|
||||
snprintf(g_hdr.layer_fmt, sizeof(g_hdr.layer_fmt), "composed %s", droiddeck_ahb_format_name(ahb_format));
|
||||
break;
|
||||
case BANNER_HDR_SWAPCHAIN:
|
||||
case DROIDDECK_HDR_SWAPCHAIN:
|
||||
g_hdr.swapchain++; g_hdr.win_swapchain++;
|
||||
snprintf(g_hdr.layer_fmt, sizeof(g_hdr.layer_fmt), "HDR10 swapchain");
|
||||
atomic_store(&g_screen_hr_ns, now_ns());
|
||||
break;
|
||||
default: /* BANNER_HDR_TONEMAPPED: shown, but not as HDR */
|
||||
default: /* DROIDDECK_HDR_TONEMAPPED: shown, but not as HDR */
|
||||
g_hdr.tonemapped++; g_hdr.win_tonemapped++;
|
||||
if (!atomic_load(&g_output_on)) g_hdr.tm_off++;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
@@ -446,7 +446,7 @@ void banner_color_frame_shown(const struct banner_color *c, int path, uint32_t a
|
||||
g_hdr.win_layer++;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
atomic_store(&g_last_frame_ns, now_ns());
|
||||
if (path == BANNER_HDR_SWAPCHAIN) {
|
||||
if (path == DROIDDECK_HDR_SWAPCHAIN) {
|
||||
/* The screen surface's headroom request (the app applies it): worked out again when the
|
||||
* description changes, else once a second. */
|
||||
static uint32_t ident;
|
||||
@@ -454,7 +454,7 @@ void banner_color_frame_shown(const struct banner_color *c, int path, uint32_t a
|
||||
const int64_t t = now_ns();
|
||||
if (c->identity != ident || t - calc_ns > 1000000000LL) {
|
||||
char why[200];
|
||||
const float r = banner_color_desired_headroom(c, why, sizeof(why));
|
||||
const float r = droiddeck_color_desired_headroom(c, why, sizeof(why));
|
||||
ident = c->identity; calc_ns = t;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
snprintf(g_screen_hr_why, sizeof(g_screen_hr_why), "%s", why);
|
||||
@@ -463,12 +463,12 @@ void banner_color_frame_shown(const struct banner_color *c, int path, uint32_t a
|
||||
}
|
||||
}
|
||||
if (first8)
|
||||
banner_log(TAG, "HDR frames are reaching the display layer through the compositor's 8-bit layer copy (the game's "
|
||||
droiddeck_log(TAG, "HDR frames are reaching the display layer through the compositor's 8-bit layer copy (the game's "
|
||||
"buffer is not a gralloc buffer this frame): colours stay correct (the frame keeps its BT2020_PQ tag), "
|
||||
"precision drops to 8 bits (banding possible)");
|
||||
}
|
||||
|
||||
void banner_color_frame_copied(const char *who, const char *reason) {
|
||||
void droiddeck_color_frame_copied(const char *who, const char *reason) {
|
||||
int first = 0;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
g_hdr.copy_frames++;
|
||||
@@ -479,14 +479,14 @@ void banner_color_frame_copied(const char *who, const char *reason) {
|
||||
}
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (first)
|
||||
banner_log(TAG, "HDR frames of %s go through the compositor's 8-bit SDR copy now, because %s: shown WITHOUT "
|
||||
droiddeck_log(TAG, "HDR frames of %s go through the compositor's 8-bit SDR copy now, because %s: shown WITHOUT "
|
||||
"tone mapping (washed out) until that changes", who ? who : "a window", reason ? reason : "?");
|
||||
}
|
||||
|
||||
void banner_color_ratio_sample(float ratio, int listener) {
|
||||
void droiddeck_color_ratio_sample(float ratio, int listener) {
|
||||
if (atomic_load(&g_gate) != 1) return;
|
||||
int64_t t = now_ns();
|
||||
int age = banner_color_last_frame_age_ms();
|
||||
int age = droiddeck_color_last_frame_age_ms();
|
||||
int live = age >= 0 && age < 1500;
|
||||
int log_it = 0, periodic = 0, nohead_now = 0, head_back = 0;
|
||||
float was;
|
||||
@@ -536,28 +536,28 @@ void banner_color_ratio_sample(float ratio, int listener) {
|
||||
}
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (nohead_now)
|
||||
banner_log(TAG, "no HDR headroom for 5 s while HDR frames are on screen (display HDR/SDR ratio %.2f): %s - Android "
|
||||
droiddeck_log(TAG, "no HDR headroom for 5 s while HDR frames are on screen (display HDR/SDR ratio %.2f): %s - Android "
|
||||
"drops HDR headroom while the screen is recorded and when the device is hot, and some phones never "
|
||||
"boost HDR for apps; HDR highlights look no brighter until that ends [%s]", ratio, causes, env);
|
||||
if (head_back)
|
||||
banner_log(TAG, "HDR headroom is back: display HDR/SDR ratio %.2f with HDR frames on screen", ratio);
|
||||
droiddeck_log(TAG, "HDR headroom is back: display HDR/SDR ratio %.2f with HDR frames on screen", ratio);
|
||||
if (!log_it) return;
|
||||
char when[64];
|
||||
if (age < 0) snprintf(when, sizeof(when), "none yet this session");
|
||||
else snprintf(when, sizeof(when), "%s, last one %d ms ago", live ? "yes" : "no", age);
|
||||
if (periodic)
|
||||
banner_log(TAG, "display HDR/SDR ratio %.2f (steady; HDR frames on screen: %s)%s%s%s%s%s", ratio, when,
|
||||
droiddeck_log(TAG, "display HDR/SDR ratio %.2f (steady; HDR frames on screen: %s)%s%s%s%s%s", ratio, when,
|
||||
live && ratio <= 1.01f ? " - no HDR headroom: " : "", live && ratio <= 1.01f ? causes : "",
|
||||
env[0] ? " [" : "", env, env[0] ? "]" : "");
|
||||
else if (was > 0.0f)
|
||||
banner_log(TAG, "display HDR/SDR ratio %.2f (was %.2f; HDR frames on screen: %s) [%s]", ratio, was, when,
|
||||
droiddeck_log(TAG, "display HDR/SDR ratio %.2f (was %.2f; HDR frames on screen: %s) [%s]", ratio, was, when,
|
||||
listener ? "display listener" : "sampler");
|
||||
else
|
||||
banner_log(TAG, "display HDR/SDR ratio %.2f (first reading; HDR frames on screen: %s) [%s]", ratio, when,
|
||||
droiddeck_log(TAG, "display HDR/SDR ratio %.2f (first reading; HDR frames on screen: %s) [%s]", ratio, when,
|
||||
listener ? "display listener" : "sampler");
|
||||
}
|
||||
|
||||
void banner_color_stats_tick(void) {
|
||||
void droiddeck_color_stats_tick(void) {
|
||||
if (atomic_load(&g_gate) != 1) return;
|
||||
char line[512];
|
||||
int any;
|
||||
@@ -582,13 +582,13 @@ void banner_color_stats_tick(void) {
|
||||
g_hdr.win_zc = g_hdr.win_composed = g_hdr.win_swapchain = g_hdr.win_tonemapped = 0;
|
||||
g_hdr.win_ratio_n = 0;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (any) banner_log(TAG, "%s", line);
|
||||
if (any) droiddeck_log(TAG, "%s", line);
|
||||
log_verdict(0);
|
||||
}
|
||||
|
||||
int banner_color_hdr_state(void) {
|
||||
int droiddeck_color_hdr_state(void) {
|
||||
if (atomic_load(&g_gate) != 1) return 0;
|
||||
int age = banner_color_last_frame_age_ms();
|
||||
int age = droiddeck_color_last_frame_age_ms();
|
||||
if (age < 0 || age >= 1500) return 0;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
int confirmed = !g_hdr.ratio_n || g_hdr.ratio_last > 1.01f; /* no ratio on this display: the tag is all there is */
|
||||
@@ -597,26 +597,26 @@ int banner_color_hdr_state(void) {
|
||||
return confirmed ? 1 : nohead ? 2 : 0;
|
||||
}
|
||||
|
||||
int banner_color_hdr_on_screen(void) { return banner_color_hdr_state() == 1; }
|
||||
int droiddeck_color_hdr_on_screen(void) { return droiddeck_color_hdr_state() == 1; }
|
||||
|
||||
static _Atomic int g_sdr_white_x100 = 20300;
|
||||
void banner_color_set_sdr_white(float nits) {
|
||||
void droiddeck_color_set_sdr_white(float nits) {
|
||||
if (!(nits >= 10.0f && nits <= 2000.0f)) return;
|
||||
atomic_store(&g_sdr_white_x100, (int)(nits * 100.0f + 0.5f));
|
||||
banner_log(TAG, "SDR content inside an HDR picture is placed at %.0f nits (BANNER_WAYLAND_HDR_SDR_NITS)", nits);
|
||||
droiddeck_log(TAG, "SDR content inside an HDR picture is placed at %.0f nits (DROIDDECK_WAYLAND_HDR_SDR_NITS)", nits);
|
||||
}
|
||||
float banner_color_sdr_white(void) { return atomic_load(&g_sdr_white_x100) / 100.0f; }
|
||||
float droiddeck_color_sdr_white(void) { return atomic_load(&g_sdr_white_x100) / 100.0f; }
|
||||
|
||||
int banner_color_requested(void) {
|
||||
int droiddeck_color_requested(void) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
int m = g_req.mode;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
return m != 0;
|
||||
}
|
||||
|
||||
int banner_color_output(void) { return atomic_load(&g_output_on); }
|
||||
int droiddeck_color_output(void) { return atomic_load(&g_output_on); }
|
||||
|
||||
void banner_color_env_sample(int thermal, float headroom, int brightness, int bmode) {
|
||||
void droiddeck_color_env_sample(int thermal, float headroom, int brightness, int bmode) {
|
||||
if (atomic_load(&g_gate) != 1) return; /* evidence for the HDR lines only */
|
||||
char msg[2][200];
|
||||
int nmsg = 0;
|
||||
@@ -644,42 +644,42 @@ void banner_color_env_sample(int thermal, float headroom, int brightness, int bm
|
||||
"brightness changes are logged as they happen)", e);
|
||||
}
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
for (int i = 0; i < nmsg; i++) banner_log(TAG, "%s", msg[i]);
|
||||
for (int i = 0; i < nmsg; i++) droiddeck_log(TAG, "%s", msg[i]);
|
||||
}
|
||||
|
||||
int banner_color_tonemapped_on_screen(void) {
|
||||
int droiddeck_color_tonemapped_on_screen(void) {
|
||||
if (atomic_load(&g_gate) != 1) return 0;
|
||||
int64_t t = atomic_load(&g_last_tm_ns);
|
||||
return t && now_ns() - t < 1500000000LL;
|
||||
}
|
||||
|
||||
void banner_color_set_output(int on) {
|
||||
void droiddeck_color_set_output(int on) {
|
||||
on = on ? 1 : 0;
|
||||
if (atomic_load(&g_gate) != 1) {
|
||||
/* The drawer only shows the switch in sessions whose gate is open; say so if it ever gets here. */
|
||||
banner_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off");
|
||||
droiddeck_log(TAG, "HDR output switch (%s) ignored: HDR is not open in this session", on ? "on" : "off");
|
||||
return;
|
||||
}
|
||||
if (atomic_exchange(&g_output_on, on) == on) return;
|
||||
char who[160];
|
||||
int age = banner_color_last_frame_age_ms(), tm = banner_color_tonemapped_on_screen();
|
||||
int age = droiddeck_color_last_frame_age_ms(), tm = droiddeck_color_tonemapped_on_screen();
|
||||
pthread_mutex_lock(&g_mu);
|
||||
if (!on) g_hdr.output_offs++;
|
||||
snprintf(who, sizeof(who), "%s", g_hdr.applied_who[0] ? g_hdr.applied_who : "no HDR program yet");
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (on)
|
||||
banner_log(TAG, "HDR output switched ON in the drawer: HDR frames go to the display as HDR again from the next "
|
||||
droiddeck_log(TAG, "HDR output switched ON in the drawer: HDR frames go to the display as HDR again from the next "
|
||||
"frame (%s; %s)", who, tm ? "they were being tone-mapped to SDR until now" : "none were on screen just now");
|
||||
else
|
||||
banner_log(TAG, "HDR output switched OFF in the drawer: HDR frames are tone-mapped to SDR from the next frame "
|
||||
droiddeck_log(TAG, "HDR output switched OFF in the drawer: HDR frames are tone-mapped to SDR from the next frame "
|
||||
"(%s; %s). The game is not told - it keeps rendering HDR; its own HDR setting and DXVK_HDR are "
|
||||
"untouched", who, age >= 0 && age < 1500 ? "HDR frames were on screen" : "no HDR frames on screen just now");
|
||||
banner_request_redraw(); /* a paused game commits nothing: show the change now */
|
||||
droiddeck_request_redraw(); /* a paused game commits nothing: show the change now */
|
||||
}
|
||||
|
||||
static _Atomic int g_session_ended;
|
||||
|
||||
void banner_color_session_end(void) {
|
||||
void droiddeck_color_session_end(void) {
|
||||
if (atomic_exchange(&g_session_ended, 1)) return;
|
||||
if (atomic_load(&g_gate) < 0) return;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
@@ -692,7 +692,7 @@ void banner_color_session_end(void) {
|
||||
|
||||
struct cm_desc {
|
||||
int refs; /* protocol objects + surfaces (pending / current) */
|
||||
struct banner_color c;
|
||||
struct droiddeck_color c;
|
||||
/* Set on the output / preferred descriptions the compositor serves (never on one a game built
|
||||
* from parameters): get_information is answered rather than refused, with these as the target. */
|
||||
int informative;
|
||||
@@ -727,7 +727,7 @@ static void image_description_get_information(struct wl_client *c, struct wl_res
|
||||
wl_resource_get_version(r), id);
|
||||
if (!info) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(info, NULL, NULL, NULL); /* events only */
|
||||
const struct banner_color *col = &d->c;
|
||||
const struct droiddeck_color *col = &d->c;
|
||||
int32_t xy[8] = { (int32_t)(col->red[0] * 1e6f + 0.5f), (int32_t)(col->red[1] * 1e6f + 0.5f),
|
||||
(int32_t)(col->green[0] * 1e6f + 0.5f), (int32_t)(col->green[1] * 1e6f + 0.5f),
|
||||
(int32_t)(col->blue[0] * 1e6f + 0.5f), (int32_t)(col->blue[1] * 1e6f + 0.5f),
|
||||
@@ -765,12 +765,12 @@ static void image_description_resource_destroy(struct wl_resource *r) {
|
||||
static void make_output_description(struct wl_client *c, struct wl_resource *parent, uint32_t id, const char *what) {
|
||||
struct cm_desc *d = calloc(1, sizeof(*d));
|
||||
if (!d) { wl_client_post_no_memory(c); return; }
|
||||
struct banner_color *col = &d->c;
|
||||
struct droiddeck_color *col = &d->c;
|
||||
col->identity = g_next_identity++;
|
||||
if (!g_next_identity) g_next_identity = 1;
|
||||
col->primaries = WP_COLOR_MANAGER_V1_PRIMARIES_BT2020;
|
||||
col->tf = WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ;
|
||||
col->dataspace = BANNER_ADATASPACE_BT2020_PQ;
|
||||
col->dataspace = DROIDDECK_ADATASPACE_BT2020_PQ;
|
||||
col->has_st2086 = 1;
|
||||
col->red[0] = 0.708f; col->red[1] = 0.292f; col->green[0] = 0.170f; col->green[1] = 0.797f;
|
||||
col->blue[0] = 0.131f; col->blue[1] = 0.046f; col->white[0] = 0.3127f; col->white[1] = 0.3290f;
|
||||
@@ -788,8 +788,8 @@ static void make_output_description(struct wl_client *c, struct wl_resource *par
|
||||
d->refs = 1;
|
||||
wl_resource_set_implementation(r, &image_description_impl, d, image_description_resource_destroy);
|
||||
wp_image_description_v1_send_ready(r, col->identity);
|
||||
banner_log(TAG, "%s asked for %s: answered the display's HDR10 volume (%s), ready and open to get_information",
|
||||
banner_client_name(c), what, col->text);
|
||||
droiddeck_log(TAG, "%s asked for %s: answered the display's HDR10 volume (%s), ready and open to get_information",
|
||||
droiddeck_client_name(c), what, col->text);
|
||||
}
|
||||
|
||||
static void params_create(struct wl_client *client, struct wl_resource *r, uint32_t id) {
|
||||
@@ -801,15 +801,15 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3
|
||||
}
|
||||
struct cm_desc *d = calloc(1, sizeof(*d));
|
||||
if (!d) { wl_client_post_no_memory(client); return; }
|
||||
struct banner_color *c = &d->c;
|
||||
struct droiddeck_color *c = &d->c;
|
||||
c->identity = g_next_identity++;
|
||||
if (!g_next_identity) g_next_identity = 1;
|
||||
c->primaries = p->primaries;
|
||||
c->tf = p->tf;
|
||||
if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_ST2084_PQ)
|
||||
c->dataspace = BANNER_ADATASPACE_BT2020_PQ;
|
||||
c->dataspace = DROIDDECK_ADATASPACE_BT2020_PQ;
|
||||
else if (p->primaries == WP_COLOR_MANAGER_V1_PRIMARIES_BT2020 && p->tf == WP_COLOR_MANAGER_V1_TRANSFER_FUNCTION_HLG)
|
||||
c->dataspace = BANNER_ADATASPACE_BT2020_HLG;
|
||||
c->dataspace = DROIDDECK_ADATASPACE_BT2020_HLG;
|
||||
|
||||
/* HDR metadata, kept only when it makes sense. The PQ defaults stand in for what was not given
|
||||
* (0.005 - 10000 cd/m², the target volume = the primary one); CTA-861.3 treats 0 as unknown. */
|
||||
@@ -870,12 +870,12 @@ static void params_create(struct wl_client *client, struct wl_resource *r, uint3
|
||||
g_hdr.descs++;
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
}
|
||||
banner_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity,
|
||||
banner_client_name(client), c->text, dataspace_name(c->dataspace));
|
||||
droiddeck_log(TAG, "image description #%u from %s: %s -> ready (on a display layer: dataspace %s)", c->identity,
|
||||
droiddeck_client_name(client), c->text, dataspace_name(c->dataspace));
|
||||
if (dropped[0]) {
|
||||
size_t l = strlen(dropped);
|
||||
if (l && dropped[l - 1] == ',') dropped[l - 1] = 0;
|
||||
banner_log(TAG, "image description #%u: dropped HDR metadata that breaks the protocol's rules:%s "
|
||||
droiddeck_log(TAG, "image description #%u: dropped HDR metadata that breaks the protocol's rules:%s "
|
||||
"(Android gets the rest)", c->identity, dropped);
|
||||
}
|
||||
wl_resource_destroy(r); /* create is the creator's destructor */
|
||||
@@ -982,7 +982,7 @@ static struct cm_surf *surf_of(struct wl_resource *surface) {
|
||||
|
||||
static void describe_surface(struct wl_resource *surface, char *out, size_t size) {
|
||||
struct surface *s = surface ? wl_resource_get_user_data(surface) : NULL;
|
||||
if (s) banner_surface_describe(s, out, size);
|
||||
if (s) droiddeck_surface_describe(s, out, size);
|
||||
else snprintf(out, size, "a closed window");
|
||||
}
|
||||
|
||||
@@ -1002,8 +1002,8 @@ static void cm_surface_set_image_description(struct wl_client *c, struct wl_reso
|
||||
struct cm_surf *cs = wl_resource_get_user_data(r);
|
||||
struct cm_desc *d = desc_res ? wl_resource_get_user_data(desc_res) : NULL;
|
||||
if (!cs) {
|
||||
banner_log(TAG, "%s set an image description on a colour-management object whose surface is gone: ignored",
|
||||
banner_client_name(c));
|
||||
droiddeck_log(TAG, "%s set an image description on a colour-management object whose surface is gone: ignored",
|
||||
droiddeck_client_name(c));
|
||||
return;
|
||||
}
|
||||
if (!d) {
|
||||
@@ -1045,7 +1045,7 @@ static void cm_surface_resource_destroy(struct wl_resource *r) {
|
||||
cs->pending_dirty = 1;
|
||||
}
|
||||
|
||||
void banner_color_commit(struct wl_resource *surface) {
|
||||
void droiddeck_color_commit(struct wl_resource *surface) {
|
||||
if (atomic_load(&g_gate) != 1) return;
|
||||
struct cm_surf *cs = surf_of(surface);
|
||||
if (!cs || !cs->pending_dirty) return;
|
||||
@@ -1056,7 +1056,7 @@ void banner_color_commit(struct wl_resource *surface) {
|
||||
char who[160];
|
||||
describe_surface(surface, who, sizeof(who));
|
||||
if (cs->current) {
|
||||
banner_log(TAG, "%s: image description #%u now applies to its frames (%s; perceptual intent)", who,
|
||||
droiddeck_log(TAG, "%s: image description #%u now applies to its frames (%s; perceptual intent)", who,
|
||||
cs->current->c.identity, cs->current->c.text);
|
||||
if (cs->current->c.dataspace) {
|
||||
pthread_mutex_lock(&g_mu);
|
||||
@@ -1064,16 +1064,16 @@ void banner_color_commit(struct wl_resource *surface) {
|
||||
snprintf(g_hdr.applied_who, sizeof(g_hdr.applied_who), "%s", who);
|
||||
pthread_mutex_unlock(&g_mu);
|
||||
if (!g_zero_copy)
|
||||
banner_log(TAG, "%s: zero-copy presentation is OFF, so its HDR frames are composed into the HDR picture "
|
||||
droiddeck_log(TAG, "%s: zero-copy presentation is OFF, so its HDR frames are composed into the HDR picture "
|
||||
"(one extra pass per frame) - switch Zero-copy presentation on for the direct path", who);
|
||||
}
|
||||
} else if (old) {
|
||||
banner_log(TAG, "%s: image description #%u removed - its frames are sRGB again", who, old->c.identity);
|
||||
droiddeck_log(TAG, "%s: image description #%u removed - its frames are sRGB again", who, old->c.identity);
|
||||
}
|
||||
desc_unref(old);
|
||||
}
|
||||
|
||||
const struct banner_color *banner_color_of(struct wl_resource *surface) {
|
||||
const struct droiddeck_color *droiddeck_color_of(struct wl_resource *surface) {
|
||||
if (atomic_load(&g_gate) != 1) return NULL;
|
||||
struct cm_surf *cs = surf_of(surface);
|
||||
return cs && cs->current ? &cs->current->c : NULL;
|
||||
@@ -1125,14 +1125,14 @@ static void cm_get_surface(struct wl_client *c, struct wl_resource *r, uint32_t
|
||||
describe_surface(surface, who, sizeof(who));
|
||||
if (cs->owner) {
|
||||
/* The protocol says surface_exists; a game would be disconnected for it. The newer object wins. */
|
||||
banner_log(TAG, "%s: a second colour-management object for the same surface - the newer one takes over "
|
||||
droiddeck_log(TAG, "%s: a second colour-management object for the same surface - the newer one takes over "
|
||||
"(protocol error surface_exists not raised)", who);
|
||||
wl_resource_set_user_data(cs->owner, NULL);
|
||||
}
|
||||
cs->owner = o;
|
||||
wl_resource_set_implementation(o, &cm_surface_impl, cs, cm_surface_resource_destroy);
|
||||
banner_log(TAG, "%s: colour-management surface created by %s (its Vulkan swapchain asks for a colour space "
|
||||
"other than sRGB)", who, banner_client_name(c));
|
||||
droiddeck_log(TAG, "%s: colour-management surface created by %s (its Vulkan swapchain asks for a colour space "
|
||||
"other than sRGB)", who, droiddeck_client_name(c));
|
||||
}
|
||||
|
||||
static void cm_get_surface_feedback(struct wl_client *c, struct wl_resource *r, uint32_t id, struct wl_resource *surface) {
|
||||
@@ -1186,16 +1186,16 @@ static void bind_cm(struct wl_client *c, void *data, uint32_t ver, uint32_t id)
|
||||
/* One line per program: Mesa binds again for every surface-format query. */
|
||||
if (last_named != c) {
|
||||
last_named = c;
|
||||
banner_log(TAG, "%s bound wp_color_manager_v1 version %u (offered: perceptual intent; parametric descriptions "
|
||||
droiddeck_log(TAG, "%s bound wp_color_manager_v1 version %u (offered: perceptual intent; parametric descriptions "
|
||||
"with mastering metadata; BT.2020 primaries; ST 2084 PQ) - its Vulkan driver can now list "
|
||||
"VK_COLOR_SPACE_HDR10_ST2084_EXT", banner_client_name(c), ver > 1 ? 1u : ver);
|
||||
"VK_COLOR_SPACE_HDR10_ST2084_EXT", droiddeck_client_name(c), ver > 1 ? 1u : ver);
|
||||
}
|
||||
}
|
||||
|
||||
void banner_color_client_gone(struct wl_client *client) {
|
||||
void droiddeck_color_client_gone(struct wl_client *client) {
|
||||
if (atomic_load(&g_gate) != 1 || atomic_load(&g_session_ended)) return;
|
||||
/* A program that presented HDR has left: say where the session stands now, while it is fresh. */
|
||||
const char *name = banner_client_name(client);
|
||||
const char *name = droiddeck_client_name(client);
|
||||
int mine;
|
||||
pthread_mutex_lock(&g_mu);
|
||||
mine = g_hdr.applied_who[0] && name && strstr(g_hdr.applied_who, name) != NULL;
|
||||
@@ -1205,7 +1205,7 @@ void banner_color_client_gone(struct wl_client *client) {
|
||||
|
||||
/* ---------------------------------------------------------------- the gate */
|
||||
|
||||
void banner_color_init(struct wl_display *display) {
|
||||
void droiddeck_color_init(struct wl_display *display) {
|
||||
char why[320] = "";
|
||||
int mode, dxvk_hdr, zc_forced, known, hdr10, id, ratio_avail, api;
|
||||
char name[96], formats[96], source[64];
|
||||
@@ -1229,14 +1229,14 @@ void banner_color_init(struct wl_display *display) {
|
||||
|
||||
/* What asked for HDR, in the words the user knows it by: the editors' setting, or the env override. */
|
||||
char asked[128];
|
||||
if (mode == 2) snprintf(asked, sizeof(asked), "BANNER_WAYLAND_HDR=force (%s)", source);
|
||||
else if (strstr(source, "env")) snprintf(asked, sizeof(asked), "BANNER_WAYLAND_HDR=1 (%s)", source);
|
||||
if (mode == 2) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=force (%s)", source);
|
||||
else if (strstr(source, "env")) snprintf(asked, sizeof(asked), "DROIDDECK_WAYLAND_HDR=1 (%s)", source);
|
||||
else snprintf(asked, sizeof(asked), "HDR output is on (%s)", source);
|
||||
|
||||
int layer_ok = sc_layer_can_tag_hdr();
|
||||
int ahb_ok = ahb_swapchain_advertised();
|
||||
char off_why[128];
|
||||
if (strstr(source, "env")) snprintf(off_why, sizeof(off_why), "BANNER_WAYLAND_HDR=0 in the %s overrides the setting", source);
|
||||
if (strstr(source, "env")) snprintf(off_why, sizeof(off_why), "DROIDDECK_WAYLAND_HDR=0 in the %s overrides the setting", source);
|
||||
else snprintf(off_why, sizeof(off_why), "the HDR output setting is off");
|
||||
if (mode == 0)
|
||||
snprintf(why, sizeof(why), "HDR output is off (%s)", off_why);
|
||||
@@ -1255,16 +1255,16 @@ void banner_color_init(struct wl_display *display) {
|
||||
snprintf(g_gate_why, sizeof(g_gate_why), "%s", why);
|
||||
atomic_store(&g_gate, 0);
|
||||
if (mode) {
|
||||
banner_log(TAG, "HDR gate CLOSED: %s. Nothing is advertised (no wp_color_manager_v1, no 10-bit dma-buf "
|
||||
droiddeck_log(TAG, "HDR gate CLOSED: %s. Nothing is advertised (no wp_color_manager_v1, no 10-bit dma-buf "
|
||||
"formats): games see an SDR display, exactly as without the switch", why);
|
||||
if (dxvk_hdr)
|
||||
banner_log(TAG, "DXVK_HDR=1 is set: DXGI will still claim an HDR display that no swapchain can get here "
|
||||
droiddeck_log(TAG, "DXVK_HDR=1 is set: DXGI will still claim an HDR display that no swapchain can get here "
|
||||
"(games that check fall back to SDR; some show washed-out colours) - remove it on this display");
|
||||
log_verdict(1);
|
||||
} else if (dxvk_hdr || (known && hdr10)) {
|
||||
/* Off, and silent unless it is worth a line: a display that could show HDR10, or a DXVK
|
||||
* switch that promises games an HDR display they cannot get. */
|
||||
banner_log(TAG, "HDR output off for this session (%s)%s%s", off_why,
|
||||
droiddeck_log(TAG, "HDR output off for this session (%s)%s%s", off_why,
|
||||
(known && hdr10) ? " - this display lists HDR10, so switching HDR output on for this game would "
|
||||
"offer it to games" : "",
|
||||
dxvk_hdr ? " - but DXVK_HDR=1 is set, so DXGI claims an HDR display the game cannot get a "
|
||||
@@ -1276,25 +1276,25 @@ void banner_color_init(struct wl_display *display) {
|
||||
if (!wl_global_create(display, &wp_color_manager_v1_interface, 1, NULL, bind_cm)) {
|
||||
snprintf(g_gate_why, sizeof(g_gate_why), "creating the wp_color_manager_v1 global failed");
|
||||
atomic_store(&g_gate, 0);
|
||||
banner_log("error", "color: wp_color_manager_v1 global creation failed - HDR gate closed");
|
||||
droiddeck_log("error", "color: wp_color_manager_v1 global creation failed - HDR gate closed");
|
||||
log_verdict(1);
|
||||
return;
|
||||
}
|
||||
atomic_store(&g_gate, 1);
|
||||
char syms[160];
|
||||
sc_layer_hdr_symbols(syms, sizeof(syms));
|
||||
banner_log(TAG, "HDR gate %s: %s and %s. Offering games HDR10: wp_color_manager_v1 version 1 (BT.2020 primaries "
|
||||
droiddeck_log(TAG, "HDR gate %s: %s and %s. Offering games HDR10: wp_color_manager_v1 version 1 (BT.2020 primaries "
|
||||
"+ ST 2084 PQ, parametric descriptions with mastering metadata) and 10-bit AB30/XB30 dma-buf formats; HDR "
|
||||
"frames go on the game's own display layer as BT2020_PQ (%s)",
|
||||
mode == 2 ? "FORCED OPEN (testing)" : "OPEN", asked, disp, syms);
|
||||
if (mode == 2 && !hdr10)
|
||||
banner_log(TAG, "BANNER_WAYLAND_HDR=force on a display without HDR10 - testing only: SurfaceFlinger will tone-map "
|
||||
droiddeck_log(TAG, "DROIDDECK_WAYLAND_HDR=force on a display without HDR10 - testing only: SurfaceFlinger will tone-map "
|
||||
"the game layer for this panel (expect GPU/CLIENT composition for it), nothing looks HDR");
|
||||
if (zc_forced)
|
||||
banner_log(TAG, "zero-copy presentation turned on for this session: the HDR game's own 10-bit frames go straight "
|
||||
droiddeck_log(TAG, "zero-copy presentation turned on for this session: the HDR game's own 10-bit frames go straight "
|
||||
"to its display layer (the best path; anything that needs the compositor gets the composed HDR picture)");
|
||||
if (!dxvk_hdr)
|
||||
banner_log(TAG, "DXVK_HDR=1 is not in the game's environment: DXVK games will not see an HDR display in DXGI "
|
||||
droiddeck_log(TAG, "DXVK_HDR=1 is not in the game's environment: DXVK games will not see an HDR display in DXGI "
|
||||
"(dxgi.enableHDR in a dxvk.conf does the same) - add DXVK_HDR=1 to the container's or shortcut's "
|
||||
"environment variables");
|
||||
(void)max_avg; (void)min_lum;
|
||||
|
||||
@@ -16,8 +16,8 @@
|
||||
|
||||
#include "linux-dmabuf-v1-server-protocol.h"
|
||||
#include "vk_present.h"
|
||||
#include "banner_ext.h"
|
||||
#include "banner_color.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "droiddeck_color.h"
|
||||
#include "compositor_internal.h"
|
||||
|
||||
/* ------------------------------------------------------------ zwp_linux_dmabuf_v1 */
|
||||
@@ -112,7 +112,7 @@ static const struct zwp_linux_dmabuf_v1_interface dmabuf_impl = {
|
||||
/* The advertised format/modifier table, built at the first bind from what the renderer's driver
|
||||
* can import (vkp_dmabuf_modifiers). INVALID is always offered too (Mesa drops it; other clients
|
||||
* may use it for the implicit path). Without a renderer the list is LINEAR + INVALID, as before. */
|
||||
/* The last two rows are HDR10's (banner_color.h): A2B10G10R10 as AB30 (alpha) + XB30 (opaque) - Mesa
|
||||
/* The last two rows are HDR10's (droiddeck_color.h): A2B10G10R10 as AB30 (alpha) + XB30 (opaque) - Mesa
|
||||
* lists a VkFormat only when both are advertised, and it is the one 10-bit layout our zero-copy WSI
|
||||
* can put in a gralloc buffer (AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM). They are advertised ONLY
|
||||
* while the HDR gate is open, and after the 8-bit rows, so every other session - and every client that
|
||||
@@ -132,7 +132,7 @@ static void dmabuf_build_formats(void) {
|
||||
char line[320];
|
||||
int pos = 0, compressed = 0;
|
||||
g_dmabuf_fmts_ready = 1;
|
||||
g_dmabuf_nfmt = banner_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR;
|
||||
g_dmabuf_nfmt = droiddeck_color_hdr_open() ? DMABUF_NFMT_MAX : DMABUF_NFMT_SDR;
|
||||
for (int f = 0; f < g_dmabuf_nfmt; f++) {
|
||||
uint64_t got[DMABUF_NMOD];
|
||||
int n = vkp_dmabuf_modifiers(g_dmabuf_fmts[f].fmt, got, DMABUF_NMOD), k = 0;
|
||||
@@ -155,10 +155,10 @@ static void dmabuf_build_formats(void) {
|
||||
vkp_modifier_name(g_dmabuf_fmts[f].mods[i]));
|
||||
if (pos >= (int)sizeof(line)) pos = (int)sizeof(line) - 1;
|
||||
}
|
||||
banner_log("dmabuf", "formats: %s%s", line,
|
||||
!g_ubwc ? " (BANNER_WAYLAND_UBWC=0: qcom_compressed not advertised)" : "");
|
||||
droiddeck_log("dmabuf", "formats: %s%s", line,
|
||||
!g_ubwc ? " (DROIDDECK_WAYLAND_UBWC=0: qcom_compressed not advertised)" : "");
|
||||
if (g_ubwc && !compressed)
|
||||
banner_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: "
|
||||
droiddeck_log("dmabuf", "the compositor's driver (%s) reports no importable qcom_compressed layout: "
|
||||
"game swapchains stay linear", vkp_gpu_name());
|
||||
if (g_dmabuf_nfmt > DMABUF_NFMT_SDR) {
|
||||
/* The rows above always carry LINEAR; say what the compositor's own driver can really import
|
||||
@@ -166,7 +166,7 @@ static void dmabuf_build_formats(void) {
|
||||
uint64_t got[DMABUF_NMOD];
|
||||
int n = vkp_dmabuf_modifiers(DRM_XBGR2101010, got, DMABUF_NMOD), ubwc10 = 0;
|
||||
for (int i = 0; i < n; i++) if (got[i] == VKP_MOD_QCOM_COMPRESSED) ubwc10 = 1;
|
||||
banner_log("color", "10-bit dma-buf formats AB30/XB30 advertised for HDR10; the compositor's driver (%s) "
|
||||
droiddeck_log("color", "10-bit dma-buf formats AB30/XB30 advertised for HDR10; the compositor's driver (%s) "
|
||||
"imports XB30 %s", vkp_gpu_name(),
|
||||
n == 0 ? "with no layout it reports (copy path unlikely; display layer only)"
|
||||
: ubwc10 ? "linear and UBWC" : "linear only (UBWC 10-bit frames: display layer only)");
|
||||
@@ -237,7 +237,7 @@ static void dmabuf_build_feedback(void) {
|
||||
}
|
||||
if (!n) return;
|
||||
|
||||
int fd = (int)syscall(__NR_memfd_create, "banner-dmabuf-formats",
|
||||
int fd = (int)syscall(__NR_memfd_create, "droiddeck-dmabuf-formats",
|
||||
MFD_CLOEXEC | MFD_ALLOW_SEALING);
|
||||
if (fd < 0) { WLOGE("dmabuf feedback: memfd_create failed (%s)", strerror(errno)); return; }
|
||||
size_t size = (size_t)n * sizeof(entries[0]);
|
||||
@@ -251,14 +251,14 @@ static void dmabuf_build_feedback(void) {
|
||||
g_fmt_table_fd = fd;
|
||||
g_fmt_table_size = size;
|
||||
g_fmt_table_n = (uint16_t)n;
|
||||
banner_log("dmabuf", "feedback ready: %d format/modifier pairs, main device %u:%u",
|
||||
droiddeck_log("dmabuf", "feedback ready: %d format/modifier pairs, main device %u:%u",
|
||||
n, (unsigned)major(g_main_device), (unsigned)minor(g_main_device));
|
||||
/* Vulkan games never need the node. Mesa's EGL did until Wayland layer versionCode 9: without
|
||||
* one it fell back to a software path that draws nothing here (black window, sound plays). */
|
||||
if (!g_main_device)
|
||||
banner_log("dmabuf", "%s: OpenGL games need Wayland layer versionCode 9 or newer, "
|
||||
droiddeck_log("dmabuf", "%s: OpenGL games need Wayland layer versionCode 9 or newer, "
|
||||
"which runs OpenGL on the GPU without a DRM node; older layers show a black window",
|
||||
g_no_render_node ? "no DRM device named (forced by BANNER_WAYLAND_NO_RENDER_NODE=1)"
|
||||
g_no_render_node ? "no DRM device named (forced by DROIDDECK_WAYLAND_NO_RENDER_NODE=1)"
|
||||
: "this device gives apps no display (DRM) device (/dev/dri)");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* wp_single_pixel_buffer_manager_v1 (version 1): a wl_buffer of one pixel of one colour, which a
|
||||
* client stretches over a surface with wp_viewporter. KWin's Wayland backend - the desktop's KWin
|
||||
* nested in this compositor - refuses to start without it. The surface takes the pixel as a 1x1
|
||||
* image, the way it takes a wl_shm buffer (compositor.c, take_pixel).
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include "droiddeck_ext.h"
|
||||
#include "single-pixel-buffer-v1-server-protocol.h"
|
||||
|
||||
struct single_pixel {
|
||||
uint8_t bgra[4]; /* premultiplied, as wl_shm's ARGB8888 lies in memory */
|
||||
};
|
||||
|
||||
static void buffer_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static const struct wl_buffer_interface buffer_impl = { .destroy = buffer_destroy };
|
||||
|
||||
static void buffer_free(struct wl_resource *r) { free(wl_resource_get_user_data(r)); }
|
||||
|
||||
int single_pixel_buffer_get(struct wl_resource *buffer, uint8_t bgra[4]) {
|
||||
if (!buffer || !wl_resource_instance_of(buffer, &wl_buffer_interface, &buffer_impl)) return 0;
|
||||
struct single_pixel *p = wl_resource_get_user_data(buffer);
|
||||
for (int i = 0; i < 4; i++) bgra[i] = p->bgra[i];
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void mgr_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static void mgr_create_buffer(struct wl_client *c, struct wl_resource *r, uint32_t id,
|
||||
uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha) {
|
||||
struct single_pixel *p = calloc(1, sizeof(*p));
|
||||
struct wl_resource *buffer = p ? wl_resource_create(c, &wl_buffer_interface, 1, id) : NULL;
|
||||
if (!buffer) { free(p); wl_client_post_no_memory(c); return; }
|
||||
/* The protocol's values span the whole u32 range; the top byte is the 8-bit channel. */
|
||||
p->bgra[0] = blue >> 24;
|
||||
p->bgra[1] = green >> 24;
|
||||
p->bgra[2] = red >> 24;
|
||||
p->bgra[3] = alpha >> 24;
|
||||
wl_resource_set_implementation(buffer, &buffer_impl, p, buffer_free);
|
||||
}
|
||||
static const struct wp_single_pixel_buffer_manager_v1_interface mgr_impl = {
|
||||
.destroy = mgr_destroy, .create_u32_rgba_buffer = mgr_create_buffer,
|
||||
};
|
||||
static void bind_manager(struct wl_client *c, void *data, uint32_t ver, uint32_t id) {
|
||||
struct wl_resource *r = wl_resource_create(c, &wp_single_pixel_buffer_manager_v1_interface, ver, id);
|
||||
if (!r) { wl_client_post_no_memory(c); return; }
|
||||
wl_resource_set_implementation(r, &mgr_impl, NULL, NULL);
|
||||
}
|
||||
|
||||
void single_pixel_init(struct wl_display *display) {
|
||||
wl_global_create(display, &wp_single_pixel_buffer_manager_v1_interface, 1, NULL, bind_manager);
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
* Focus model. winewayland enables its text input as soon as our `enter` names a surface and
|
||||
* routes every IME update to that surface's window - inside that window's process (the update
|
||||
* list is per process). Keyboard focus in this compositor sits on the desktop surface (the
|
||||
* desktop owner's process), so text input can't follow it; it follows banner_ime_target():
|
||||
* desktop owner's process), so text input can't follow it; it follows droiddeck_ime_target():
|
||||
* the program window last clicked, else the topmost program window. Clicking into notepad
|
||||
* moves the text-input focus to notepad's process, which is where the edit control lives.
|
||||
*
|
||||
@@ -13,7 +13,7 @@
|
||||
* them (enable resets the state as the protocol says). We answer with `done(serial)` only when
|
||||
* we sent events (preedit/commit strings), never for every commit.
|
||||
*
|
||||
* Host side. banner_on_text_input(enabled, program, cursor rect in scene pixels) tells the app
|
||||
* Host side. droiddeck_on_text_input(enabled, program, cursor rect in scene pixels) tells the app
|
||||
* when a program starts/stops accepting IME text or moves its caret (Wine reports the rect only
|
||||
* when an edit control positions its IME composition window, via ImmSetCompositionWindow).
|
||||
* Typed text arrives through text_input_host_*: preedit_string / commit_string + done.
|
||||
@@ -23,7 +23,7 @@
|
||||
#define _GNU_SOURCE 1
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "banner_ext.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "text-input-unstable-v3-server-protocol.h"
|
||||
|
||||
#ifndef KEY_BACKSPACE
|
||||
@@ -58,7 +58,7 @@ static struct wl_resource *g_target; /* surface text input is focused
|
||||
static int g_told_enabled, g_told_rect[4];
|
||||
static struct text_input *g_told_ti;
|
||||
|
||||
static const char *ti_program(struct text_input *ti) { return banner_client_name(ti->client); }
|
||||
static const char *ti_program(struct text_input *ti) { return droiddeck_client_name(ti->client); }
|
||||
|
||||
/* The enabled text input focused on the current target, if any. */
|
||||
static struct text_input *active_input(void) {
|
||||
@@ -74,22 +74,22 @@ static void tell_app(void) {
|
||||
int enabled = ti != NULL, rect[4] = {0, 0, 0, 0};
|
||||
if (ti) {
|
||||
int ox = 0, oy = 0;
|
||||
banner_surface_scene_origin(ti->entered, &ox, &oy);
|
||||
droiddeck_surface_scene_origin(ti->entered, &ox, &oy);
|
||||
rect[0] = ti->rect[0] + ox; rect[1] = ti->rect[1] + oy;
|
||||
rect[2] = ti->rect[2]; rect[3] = ti->rect[3];
|
||||
}
|
||||
if (enabled == g_told_enabled && ti == g_told_ti && !memcmp(rect, g_told_rect, sizeof(rect))) return;
|
||||
if (enabled && (!g_told_enabled || ti != g_told_ti))
|
||||
banner_log("text-input", "text input enabled by %s (cursor rect %d,%d %dx%d)", ti_program(ti),
|
||||
droiddeck_log("text-input", "text input enabled by %s (cursor rect %d,%d %dx%d)", ti_program(ti),
|
||||
rect[0], rect[1], rect[2], rect[3]);
|
||||
else if (enabled)
|
||||
banner_log("text-input", "cursor rect from %s: %d,%d %dx%d", ti_program(ti), rect[0], rect[1], rect[2], rect[3]);
|
||||
droiddeck_log("text-input", "cursor rect from %s: %d,%d %dx%d", ti_program(ti), rect[0], rect[1], rect[2], rect[3]);
|
||||
else
|
||||
banner_log("text-input", "text input disabled%s%s", g_told_ti ? " by " : "", g_told_ti ? ti_program(g_told_ti) : "");
|
||||
droiddeck_log("text-input", "text input disabled%s%s", g_told_ti ? " by " : "", g_told_ti ? ti_program(g_told_ti) : "");
|
||||
g_told_enabled = enabled;
|
||||
g_told_ti = ti;
|
||||
memcpy(g_told_rect, rect, sizeof(rect));
|
||||
banner_on_text_input(enabled, enabled ? ti_program(ti) : "", rect[0], rect[1], rect[2], rect[3]);
|
||||
droiddeck_on_text_input(enabled, enabled ? ti_program(ti) : "", rect[0], rect[1], rect[2], rect[3]);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ focus */
|
||||
@@ -102,8 +102,8 @@ static void send_leave(struct text_input *ti) {
|
||||
ti->has_preedit = 0;
|
||||
}
|
||||
|
||||
void banner_text_input_refocus(void) {
|
||||
struct wl_resource *t = banner_ime_target();
|
||||
void droiddeck_text_input_refocus(void) {
|
||||
struct wl_resource *t = droiddeck_ime_target();
|
||||
struct text_input *ti;
|
||||
if (t == g_target) return;
|
||||
wl_list_for_each(ti, &g_inputs, link)
|
||||
@@ -121,7 +121,7 @@ void banner_text_input_refocus(void) {
|
||||
wl_display_flush_clients(g_disp);
|
||||
}
|
||||
|
||||
void banner_text_input_surface_gone(struct wl_resource *surface) {
|
||||
void droiddeck_text_input_surface_gone(struct wl_resource *surface) {
|
||||
struct text_input *ti;
|
||||
wl_list_for_each(ti, &g_inputs, link)
|
||||
if (ti->entered == surface) { ti->entered = NULL; ti->enabled = 0; ti->has_preedit = 0; }
|
||||
@@ -136,7 +136,7 @@ static void ti_res_destroy(struct wl_resource *r) {
|
||||
if (!ti) return;
|
||||
wl_list_remove(&ti->link);
|
||||
if (g_told_ti == ti) { g_told_ti = NULL; g_told_enabled = 0; memset(g_told_rect, 0, sizeof(g_told_rect));
|
||||
banner_on_text_input(0, "", 0, 0, 0, 0); }
|
||||
droiddeck_on_text_input(0, "", 0, 0, 0, 0); }
|
||||
free(ti);
|
||||
}
|
||||
|
||||
@@ -235,13 +235,13 @@ static int32_t utf8_offset(const char *s, size_t len, int chars) {
|
||||
void text_input_host_commit(const char *utf8, size_t len) {
|
||||
struct text_input *ti = active_input();
|
||||
if (!ti) {
|
||||
banner_log("text-input", "typed text (%zu chars) dropped: no program accepts text input", utf8_chars(utf8, len));
|
||||
droiddeck_log("text-input", "typed text (%zu chars) dropped: no program accepts text input", utf8_chars(utf8, len));
|
||||
return;
|
||||
}
|
||||
if (ti->has_preedit) { zwp_text_input_v3_send_preedit_string(ti->res, "", 0, 0); ti->has_preedit = 0; }
|
||||
zwp_text_input_v3_send_commit_string(ti->res, utf8);
|
||||
zwp_text_input_v3_send_done(ti->res, ti->serial);
|
||||
banner_log("text-input", "committed %zu chars to %s", utf8_chars(utf8, len), ti_program(ti));
|
||||
droiddeck_log("text-input", "committed %zu chars to %s", utf8_chars(utf8, len), ti_program(ti));
|
||||
}
|
||||
|
||||
void text_input_host_preedit(const char *utf8, size_t len, int cursor_begin, int cursor_end) {
|
||||
@@ -264,9 +264,9 @@ void text_input_host_delete(int before, int after) {
|
||||
zwp_text_input_v3_send_done(ti->res, ti->serial);
|
||||
ti->has_preedit = 0;
|
||||
}
|
||||
for (int i = 0; i < before; i++) { banner_inject_key(KEY_BACKSPACE, 1); banner_inject_key(KEY_BACKSPACE, 0); }
|
||||
for (int i = 0; i < after; i++) { banner_inject_key(KEY_DELETE, 1); banner_inject_key(KEY_DELETE, 0); }
|
||||
banner_log("text-input", "deleted %d before / %d after the caret (as key presses)", before, after);
|
||||
for (int i = 0; i < before; i++) { droiddeck_inject_key(KEY_BACKSPACE, 1); droiddeck_inject_key(KEY_BACKSPACE, 0); }
|
||||
for (int i = 0; i < after; i++) { droiddeck_inject_key(KEY_DELETE, 1); droiddeck_inject_key(KEY_DELETE, 0); }
|
||||
droiddeck_log("text-input", "deleted %d before / %d after the caret (as key presses)", before, after);
|
||||
}
|
||||
|
||||
void text_input_init(struct wl_display *display) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* missing. We send no icon_size (any size is fine) and `done` at bind, as the protocol asks.
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include "banner_ext.h"
|
||||
#include "droiddeck_ext.h"
|
||||
#include "xdg-toplevel-icon-v1-server-protocol.h"
|
||||
|
||||
static void icon_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
|
||||
@@ -11,14 +11,27 @@ import com.droiddeck.launcher.session.GpuClockPin
|
||||
* sandboxes are started through (BwrapSpawner).
|
||||
*/
|
||||
class App : Application() {
|
||||
override fun attachBaseContext(base: android.content.Context) =
|
||||
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(base))
|
||||
|
||||
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
|
||||
super.onConfigurationChanged(newConfig)
|
||||
com.droiddeck.launcher.core.AppLanguage.systemChanged(newConfig)
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
CrashHandler.install(this)
|
||||
// Before anything else touches the session prefs: a new install's first read decides it.
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this)
|
||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||
GpuClockPin.clearLeftover(this)
|
||||
BwrapSpawner.start(this)
|
||||
com.droiddeck.launcher.frontend.GameFileSync.start(this)
|
||||
// The game stores the Stores section can talk to; the native engine loads only when one needs it.
|
||||
com.droiddeck.launcher.stores.StoresState.init(this)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.gog.GogBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.epic.EpicBackend)
|
||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.session.ComponentsManager
|
||||
import com.droiddeck.launcher.session.ProtonDefault
|
||||
|
||||
/**
|
||||
* The Components page's state and work: the Protons and their DXVK/VKD3D sets, the Nightlies
|
||||
@@ -20,6 +21,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
var compChecking by mutableStateOf(false)
|
||||
var compBusy by mutableStateOf<String?>(null)
|
||||
var compDownloads by mutableStateOf<Map<String, Int>>(emptyMap())
|
||||
private var shownDefault: String? = null
|
||||
|
||||
/** Reads the Protons (and on first open saves their originals) off the UI thread; the Nightlies list comes from its cache. */
|
||||
fun refreshComponents(snapshotFirst: Boolean = false) {
|
||||
@@ -28,19 +30,40 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
runCatching { ComponentsManager.applyQueued(activity) }
|
||||
val snap = runCatching { ComponentsManager.snapshot(activity) }.onFailure { Log.w(TAG, "components", it) }.getOrNull()
|
||||
val cat = runCatching { ComponentsManager.catalog(activity, false) }.getOrNull()
|
||||
val chosen = snap?.let { s -> runCatching { ProtonDefault.selectedId(activity, s.protons.map { it.proton }) }.getOrNull() }
|
||||
ui.post {
|
||||
compSnapshot = snap ?: ComponentsManager.Snapshot(emptyList(), emptyList())
|
||||
if (cat != null && cat.fetchedAt > 0) { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
||||
if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) compProton = snap?.protons?.firstOrNull()?.proton?.id
|
||||
if (chosen != null && chosen != shownDefault) {
|
||||
shownDefault = chosen
|
||||
compProton = chosen
|
||||
} else if (compProton == null || snap?.protons?.none { it.proton.id == compProton } == true) {
|
||||
compProton = chosen ?: snap?.protons?.firstOrNull()?.proton?.id
|
||||
}
|
||||
}
|
||||
}, "components").start()
|
||||
}
|
||||
|
||||
fun chooseProton(id: String) {
|
||||
val proton = compSnapshot?.protons?.firstOrNull { it.proton.id == id }?.proton ?: return
|
||||
compProton = id
|
||||
Thread({
|
||||
val message = runCatching {
|
||||
when (ProtonDefault.request(activity, proton)) {
|
||||
ProtonDefault.Outcome.LIVE -> activity.getString(R.string.comp_default_live, proton.name)
|
||||
ProtonDefault.Outcome.NEXT_START -> activity.getString(R.string.comp_default_next, proton.name)
|
||||
ProtonDefault.Outcome.NOT_RUNNABLE -> activity.getString(R.string.comp_default_not_runnable, proton.name)
|
||||
}
|
||||
}.getOrElse { e -> activity.getString(R.string.comp_default_failed, e.message ?: e.javaClass.simpleName) }
|
||||
ui.post { android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show() }
|
||||
}, "components-default").start()
|
||||
}
|
||||
|
||||
fun componentAction(label: String, work: () -> String) {
|
||||
if (compBusy != null) return
|
||||
compBusy = label
|
||||
Thread({
|
||||
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
|
||||
val message = runCatching(work).getOrElse { e -> activity.getString(R.string.main_action_failed, label, e.message ?: e.javaClass.simpleName) }
|
||||
ui.post {
|
||||
compBusy = null
|
||||
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
@@ -56,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
val cat = runCatching { ComponentsManager.catalog(activity, true) }.getOrNull()
|
||||
ui.post {
|
||||
compChecking = false
|
||||
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, "The Nightlies could not be reached", android.widget.Toast.LENGTH_LONG).show()
|
||||
if (cat == null || cat.items.isEmpty()) android.widget.Toast.makeText(activity, activity.getString(R.string.comp_nightlies_unreachable), android.widget.Toast.LENGTH_LONG).show()
|
||||
else { compCatalog = cat.items; compCatalogAt = cat.fetchedAt }
|
||||
}
|
||||
}, "components-catalog").start()
|
||||
@@ -68,8 +91,8 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
|
||||
Thread({
|
||||
val message = runCatching {
|
||||
val pkg = ComponentsManager.download(activity, item) { pc -> ui.post { if (compDownloads.containsKey(item.file)) compDownloads = compDownloads + (item.file to pc) } }
|
||||
"Stored ${pkg.version}"
|
||||
}.getOrElse { e -> "Download failed: ${e.message ?: e.javaClass.simpleName}" }
|
||||
activity.getString(R.string.comp_stored, pkg.version)
|
||||
}.getOrElse { e -> activity.getString(R.string.comp_download_failed, e.message ?: e.javaClass.simpleName) }
|
||||
ui.post {
|
||||
compDownloads = compDownloads - item.file
|
||||
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||
|
||||
@@ -7,6 +7,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.runtime.DeckyManager
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Decky Loader's state in the launcher: what is installed, the releases on offer and an install
|
||||
@@ -18,6 +19,8 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
||||
var deckyChecking by mutableStateOf(false)
|
||||
var deckyStage by mutableStateOf<String?>(null)
|
||||
var deckyPercent by mutableIntStateOf(-1)
|
||||
/** True while the stage is the plugin's binary download (DeckyManager.downloadingBinary). */
|
||||
var deckyDownloadingBinary by mutableStateOf(false)
|
||||
var deckySupervisor by mutableStateOf(false)
|
||||
var deckyReleaseRequest = 0
|
||||
|
||||
@@ -40,15 +43,33 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
|
||||
|
||||
fun installDecky(release: DeckyManager.Release) {
|
||||
if (deckyStage != null || SessionState.running) return
|
||||
deckyStage = "Starting…"; deckyPercent = -1
|
||||
deckyStage = activity.getString(R.string.store_starting); deckyPercent = -1
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
DeckyManager.install(activity, release) { label, value -> ui.post { deckyStage = label; deckyPercent = value } }
|
||||
}.getOrElse { error -> "Decky install failed: ${error.message ?: error.javaClass.simpleName}" }
|
||||
}.getOrElse { error -> activity.getString(R.string.decky_install_failed, error.message ?: error.javaClass.simpleName) }
|
||||
ui.post {
|
||||
deckyStage = null; deckyPercent = -1; deckyInstalled = DeckyManager.installed(activity)
|
||||
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "install-decky").start()
|
||||
}
|
||||
|
||||
fun importPluginZip(archive: File) {
|
||||
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
|
||||
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
|
||||
Thread({
|
||||
val problem = runCatching {
|
||||
DeckyManager.installPluginZip(activity, archive) { label, value ->
|
||||
val binary = DeckyManager.downloadingBinary
|
||||
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
|
||||
}
|
||||
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) }
|
||||
ui.post {
|
||||
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
|
||||
val message = problem ?: activity.getString(R.string.decky_plugin_installed)
|
||||
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "import-decky-plugin").start()
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,12 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import com.droiddeck.launcher.gpu.DriverBundle
|
||||
import com.droiddeck.launcher.core.DeviceSupport
|
||||
import com.droiddeck.launcher.gpu.DriverPairs
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
import com.droiddeck.launcher.gpu.SystemVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipDriver
|
||||
import com.droiddeck.launcher.gpu.TurnipReleases
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
@@ -37,13 +39,15 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
/** The latest Banners-Turnip release as each driver menu offers it (see [refreshReleaseRows]). */
|
||||
var linuxDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||
var androidDownloads by mutableStateOf<List<com.droiddeck.launcher.ui.DownloadRow>>(emptyList())
|
||||
var releaseStatus by mutableStateOf("Not checked yet - tap refresh to look for new drivers")
|
||||
// Empty until the first refresh: the activity has no context yet while its fields are made.
|
||||
var releaseStatus by mutableStateOf("")
|
||||
var releaseChecking by mutableStateOf(false)
|
||||
var canRestoreBundled by mutableStateOf(false)
|
||||
/** Asset name -> download percent, while it downloads. */
|
||||
private val releaseProgress = HashMap<String, Int>()
|
||||
var linuxSelected by mutableStateOf("")
|
||||
val gpu: GpuInfo = GpuInfo.detect()
|
||||
var gpu: GpuInfo = GpuInfo.detect()
|
||||
private set
|
||||
// Read in refreshDrivers/ensureAuto: the activity has no context yet while its fields are made.
|
||||
var mode by mutableStateOf(SessionPrefs.GPU_DRIVERS_AUTO)
|
||||
var pairRows by mutableStateOf<List<PairRow>>(emptyList())
|
||||
@@ -57,13 +61,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
private var autoCheckedThisProcess = false
|
||||
|
||||
fun state() = GpuDriversState(
|
||||
gpuName = gpu.name, gpuFamily = gpu.family.label, soc = gpu.soc, supportText = gpu.supportText,
|
||||
gpuName = gpu.displayName(activity), gpuFamily = if (gpu.name.contains("Xclipse", ignoreCase = true)) gpu.family.label(gpu.name) else gpu.family.label(activity), soc = gpu.soc, supportText = gpu.supportText(activity),
|
||||
supported = gpu.support == GpuInfo.Support.TESTED, unsupported = gpu.support == GpuInfo.Support.UNSUPPORTED,
|
||||
auto = mode == SessionPrefs.GPU_DRIVERS_AUTO, pairs = pairRows, busy = pairBusy, percent = pairPercent,
|
||||
autoStatus = autoStatus, releaseStatus = releaseStatus, checking = releaseChecking,
|
||||
autoStatus = autoStatus, releaseStatus = releaseStatus.ifEmpty { activity.getString(R.string.drivers_not_checked) }, checking = releaseChecking,
|
||||
linuxRows = linuxRows, linuxSelected = linuxSelected, androidRows = androidRows, androidSelected = androidSelected,
|
||||
linuxDownloads = linuxDownloads, androidDownloads = androidDownloads, canRestoreBundled = canRestoreBundled,
|
||||
activeBundle = activeBundle,
|
||||
activeBundle = activeBundle, powerVr = gpu.family == GpuInfo.Family.POWERVR,
|
||||
systemPowerVr = SystemVulkanDriver.usesDefault(linuxSelected),
|
||||
)
|
||||
var androidRows by mutableStateOf<List<DriverRow>>(emptyList())
|
||||
var androidSelected by mutableStateOf("")
|
||||
@@ -73,10 +78,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
fun origin(id: String) = if (TurnipReleases.isDownloaded(activity, id)) DriverRow.DOWNLOADED else DriverRow.IMPORTED
|
||||
val bundles = DriverBundle.all(activity)
|
||||
fun bundleRow(id: String, linux: Boolean) = bundles.firstOrNull { (if (linux) it.linuxId else it.androidId) == id }?.let {
|
||||
DriverRow(id, it.label, "Android + Linux: sets the ${if (linux) "display" else "runtime"} driver with it", true, DriverRow.BUNDLE)
|
||||
DriverRow(id, it.label, activity.getString(if (linux) R.string.drivers_bundle_sets_display else R.string.drivers_bundle_sets_runtime), true, DriverRow.BUNDLE)
|
||||
}
|
||||
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
|
||||
if (id.isEmpty()) DriverRow("", "Runtime default", "the Turnip built into the runtime", false)
|
||||
if (id.isEmpty()) DriverRow("", activity.getString(if (gpu.family == GpuInfo.Family.POWERVR) R.string.gpu_system_powervr else R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
|
||||
else bundleRow(id, linux = true) ?: DriverRow(
|
||||
id, lm.getDriverName(id),
|
||||
listOfNotNull(
|
||||
@@ -92,8 +97,8 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
val auto = td.autoId()
|
||||
androidRows = buildList {
|
||||
add(DriverRow(
|
||||
TurnipDriver.AUTO, "Auto - picked by GPU",
|
||||
if (auto == "system") "system Vulkan: no bundled build for this GPU" else "${td.displayName(auto)} (bundled)",
|
||||
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)),
|
||||
false,
|
||||
))
|
||||
for (id in td.visibleBundled()) add(DriverRow(id, td.displayName(id), td.driverVersion(id), true, DriverRow.BUNDLED))
|
||||
@@ -109,7 +114,9 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
/** One line for the settings row that opens this: "Auto · WinNative · Balanced". */
|
||||
fun summary(): String {
|
||||
val active = pairRows.firstOrNull { it.active }?.name ?: activeBundle
|
||||
return (if (mode == SessionPrefs.GPU_DRIVERS_AUTO) "Auto" else "Manual") + (active?.let { " · $it" } ?: "")
|
||||
?: if (SystemVulkanDriver.usesDefault(linuxSelected) && androidSelected == TurnipDriver.AUTO) activity.getString(R.string.gpu_system_powervr) else null
|
||||
val label = activity.getString(if (mode == SessionPrefs.GPU_DRIVERS_AUTO) R.string.common_auto else R.string.drivers_manual)
|
||||
return active?.let { activity.getString(R.string.drivers_summary, label, it) } ?: label
|
||||
}
|
||||
|
||||
/** The pairs the last check found, with what is installed and in use; this GPU's first. */
|
||||
@@ -125,11 +132,13 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
val mb = p.assets.sumOf { it.size } / 1_048_576.0
|
||||
PairRow(
|
||||
key = p.key, name = p.name, version = p.version,
|
||||
detail = if (!p.complete) "Only one half is published right now" else "%.0f MB for both".format(mb),
|
||||
detail = if (!p.complete) activity.getString(R.string.drivers_half_published) else activity.getString(R.string.drivers_pair_size, mb),
|
||||
recommended = p.key == recommended, suits = p.suits(gpu), complete = p.complete,
|
||||
installed = displayId != null && linuxId != null,
|
||||
active = displayId != null && linuxId != null &&
|
||||
SessionPrefs.androidDriver(activity) == displayId && SessionPrefs.linuxDriver(activity) == linuxId,
|
||||
active = displayId != null && linuxId != null && SessionPrefs.linuxDriver(activity) == linuxId &&
|
||||
(SessionPrefs.androidDriver(activity) == displayId ||
|
||||
// A Mali pair under Auto: the display is the phone's own driver.
|
||||
(gpu.family.mali && DriverPairs.isNonAdreno(p.key) && SessionPrefs.androidDriver(activity) == TurnipDriver.AUTO)),
|
||||
)
|
||||
}.sortedByDescending { it.recommended }
|
||||
}
|
||||
@@ -150,18 +159,61 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
fun ensureAuto(force: Boolean) {
|
||||
mode = SessionPrefs.gpuDriverMode(activity)
|
||||
if (mode != SessionPrefs.GPU_DRIVERS_AUTO || pairBusy != null || releaseChecking) return
|
||||
if (gpu.family == GpuInfo.Family.POWERVR && !SystemVulkanDriver.isXclipse()) {
|
||||
// Auto owns both choices. Manual imports remain available when Manual is selected.
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(activity)
|
||||
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
|
||||
refreshDrivers()
|
||||
return
|
||||
}
|
||||
// A Mali pair set by an earlier build put its PanVK Android half on the display, which fails
|
||||
// on Mali gralloc. Under Auto the display is the phone's own driver (Android's loader).
|
||||
if (gpu.family.mali) {
|
||||
val display = SessionPrefs.androidDriver(activity)
|
||||
if (display.isNotEmpty() && DriverPairs.isNonAdreno(DriverBundle.containing(activity, display, false)?.id)) {
|
||||
SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
||||
Log.i(TAG, "auto: Mali display back on the phone's own driver (was $display)")
|
||||
}
|
||||
}
|
||||
if (!force && autoCheckedThisProcess) return
|
||||
autoCheckedThisProcess = true
|
||||
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null &&
|
||||
com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) {
|
||||
// No name for this Mali yet: ask its own Vulkan driver (it creates an instance, so off
|
||||
// the main thread), then decide again with the name it gives.
|
||||
autoStatus = activity.getString(R.string.drivers_checking_latest)
|
||||
Thread({
|
||||
com.droiddeck.launcher.gpu.VulkanInfo.query()
|
||||
ui.post {
|
||||
gpu = GpuInfo.detect()
|
||||
Log.i(TAG, "auto: Mali named by its driver: ${gpu.name} -> ${gpu.family}")
|
||||
autoCheckedThisProcess = false
|
||||
ensureAuto(force)
|
||||
}
|
||||
}, "gpu-name").start()
|
||||
return
|
||||
}
|
||||
Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair"))
|
||||
if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
||||
useMaliBridge()
|
||||
autoStatus = activity.getString(R.string.drivers_mali_bridge_auto)
|
||||
refreshDrivers()
|
||||
return
|
||||
}
|
||||
if (DriverPairs.recommendedKey(gpu, emptyList()) == null) {
|
||||
autoStatus = "No drivers to set: ${gpu.supportText.lowercase()}"
|
||||
autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity).lowercase())
|
||||
return
|
||||
}
|
||||
releaseChecking = true
|
||||
autoStatus = "Checking for the latest drivers…"
|
||||
autoStatus = activity.getString(R.string.drivers_checking_latest)
|
||||
Thread({
|
||||
val cached = TurnipReleases.cached(activity)
|
||||
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > 24 * 3_600_000L ||
|
||||
cached.assets.none { it.pair.isNotEmpty() }
|
||||
// The open non-Adreno drivers are rebuilt in place while they are tested: an hour.
|
||||
val maxAge = if (DeviceSupport.adreno()) 24 * 3_600_000L else 3_600_000L
|
||||
val stale = cached == null || System.currentTimeMillis() - cached.checkedAt > maxAge ||
|
||||
cached.assets.none { it.pair.isNotEmpty() } ||
|
||||
// A list checked before this device's open drivers were offered has none of them.
|
||||
(!DeviceSupport.adreno() && cached.assets.none { DriverPairs.isNonAdreno(it.pair) })
|
||||
val problem = if (force || stale) runCatching { TurnipReleases.refresh(activity) }.exceptionOrNull()?.message else null
|
||||
ui.post {
|
||||
releaseChecking = false
|
||||
@@ -172,15 +224,40 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
val pair = pairs.firstOrNull { it.key == key }
|
||||
val row = pairRows.firstOrNull { it.key == key }
|
||||
when {
|
||||
row?.active == true -> autoStatus = "Up to date" + (problem?.let { " (couldn't check: $it)" } ?: "")
|
||||
row?.active == true -> autoStatus = problem?.let { activity.getString(R.string.drivers_up_to_date_check_failed, it) }
|
||||
?: activity.getString(R.string.upd_current_status)
|
||||
gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> {
|
||||
// RADV is not published right now: the Xclipse falls back to the system route.
|
||||
SessionPrefs.ensurePowerVrAutoDrivers(activity)
|
||||
autoStatus = activity.getString(R.string.drivers_powervr_builtin)
|
||||
refreshDrivers()
|
||||
}
|
||||
gpu.family.mali && (pair == null || !pair.complete) -> {
|
||||
// No open driver for this Mali published yet: draw through the bridge.
|
||||
useMaliBridge()
|
||||
autoStatus = activity.getString(R.string.drivers_mali_bridge_fallback, key?.let { DriverPairs.nonAdrenoName(it) } ?: gpu.name)
|
||||
refreshDrivers()
|
||||
}
|
||||
pair == null || !pair.complete ->
|
||||
autoStatus = problem?.let { "Couldn't check: $it" } ?: "The recommended drivers aren't published right now"
|
||||
autoStatus = problem?.let { activity.getString(R.string.upd_couldnt_check, it) } ?: activity.getString(R.string.drivers_recommended_unpublished)
|
||||
else -> installPair(pair, auto = true)
|
||||
}
|
||||
}
|
||||
}, "gpu-driver-auto").start()
|
||||
}
|
||||
|
||||
/**
|
||||
* Auto on a Mali without an open driver pair: the Vulkan bridge draws instead, on the phone's
|
||||
* own driver, so a pair Auto set earlier is unset rather than left half-working.
|
||||
*/
|
||||
private fun useMaliBridge() {
|
||||
if (DeviceSupport.openDriverActive(activity)) {
|
||||
SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
||||
SessionPrefs.setLinuxDriver(activity, "")
|
||||
}
|
||||
SessionPrefs.setVkBridge(activity, true)
|
||||
}
|
||||
|
||||
/** Manual: install (if need be) and set both halves of a pair. */
|
||||
fun selectPair(key: String) {
|
||||
if (pairBusy != null) return
|
||||
@@ -197,7 +274,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
if (!pair.complete) return
|
||||
pairBusy = pair.key
|
||||
pairPercent = 0
|
||||
if (auto) autoStatus = "Downloading ${pair.name} ${pair.version}…"
|
||||
if (auto) autoStatus = activity.getString(R.string.drivers_downloading_pair, pair.name, pair.version)
|
||||
Thread({
|
||||
val lm = LinuxVulkanDriverManager(activity)
|
||||
val td = TurnipDriver(activity)
|
||||
@@ -213,11 +290,20 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
ui.post {
|
||||
pairBusy = null
|
||||
pairPercent = -1
|
||||
result.onSuccess { (displayId, linuxId) ->
|
||||
result.onSuccess { (pairDisplayId, linuxId) ->
|
||||
// A Mali pair under Auto: the compositor draws on the phone's own Mali driver
|
||||
// (dma-buf, modifiers and AHB all work there) and the guest runs the pair's
|
||||
// PanVK. Its Android half stays installed for a manual pick.
|
||||
// The same when the pair is picked by hand: a PanVK Android half on the display
|
||||
// stalls Mali gralloc ("Waiting for Steam's first frame"); it stays a manual pick
|
||||
// under "Runtime and display drivers separately".
|
||||
val displayId = if (gpu.family.mali && DriverPairs.isNonAdreno(pair.key)) TurnipDriver.AUTO else pairDisplayId
|
||||
val displayChanged = SessionPrefs.androidDriver(activity) != displayId
|
||||
SessionPrefs.setAndroidDriver(activity, displayId)
|
||||
SessionPrefs.setLinuxDriver(activity, linuxId)
|
||||
val restart = if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
|
||||
// The Mali bridge switch is the user's and is left as it is: when it is on, the
|
||||
// bridge wins for the session (DeviceSupport.vkBridge) and the pair waits.
|
||||
val restart = displayChanged && CompositorHost.isStarted
|
||||
if (auto) {
|
||||
val previous = SessionPrefs.gpuAutoInstalled(activity)
|
||||
for (id in previous - setOf(displayId, linuxId)) {
|
||||
@@ -230,14 +316,18 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
TurnipReleases.forget(activity, id)
|
||||
}
|
||||
SessionPrefs.setGpuAutoInstalled(activity, setOf(displayId, linuxId))
|
||||
autoStatus = (if (downloaded) "Updated to" else "Switched to") + " ${pair.name} ${pair.version}.$restart"
|
||||
autoStatus = activity.getString(
|
||||
if (downloaded) { if (restart) R.string.drivers_updated_to_restart else R.string.drivers_updated_to }
|
||||
else { if (restart) R.string.drivers_switched_to_restart else R.string.drivers_switched_to },
|
||||
pair.name, pair.version,
|
||||
)
|
||||
} else {
|
||||
android.widget.Toast.makeText(activity, "Using ${pair.name} ${pair.version}.$restart", android.widget.Toast.LENGTH_LONG).show()
|
||||
android.widget.Toast.makeText(activity, activity.getString(if (restart) R.string.drivers_using_restart else R.string.drivers_using, pair.name, pair.version), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Log.w(TAG, "driver pair ${pair.key}", e)
|
||||
val why = if (e is IllegalArgumentException) e.message else "Download failed: ${e.message}"
|
||||
if (auto) autoStatus = why ?: "Download failed"
|
||||
val why = if (e is IllegalArgumentException) e.message else activity.getString(R.string.comp_download_failed, e.message)
|
||||
if (auto) autoStatus = why ?: activity.getString(R.string.user_apps_download_failed)
|
||||
else android.widget.Toast.makeText(activity, why, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
refreshDrivers()
|
||||
@@ -298,7 +388,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
try {
|
||||
LinuxVulkanDriverManager(activity).installDriver(uri, name)
|
||||
} catch (runtime: IllegalArgumentException) {
|
||||
throw IllegalArgumentException("Not a driver zip: neither an AdrenoTools driver, a -Linux Turnip nor an Android + Linux bundle")
|
||||
throw IllegalArgumentException(activity.getString(R.string.drivers_not_a_driver))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -307,10 +397,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
e.message
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "driver import", e)
|
||||
"Import failed: ${e.message}"
|
||||
activity.getString(R.string.drivers_import_failed, e.message)
|
||||
}
|
||||
ui.post {
|
||||
val done = bundle?.let { useBundle(it) } ?: "Imported ${name ?: "driver"}"
|
||||
val done = bundle?.let { useBundle(it) }
|
||||
?: name?.let { activity.getString(R.string.comp_imported, it) } ?: activity.getString(R.string.drivers_imported_unnamed)
|
||||
android.widget.Toast.makeText(
|
||||
activity, problem ?: done,
|
||||
if (problem != null || bundle != null) android.widget.Toast.LENGTH_LONG else android.widget.Toast.LENGTH_SHORT,
|
||||
@@ -340,8 +431,10 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
val displayChanged = SessionPrefs.androidDriver(activity) != bundle.androidId
|
||||
DriverBundle.select(activity, bundle)
|
||||
if (mode == SessionPrefs.GPU_DRIVERS_AUTO) setMode(false)
|
||||
return "Using ${bundle.label} as both the runtime and display driver." +
|
||||
if (displayChanged && CompositorHost.isStarted) " The display driver applies after DroidDeck restarts." else ""
|
||||
return activity.getString(
|
||||
if (displayChanged && CompositorHost.isStarted) R.string.drivers_using_bundle_restart else R.string.drivers_using_bundle,
|
||||
bundle.label,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -354,7 +447,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
if (bundle != null) {
|
||||
DriverBundle.remove(activity, bundle)
|
||||
TurnipReleases.forget(activity, bundle.id)
|
||||
android.widget.Toast.makeText(activity, "Deleted ${bundle.label} (both drivers)", android.widget.Toast.LENGTH_SHORT).show()
|
||||
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_deleted_bundle, bundle.label), android.widget.Toast.LENGTH_SHORT).show()
|
||||
refreshDrivers()
|
||||
return
|
||||
}
|
||||
@@ -367,7 +460,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
if (SessionPrefs.androidDriver(activity) == id) SessionPrefs.setAndroidDriver(activity, TurnipDriver.AUTO)
|
||||
}
|
||||
TurnipReleases.forget(activity, id)
|
||||
android.widget.Toast.makeText(activity, "Deleted ${id}", android.widget.Toast.LENGTH_SHORT).show()
|
||||
android.widget.Toast.makeText(activity, activity.getString(R.string.drivers_deleted, id), android.widget.Toast.LENGTH_SHORT).show()
|
||||
refreshDrivers()
|
||||
}
|
||||
|
||||
@@ -378,26 +471,28 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
.filter { it.bundle || it.linux == linux }
|
||||
.filter { a -> installedIdOf(a) == null }
|
||||
.map { a ->
|
||||
val mb = "%.1f MB".format(a.size / 1_048_576.0)
|
||||
val mb = activity.getString(R.string.common_size_mb, a.size / 1_048_576.0)
|
||||
com.droiddeck.launcher.ui.DownloadRow(a.name, "${a.source} ${a.tag}", "${a.label} · $mb", releaseProgress[a.name])
|
||||
}
|
||||
linuxDownloads = rows(linux = true)
|
||||
androidDownloads = rows(linux = false)
|
||||
if (!releaseChecking) releaseStatus = when (check) {
|
||||
null -> "Not checked yet - tap refresh to look for new drivers"
|
||||
else -> "Latest: " + check.latest.joinToString(" · ") { "${it.first} ${it.second}" } +
|
||||
(if (check.failed.isEmpty()) "" else " · ${check.failed.joinToString()} unreachable") +
|
||||
" · checked ${ago(check.checkedAt)}"
|
||||
null -> activity.getString(R.string.drivers_not_checked)
|
||||
else -> {
|
||||
val latest = check.latest.joinToString(" · ") { "${it.first} ${it.second}" }
|
||||
if (check.failed.isEmpty()) activity.getString(R.string.drivers_release_status, latest, ago(check.checkedAt))
|
||||
else activity.getString(R.string.drivers_release_status_failed, latest, check.failed.joinToString(), ago(check.checkedAt))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun ago(t: Long): String {
|
||||
val m = ((System.currentTimeMillis() - t) / 60_000).coerceAtLeast(0)
|
||||
return when {
|
||||
m < 1 -> "just now"
|
||||
m < 60 -> "$m min ago"
|
||||
m < 48 * 60 -> "${m / 60} h ago"
|
||||
else -> "${m / (24 * 60)} days ago"
|
||||
m < 1 -> activity.getString(R.string.upd_just_now)
|
||||
m < 60 -> activity.resources.getQuantityString(R.plurals.drivers_ago_minutes, m.toInt(), m)
|
||||
m < 48 * 60 -> activity.resources.getQuantityString(R.plurals.drivers_ago_hours, (m / 60).toInt(), m / 60)
|
||||
else -> activity.resources.getQuantityString(R.plurals.drivers_ago_days, (m / (24 * 60)).toInt(), m / (24 * 60))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -405,16 +500,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
fun checkLatestTurnip() {
|
||||
if (releaseChecking) return
|
||||
releaseChecking = true
|
||||
releaseStatus = "Checking Banners-Turnip, WinNative and DroidDeck…"
|
||||
releaseStatus = activity.getString(R.string.drivers_checking_sources)
|
||||
Thread({
|
||||
val problem = try { TurnipReleases.refresh(activity); null } catch (e: Exception) {
|
||||
Log.w(TAG, "latest Turnip check", e); e.message ?: "check failed"
|
||||
Log.w(TAG, "latest Turnip check", e); e.message ?: activity.getString(R.string.drivers_check_failed)
|
||||
}
|
||||
ui.post {
|
||||
releaseChecking = false
|
||||
refreshReleaseRows()
|
||||
refreshPairs()
|
||||
if (problem != null) releaseStatus = "Couldn't check: $problem"
|
||||
if (problem != null) releaseStatus = activity.getString(R.string.upd_couldnt_check, problem)
|
||||
}
|
||||
}, "turnip-release-check").start()
|
||||
}
|
||||
@@ -433,13 +528,16 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
|
||||
e.message
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "release driver download", e)
|
||||
"Download failed: ${e.message}"
|
||||
activity.getString(R.string.comp_download_failed, e.message)
|
||||
}
|
||||
ui.post {
|
||||
releaseProgress.remove(assetName)
|
||||
val pick = if (asset.bundle) "pick it in either list to set both drivers" else "pick it in the menu"
|
||||
val installed = activity.getString(
|
||||
if (asset.bundle) R.string.drivers_installed_pick_either else R.string.drivers_installed_pick,
|
||||
asset.name.removeSuffix(".zip"),
|
||||
)
|
||||
android.widget.Toast.makeText(
|
||||
activity, problem ?: "Installed ${asset.name.removeSuffix(".zip")} - $pick",
|
||||
activity, problem ?: installed,
|
||||
android.widget.Toast.LENGTH_LONG,
|
||||
).show()
|
||||
refreshDrivers()
|
||||
|
||||
@@ -7,8 +7,14 @@ import com.droiddeck.launcher.session.SessionService
|
||||
|
||||
/** Receives the system Home launch and routes it without consuming KEYCODE_HOME. */
|
||||
class HomeActivity : Activity() {
|
||||
override fun attachBaseContext(newBase: android.content.Context) {
|
||||
super.attachBaseContext(newBase)
|
||||
com.droiddeck.launcher.core.AppLanguage.applyTo(this, newBase)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
routeHome()
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -10,21 +10,23 @@ import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
|
||||
/**
|
||||
* The optional ARM64 Protons (GE-Proton, proton-cachyos): the rows the page lists and an install or
|
||||
* removal in progress. The launcher screen keeps one and shows it.
|
||||
* The optional ARM64 Protons (GE-Proton, proton-cachyos, DroidDeck-Proton): the rows the page lists,
|
||||
* an install or removal in progress, and whether a newer release is out. The launcher screen keeps
|
||||
* one and shows it.
|
||||
*/
|
||||
internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
|
||||
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
|
||||
var protonBusyId by mutableStateOf<String?>(null)
|
||||
var protonStage by mutableStateOf<String?>(null)
|
||||
var protonPercent by mutableIntStateOf(-1)
|
||||
private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
|
||||
|
||||
fun installProton(id: String) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
ProtonExtras.unqueue(activity, tool)
|
||||
protonBusyId = id
|
||||
protonStage = "Starting…"
|
||||
protonStage = activity.getString(R.string.store_starting)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
val problem = ProtonExtras.install(activity, tool) { label, value ->
|
||||
@@ -40,14 +42,15 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
||||
}, "install-proton-$id").start()
|
||||
}
|
||||
|
||||
fun removeProton(id: String) {
|
||||
/** Removes the build in [dir], or with [older] every build of it but the newest. */
|
||||
fun removeProton(id: String, dir: String? = null, older: Boolean = false) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
if (protonBusyId != null || SessionState.running) return
|
||||
protonBusyId = id
|
||||
protonStage = "Removing ${tool.name}…"
|
||||
protonStage = activity.getString(R.string.main_removing_named, dir ?: tool.name)
|
||||
protonPercent = -1
|
||||
Thread({
|
||||
ProtonExtras.remove(activity, tool)
|
||||
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
|
||||
ui.post {
|
||||
protonBusyId = null
|
||||
protonStage = null
|
||||
@@ -57,6 +60,18 @@ internal class ProtonMenu(private val activity: android.app.Activity, private va
|
||||
}
|
||||
|
||||
fun refreshProtons() {
|
||||
protonRows = ProtonExtras.tools.map { ProtonRow(it.id, it.name, ProtonExtras.installed(activity, it), ProtonExtras.queued(activity, it)) }
|
||||
protonRows = ProtonExtras.tools.map {
|
||||
val all = ProtonExtras.installedAll(activity, it)
|
||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
||||
}
|
||||
}
|
||||
|
||||
/** Looks for newer releases, at most every few hours (see ProtonExtras.checkLatest); quiet offline. */
|
||||
fun checkUpdates(force: Boolean = false) {
|
||||
if (!checking.compareAndSet(false, true)) return
|
||||
Thread({
|
||||
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
|
||||
if (asked) ui.post { refreshProtons() }
|
||||
}, "proton-updates").start()
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -46,7 +46,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
onAllowInstalls = {
|
||||
askPermission = false
|
||||
runCatching { activity.startActivity(SelfInstaller.permissionIntent(activity)) }
|
||||
.onFailure { error = "Couldn't open Android's \"Install unknown apps\" setting"; pending = null }
|
||||
.onFailure { error = activity.getString(R.string.upd_unknown_apps_failed); pending = null }
|
||||
},
|
||||
onDismissPermission = { askPermission = false; pending = null },
|
||||
)
|
||||
@@ -77,7 +77,7 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
catalog = it
|
||||
follow = AppUpdates.follow(activity, it)
|
||||
error = null
|
||||
}.onFailure { if (force) error = "Couldn't check: ${it.message ?: it.javaClass.simpleName}" }
|
||||
}.onFailure { if (force) error = activity.getString(R.string.upd_couldnt_check, it.message ?: it.javaClass.simpleName) }
|
||||
}
|
||||
}, "app-updates").start()
|
||||
}
|
||||
@@ -90,20 +90,20 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
|
||||
private fun install(r: AppUpdates.Release) {
|
||||
if (stage != null) return
|
||||
val apk = r.apk ?: run { error = "This build has no download for this copy of DroidDeck"; return }
|
||||
AppUpdates.installBlock(r)?.let { error = it; return }
|
||||
if (SessionState.running) { error = "Stop the running session first, then update"; return }
|
||||
val apk = r.apk ?: run { error = activity.getString(R.string.upd_no_download); return }
|
||||
AppUpdates.installBlock(r)?.let { error = it.message(activity); return }
|
||||
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
|
||||
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
|
||||
error = null
|
||||
stage = "Downloading"
|
||||
stage = activity.getString(R.string.upd_stage_downloading)
|
||||
percent = 0
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
|
||||
ui.post { stage = "Installing"; percent = -1 }
|
||||
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
|
||||
SelfInstaller.install(activity, file)
|
||||
}
|
||||
result.onFailure { e -> ui.post { stage = null; error = e.message ?: "The update failed" } }
|
||||
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
|
||||
}, "app-update-install").start()
|
||||
}
|
||||
|
||||
@@ -114,14 +114,14 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
|
||||
PackageInstaller.STATUS_PENDING_USER_ACTION -> {
|
||||
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
|
||||
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
|
||||
if (confirm == null) { stage = null; error = "Android didn't offer to install the update"; return }
|
||||
stage = "Waiting for you to confirm"
|
||||
if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
|
||||
stage = activity.getString(R.string.upd_stage_confirm)
|
||||
activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
PackageInstaller.STATUS_SUCCESS -> stage = null
|
||||
else -> {
|
||||
stage = null
|
||||
error = SelfInstaller.describeFailure(status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE))
|
||||
error = SelfInstaller.describeFailure(activity, status, intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import android.content.Context
|
||||
|
||||
/**
|
||||
* Who may run code through the agent bridge. Reading state, starting and stopping sessions,
|
||||
* launching and quitting games and sending input only need the shell (the provider's DUMP
|
||||
* permission). Running commands in the guest, evaluating JavaScript in the Steam client, session
|
||||
* environment, binary overrides and preference writes reach inside the app's sandbox - the guest
|
||||
* holds the Steam login - which the shell of a stock device otherwise cannot. They require
|
||||
* Setup > Session > Debugging tools to be on, in every build. The bridge itself cannot turn it on.
|
||||
*/
|
||||
object AgentAccess {
|
||||
const val MAX_REQUEST_CHARS = 256 * 1024
|
||||
private const val PREFS = "agent"
|
||||
private const val KEY_COMMANDS = "commands"
|
||||
|
||||
/** The preferences file the bridge must never write: set-pref refuses it. */
|
||||
const val PROTECTED_PREFS = PREFS
|
||||
|
||||
fun commandsAllowed(context: Context): Boolean =
|
||||
prefs(context).getBoolean(KEY_COMMANDS, false)
|
||||
|
||||
/** The Setup toggle's own state. */
|
||||
fun commandsEnabled(context: Context): Boolean = prefs(context).getBoolean(KEY_COMMANDS, false)
|
||||
|
||||
fun setCommandsEnabled(context: Context, enabled: Boolean) {
|
||||
prefs(context).edit().putBoolean(KEY_COMMANDS, enabled).apply()
|
||||
if (!enabled) runCatching { AgentEnv.revoke(context) }
|
||||
.onFailure { android.util.Log.w("AgentAccess", "Could not finish clearing debugging experiments") }
|
||||
}
|
||||
|
||||
fun requireCommands(context: Context) {
|
||||
if (!commandsAllowed(context)) throw AgentException(
|
||||
"AGENT_COMMANDS_DISABLED",
|
||||
"Debugging tools are off: turn on Setup > Session > Debugging tools on the device",
|
||||
)
|
||||
}
|
||||
|
||||
fun requireStart(context: Context, request: org.json.JSONObject) {
|
||||
if (request.optString("mode") == "run") requireCommands(context)
|
||||
}
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
}
|
||||
|
||||
/** A refusal with a stable code, answered as {"ok": false, "error": {code, message}}. */
|
||||
class AgentException(val code: String, message: String) : RuntimeException(message)
|
||||
@@ -0,0 +1,288 @@
|
||||
package com.droiddeck.launcher.agent
|
||||
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import android.Manifest
|
||||
import android.content.ContentProvider
|
||||
import android.content.ContentValues
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.database.Cursor
|
||||
import android.net.Uri
|
||||
import android.os.Binder
|
||||
import android.os.Bundle
|
||||
import android.os.Process
|
||||
import android.util.Base64
|
||||
import com.droiddeck.launcher.BuildConfig
|
||||
import com.droiddeck.launcher.frontend.GameLaunchLink
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
|
||||
import com.droiddeck.launcher.session.SessionArtifacts
|
||||
import com.droiddeck.launcher.session.SessionEvents
|
||||
import com.droiddeck.launcher.session.SessionPhase
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/**
|
||||
* The shell's control surface (docs/agent-control.md), in every build: the provider and its start
|
||||
* Activity need android.permission.DUMP, held by the shell and privileged or explicitly granted callers. Commands that
|
||||
* reach into the app's sandbox are further gated by [AgentAccess].
|
||||
*
|
||||
* A method's request is JSON, base64-encoded in the "request" extra; every answer is JSON in the
|
||||
* "json" key of the returned Bundle, {"ok": true, ...} or {"ok": false, "error": {code, message}}.
|
||||
*/
|
||||
class AgentBridgeProvider : ContentProvider() {
|
||||
override fun onCreate(): Boolean {
|
||||
val appContext = context?.applicationContext ?: return false
|
||||
Thread({
|
||||
try {
|
||||
SessionArtifacts.finishAbandoned(appContext)
|
||||
} finally {
|
||||
recoveryComplete.countDown()
|
||||
}
|
||||
}, "agent-recover-artifacts").start()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
|
||||
val context = requireNotNull(context)
|
||||
if (Binder.getCallingUid() != Process.myUid() &&
|
||||
context.checkCallingPermission(Manifest.permission.DUMP) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
throw SecurityException("android.permission.DUMP is required")
|
||||
}
|
||||
|
||||
val response = try {
|
||||
val request = decode(extras?.getString(EXTRA_REQUEST))
|
||||
// Binder identity is the shell's; everything below acts as the app.
|
||||
val token = Binder.clearCallingIdentity()
|
||||
try {
|
||||
dispatch(context, method, request)
|
||||
} finally {
|
||||
Binder.restoreCallingIdentity(token)
|
||||
}
|
||||
} catch (e: AgentException) {
|
||||
error(e.code, e.message ?: e.code)
|
||||
} catch (e: Exception) {
|
||||
error("COMMAND_FAILED", e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
val json = response.toString().let {
|
||||
if (it.length <= 384 * 1024) it else error("RESPONSE_TOO_LARGE", "Reduce the command output or select fewer fields").toString()
|
||||
}
|
||||
return Bundle().apply { putString(RESULT_JSON, json) }
|
||||
}
|
||||
|
||||
private fun dispatch(context: Context, method: String, request: JSONObject): JSONObject = when (method) {
|
||||
"state" -> state(context).put("ok", true)
|
||||
"start" -> error("USE_DROIDDECKCTL", "Start sessions with tools/droiddeckctl so Android launches a visible Activity")
|
||||
"stop" -> stop(context)
|
||||
"resume" -> resume(context)
|
||||
"launch" -> launch(context, request)
|
||||
"focus" -> guest(context, JSONObject().put("kind", "focus"), 15_000)
|
||||
"quit" -> guest(context, JSONObject().put("kind", "quit").put("appId", request.opt("appId"))
|
||||
.put("timeout", request.optDouble("timeout", 15.0)), timeoutMs(request, 15.0, 30_000))
|
||||
"input" -> AgentInput.handle(request)
|
||||
"ui" -> AgentUi.handle(request)
|
||||
"guest" -> {
|
||||
AgentAccess.requireCommands(context)
|
||||
guest(context, JSONObject(request.toString()).put("kind", "exec"), timeoutMs(request, 30.0, 10_000))
|
||||
}
|
||||
"cdp" -> {
|
||||
AgentAccess.requireCommands(context)
|
||||
guest(context, JSONObject(request.toString()).put("kind", "cdp"), timeoutMs(request, 15.0, 5_000))
|
||||
}
|
||||
"env" -> env(context, request)
|
||||
"override" -> {
|
||||
AgentAccess.requireCommands(context)
|
||||
AgentEnv.override(context, request.optString("name")).put("ok", true).put("command", "override")
|
||||
}
|
||||
"prefs" -> prefs(context, request)
|
||||
"access" -> JSONObject().put("ok", true).put("commands", AgentAccess.commandsAllowed(context))
|
||||
.put("debugBuild", BuildConfig.DEBUG).put("inbox", AgentEnv.inbox(context).absolutePath)
|
||||
else -> error("UNKNOWN_COMMAND", "Unknown agent command '$method'")
|
||||
}
|
||||
|
||||
private fun state(context: Context): JSONObject {
|
||||
val runtimeVersion = LinuxRuntimeInstaller.installedVersion(context)
|
||||
val dir = SessionState.logDirectory ?: SessionState.logFile?.parentFile ?: SessionPaths.sessionFolders(context).lastOrNull()
|
||||
val session = JSONObject()
|
||||
.put("id", SessionState.sessionId ?: dir?.name ?: JSONObject.NULL)
|
||||
.put("phase", SessionState.phase.name)
|
||||
.put("running", SessionState.running)
|
||||
.put("mode", SessionState.mode)
|
||||
.put("program", SessionState.program ?: JSONObject.NULL)
|
||||
.put("steamUi", SessionState.steamUi ?: JSONObject.NULL)
|
||||
.put("steamUrl", SessionState.steamUrl ?: JSONObject.NULL)
|
||||
.put("suspended", SessionState.suspended)
|
||||
.put("pip", SessionState.pipActive)
|
||||
.put("firstFrame", SessionState.firstFrameSeen)
|
||||
.put("output", JSONArray().put(SessionState.outputSize.first).put(SessionState.outputSize.second))
|
||||
.put("refreshHz", SessionState.refreshHz.toDouble())
|
||||
.put("lastTransitionAt", SessionState.lastTransitionAt)
|
||||
.put("guestPid", SessionState.guestPid.takeIf { it > 1 } ?: JSONObject.NULL)
|
||||
.put("installing", SessionState.installing ?: JSONObject.NULL)
|
||||
.put("logDir", dir?.absolutePath ?: JSONObject.NULL)
|
||||
.put("eventsFile", dir?.let { File(it, "events.jsonl").absolutePath } ?: JSONObject.NULL)
|
||||
.put("artifactsAvailable", dir?.isDirectory ?: false)
|
||||
.put("artifactsComplete", dir?.let { File(it, ".complete").isFile } ?: false)
|
||||
|
||||
val failure = if (SessionState.failureCode == null) JSONObject.NULL else JSONObject()
|
||||
.put("code", SessionState.failureCode)
|
||||
.put("message", SessionState.failureMessage ?: JSONObject.NULL)
|
||||
.put("status", SessionState.failureStatus ?: JSONObject.NULL)
|
||||
session.put("failure", failure)
|
||||
|
||||
// gamescope's focus as last published by the guest agent, without the window lists
|
||||
// (the focus command returns those, fresh).
|
||||
val focus = AgentGuest.focus(context)?.let { snap ->
|
||||
JSONObject()
|
||||
.put("focusedApp", snap.opt("focusedApp") ?: JSONObject.NULL)
|
||||
.put("focusedWindow", snap.opt("focusedWindow") ?: JSONObject.NULL)
|
||||
.put("focusableApps", snap.optJSONArray("focusableApps") ?: JSONArray())
|
||||
.put("baselayerAppIds", snap.optJSONArray("baselayerAppIds") ?: JSONArray())
|
||||
.put("seq", snap.optInt("seq"))
|
||||
.put("t", snap.optLong("t"))
|
||||
}
|
||||
session.put("focus", focus ?: JSONObject.NULL)
|
||||
|
||||
val hello = AgentGuest.hello(context)
|
||||
return JSONObject()
|
||||
.put("schema", SCHEMA)
|
||||
.put("build", BuildConfig.BUILD_LABEL)
|
||||
.put("appVersion", context.packageManager.getPackageInfo(context.packageName, 0).versionName)
|
||||
.put("runtime", JSONObject()
|
||||
.put("installed", LinuxRuntime.isInstalled(context))
|
||||
.put("version", runtimeVersion ?: JSONObject.NULL))
|
||||
.put("agent", JSONObject()
|
||||
.put("guest", hello != null)
|
||||
.put("guestFocus", hello?.optBoolean("focus") ?: false)
|
||||
.put("commands", AgentAccess.commandsAllowed(context)))
|
||||
.put("session", session)
|
||||
}
|
||||
|
||||
private fun stop(context: Context): JSONObject {
|
||||
if (SessionState.running) {
|
||||
SessionService.stop(context)
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
if (SessionState.phase == SessionPhase.STOPPING) {
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
if (SessionState.phase in STARTING_PHASES) {
|
||||
SessionState.stopRequested = true
|
||||
SessionEvents.transition(SessionPhase.STOPPING, "session.stop_requested")
|
||||
return JSONObject().put("ok", true).put("command", "stop")
|
||||
}
|
||||
return error("NO_ACTIVE_SESSION", "There is no session to stop")
|
||||
}
|
||||
|
||||
private fun resume(context: Context): JSONObject {
|
||||
if (!SessionState.running || !SessionState.suspended) {
|
||||
return error("SESSION_NOT_SUSPENDED", "There is no suspended session to resume")
|
||||
}
|
||||
SessionService.resume(context)
|
||||
return JSONObject().put("ok", true).put("command", "resume")
|
||||
}
|
||||
|
||||
private fun launch(context: Context, request: JSONObject): JSONObject {
|
||||
val appId = request.optString("appId")
|
||||
if (!GameLaunchLink.validId(appId)) throw AgentException("INVALID_APP_ID", "appId must be a decimal Steam app id")
|
||||
if (!SessionState.running || SessionState.mode != SessionService.MODE_STEAM) {
|
||||
throw AgentException("NO_STEAM_SESSION", "Games launch inside a running Steam session")
|
||||
}
|
||||
if (!SessionService.launchGame(context, appId)) throw AgentException("LAUNCH_REJECTED", "The session did not accept the launch")
|
||||
SessionEvents.record("agent.launch_requested", mapOf("appId" to appId))
|
||||
return JSONObject().put("ok", true).put("command", "launch").put("appId", appId)
|
||||
}
|
||||
|
||||
private fun env(context: Context, request: JSONObject): JSONObject {
|
||||
AgentAccess.requireCommands(context)
|
||||
val result = when (val op = request.optString("op", "list")) {
|
||||
"list" -> AgentEnv.list(context)
|
||||
"set" -> {
|
||||
val lines = request.optJSONArray("lines") ?: JSONArray()
|
||||
AgentEnv.set(context, List(lines.length()) { lines.optString(it) }, request.optBoolean("persistent"))
|
||||
}
|
||||
"clear" -> AgentEnv.clear(context, request.optString("scope", "next"))
|
||||
else -> throw AgentException("INVALID_REQUEST", "env op '$op' is not list, set or clear")
|
||||
}
|
||||
return result.put("ok", true).put("command", "env")
|
||||
}
|
||||
|
||||
private fun prefs(context: Context, request: JSONObject): JSONObject {
|
||||
AgentAccess.requireCommands(context)
|
||||
val file = request.optString("file")
|
||||
val result = when (val op = request.optString("op", "get")) {
|
||||
"get" -> AgentPrefs.get(context, file)
|
||||
"set" -> AgentPrefs.set(context, file, request.optString("key"), request.optString("type", "string"),
|
||||
if (request.isNull("value")) null else request.optString("value"))
|
||||
else -> throw AgentException("INVALID_REQUEST", "prefs op '$op' is not get or set")
|
||||
}
|
||||
return result.put("ok", true).put("command", "prefs")
|
||||
}
|
||||
|
||||
/** A guest agent request; its own answer already carries ok or error. */
|
||||
private fun guest(context: Context, request: JSONObject, timeoutMs: Long): JSONObject =
|
||||
AgentGuest.call(context, request, timeoutMs)
|
||||
|
||||
/** The guest's own timeout plus slack for the round trip. */
|
||||
private fun timeoutMs(request: JSONObject, defaultSeconds: Double, slackMs: Long): Long {
|
||||
val seconds = if (request.has("timeout")) request.opt("timeout")?.toString()?.toDoubleOrNull()
|
||||
?: throw AgentException("INVALID_REQUEST", "timeout must be a number") else defaultSeconds
|
||||
if (!seconds.isFinite() || seconds <= 0 || seconds > 600) {
|
||||
throw AgentException("INVALID_REQUEST", "timeout must be a positive number no greater than 600 seconds")
|
||||
}
|
||||
return (seconds * 1000).toLong() + slackMs
|
||||
}
|
||||
|
||||
private fun decode(encoded: String?): JSONObject {
|
||||
if (encoded.isNullOrBlank()) return JSONObject()
|
||||
if (encoded.length > AgentAccess.MAX_REQUEST_CHARS) throw AgentException("INVALID_REQUEST", "The encoded request exceeds 256 KiB")
|
||||
return try {
|
||||
JSONObject(String(Base64.decode(encoded, Base64.DEFAULT), Charsets.UTF_8))
|
||||
} catch (e: Exception) {
|
||||
throw AgentException("INVALID_REQUEST", "The request extra is not base64 JSON")
|
||||
}
|
||||
}
|
||||
|
||||
private fun error(code: String, message: String) = JSONObject()
|
||||
.put("ok", false)
|
||||
.put("error", JSONObject().put("code", code).put("message", message))
|
||||
|
||||
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? = null
|
||||
override fun getType(uri: Uri): String? = null
|
||||
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
|
||||
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0
|
||||
|
||||
companion object {
|
||||
const val RESULT_JSON = "json"
|
||||
const val EXTRA_REQUEST = "request"
|
||||
/** 2 added agent and session.focus; everything in 1 is unchanged. */
|
||||
const val SCHEMA = 2
|
||||
private val recoveryComplete = CountDownLatch(1)
|
||||
|
||||
fun awaitRecovery() {
|
||||
try {
|
||||
if (!recoveryComplete.await(90, TimeUnit.SECONDS)) {
|
||||
throw IllegalStateException("Session artifact recovery did not finish")
|
||||
}
|
||||
} catch (e: InterruptedException) {
|
||||
Thread.currentThread().interrupt()
|
||||
throw IllegalStateException("Interrupted while recovering session artifacts", e)
|
||||
}
|
||||
}
|
||||
|
||||
private val STARTING_PHASES = setOf(
|
||||
SessionPhase.PREPARING,
|
||||
SessionPhase.INSTALLING_RUNTIME,
|
||||
SessionPhase.STARTING_COMPOSITOR,
|
||||
SessionPhase.STARTING_GUEST,
|
||||
SessionPhase.STARTING_STEAM,
|
||||
)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1037 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user