Compare commits

...
Author SHA1 Message Date
maxjivi05 16e2b256ed Pin the gamescope build that holds forwarded client buffers until scanout ends 2026-12-01 05:17:33 -05:00
maxjivi05 6b194227ea Test that a forwarded client buffer waits for scanout and composite images do not 2026-12-01 05:15:31 -05:00
maxjivi05 cb9c486166 Return a forwarded client buffer to its client only after the display finished scanning it out 2026-12-01 05:14:10 -05:00
MaxsTechReview 044c8ee475 fix(gamescope): a composited cursor no longer forwards the default arrow to the host (#3510) 2026-12-01 03:55:33 -05:00
MaxsTechReview ca499115ac fix(zero-copy): merge a second release fence into the pending fence wait (#3509)
When the kernel cannot attach a display release fence to the buffer, the
compositor waits on the fence itself. A second release of the same buffer
before that fence signalled overwrote the pending wait, so the first wait
removed the second one and then fired again with no source to remove,
crashing the compositor and losing the session.

A second unsignalled fence is now merged into the pending wait, and a
signalled or attached one leaves the pending wait in charge of the
deferred release.
2026-12-01 02:55:37 -05:00
The412BannerandThe412Banner d7898360e3 fix(input): keep the glibc-only __chk_fail out of the bionic build (#3492)
DroidDeck-Bionic preloads libfakeinput.so into its Wine processes
(tools/bionic-runtime/build.sh builds fakeinput_steam.cpp for bionic). The
fortified read/poll/ppoll entry points (#2916) call glibc's __chk_fail, which
bionic does not export, so the bionic build of the library cannot be loaded:
"CANNOT LINK EXECUTABLE .../wine: cannot locate symbol "__chk_fail"" and no
Wine program starts. Every DroidDeck-Bionic pack built from main since #2916 is
affected (r67 predates it).

The bounds failures now go through fakeinput_chk_fail(): abort() on bionic,
__chk_fail() as before on glibc. tools/tests/test_fakeinput_bionic.py fails if
__chk_fail is named outside the non-bionic branch again.

Co-authored-by: The412Banner <the412banner@users.noreply.github.com>
2026-11-30 19:48:33 -05:00
LunaDL fcd197934a test: fix effects source cache harness initialization (#3490) 2026-11-30 18:15:04 -05:00
FryMcNuggetandFryMcNugget 768661928e feat(agent): connect the agent on Quest, which has no pairing screen (#3445)
* feat(agent): connect the agent on Quest, which has no pairing screen

Quest hides Android's Wireless debugging pairing, so the agent's connection
step could not be completed there. On a Quest the step's action is now Allow:
DroidDeck connects to adbd on 127.0.0.1:5555 (after a one-time `adb tcpip 5555`
from a computer) and the headset asks "Allow debugging?" for DroidDeck's key.
Wireless debugging accepts a key allowed that way, so the saved loopback
connection then works like a pairing.

DroidDeck also declares WRITE_SECURE_SETTINGS. When it is granted over adb,
DroidDeck turns Wireless debugging on itself before looking for its port.

* fix(agent): keep the Quest setup hint visible and report a declined prompt correctly

A late connection lookup no longer overwrites an Allow that is running.
On a Quest, the connection row shows its status above the full hint, which
holds the one-time commands. The failure message no longer claims port 5555
was silent, since a declined or unanswered prompt fails the same way.

* fix(agent): connection checks from before an Allow no longer overwrite it

A check started before Allow could land after it and mark the step as not
done, or replace the prompt instructions while Allow was still waiting.
Each Allow now starts a new generation, and older connection results are
dropped, as are results that land while Allow is running.

* ci: rerun after the Maven 429 rate limit

* fix(quest): turn Wireless debugging on by itself only on Quest

Other devices keep exactly their pairing flow even if WRITE_SECURE_SETTINGS
is granted. Once connected, the Quest agent row shows its usual short hint
instead of the setup instructions.

* fix(quest): connect after a reboot without a second Allow

After a reboot, turning Wireless debugging on makes the Quest ask again to
allow it on this network, and the 2 s wait ran out before that was
answered, so the row showed Allow. Allow then failed, since port 5555 is
closed after a reboot. The lookup now keeps trying for up to 30 s after
turning Wireless debugging on, and Allow first tries the already-trusted
key over Wireless debugging before asking on port 5555.

* ci: rerun after download timeouts in the Python tests

---------

Co-authored-by: FryMcNugget <358046012+FryMcNugget@users.noreply.github.com>
2026-11-30 15:10:08 -05:00
LunaDLandmaxjivi05 18cd1cf07f Fix: reclaim DD-FG scratch resources on rebuild (#3456)
* Prepare FrameGen for instance-owned scratch lifecycle

* Make DD-FG rebuild and teardown completion-aware

* Restore DD-FG namespace boundary

* Isolate DD-FG scratch state and reclaim resources on rebuild

* Declare per-instance scratch builder before recording code

* Make DD-FG ring teardown report unsafe GPU completion

* Retain DD-FG input ring until GPU completion is confirmed

* Add DD-FG lifecycle and resource-isolation tests

* Cover DD-FG teardown and rebuild failure cases

* Document DD-FG scratch ownership and teardown semantics

* Guard DD-FG teardown when GPU completion cannot be queried

* docs: clarify DD-FG device-loss teardown

* fix: define DD-FG scratch state before resize

* fix: define DD-FG scratch state before resize

* fix(ddfg): wait for the GPU before replacing the input ring on resize

* Fix DD-FG ring cleanup after device loss

* Propagate DD-FG device-loss status

* Retain DD-FG resources when GPU completion is unknown

* Retain DD-FG resources when GPU completion is unknown

* Retain DD-FG resources when GPU completion is unknown

* Retain DD-FG resources when GPU completion is unknown

* Retain DD-FG resources when GPU completion is unknown

* Retry DD-FG cleanup after an idle-wait failure

* Test DD-FG cleanup retry after GPU wait failure

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-30 15:04:16 -05:00
LunaDL 41f15b03bb feat(framegen): add spatial post-upscale per presentation (#3454)
* feat(framegen): add spatial post-upscale per presentation

* Fix framegen post-upscale expectations

* test: run framegen post-upscale assertions

* test: verify framegen postprocessing image handles

* test: capture framegen screen blit source
2026-11-30 15:03:52 -05:00
LunaDL 5c887bfc59 Perf: Create screen-effect pipelines on demand (#3453)
* perf: create screen-effect pipelines on demand

* fix: prepare screen-effect fallback pipelines

* docs: describe lazy screen-effect pipelines

* test: guard lazy screen-effect pipeline setup
2026-11-30 15:03:30 -05:00
LunaDL 430d777c5c Fix: Fix right stick highlights and preserve zoom bindings (#3440)
* fix(input): stop stale right-stick page scrolling

* fix(input): preserve other bindings when saving an action

* test(input): cover zoom commands on same control category

* test(input): remove unnecessary zoom binding cases

* style(input): remove added inline comment
2026-11-30 15:02:30 -05:00
MaxsTechReview 5f129fb4db fix(native): allocated getcwd and realpath results name the guest mount (#3481)
getcwd(NULL, ...) and realpath(path, NULL) returned the host path of a
session mount whenever its guest path was longer than the host path,
because the translation had to fit the buffer the C library allocated.
Shells export that host path as PWD, and Wine prefers a valid PWD, so a
program started from an added game folder on a removable card got a
working directory it could not open and started in the Windows folder.
Grow the allocated result to fit the guest path.
2026-11-30 14:24:10 -05:00
MaxsTechReview 7404fba5a3 fix(battlenet): an install folder chosen in Battle.net on the library's drive is kept (#3479)
* fix(battlenet): an install folder chosen in Battle.net on the library's drive is kept

Every open set Battle.net's default install folder back to the library folder whenever the two differed, so a folder the user picked in Battle.net on the same drive was replaced on the next open. The folder is now only moved to the library when it is unset, missing, or on another drive.

* fix(battlenet): check the trimmed folder against the rootfs drives
2026-11-30 14:24:05 -05:00
MaxsTechReview 54ca518553 fix(storage): a card library the session cannot open by its raw path is opened by its storage path (#3475)
A game storage folder saved as a raw volume path is opened through the volume's /storage path when only that one is usable, and its private directories are kept under either path. Battle.net is only given a library folder when the configured one is attached, so a missing card no longer moves its install folder to internal storage.
2026-11-30 12:00:05 -05:00
82 changed files with 2406 additions and 303 deletions

No files matched your search

+3
View File
@@ -33,6 +33,9 @@
<uses-permission android:name="android.permission.REORDER_TASKS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<!-- Granted only with adb shell pm grant; lets the agent turn Wireless debugging on where Settings hides it (Quest). -->
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+10 -3
View File
@@ -4130,13 +4130,20 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) {
return read_input(fd, buf, count);
}
// glibc's fortify failure; bionic (DroidDeck-Bionic preloads this library into its Wine processes) has no
// __chk_fail, and a library naming it there cannot be loaded, which stops every Wine program from starting.
#if defined(__BIONIC__)
[[noreturn]] static void fakeinput_chk_fail(void) { abort(); }
#else
extern "C" [[noreturn]] void __chk_fail(void);
[[noreturn]] static void fakeinput_chk_fail(void) { __chk_fail(); }
#endif
/* Programs built with _FORTIFY_SOURCE (Flatpak runtimes among them) call these instead of read, poll
* and ppoll, and glibc's versions go straight to the kernel. */
EXPORT ssize_t __read_chk(int fd, void *buf, size_t count, size_t buflen) {
static auto next_read_chk = reinterpret_cast<ssize_t (*)(int, void *, size_t, size_t)>(dlsym(RTLD_NEXT, "__read_chk"));
if (count > buflen) __chk_fail();
if (count > buflen) fakeinput_chk_fail();
if (next_read_chk && !is_fake_input_fd(fd)) return next_read_chk(fd, buf, count, buflen);
return read_input(fd, buf, count);
}
@@ -4390,13 +4397,13 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
}
EXPORT int __poll_chk(struct pollfd *fds, nfds_t nfds, int timeout, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
return poll(fds, nfds, timeout);
}
EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *timeout,
const sigset_t *sigmask, size_t fdslen) {
if (fdslen / sizeof(*fds) < nfds) __chk_fail();
if (fdslen / sizeof(*fds) < nfds) fakeinput_chk_fail();
return ppoll(fds, nfds, timeout, sigmask);
}
+73 -9
View File
@@ -27,7 +27,31 @@ VkImageMemoryBarrier bar(VkImage img, VkImageLayout from, VkImageLayout to,
}
Engine::Engine() = default;
Engine::~Engine() { destroyRing(); fg_.destroy(); }
Engine::~Engine() { (void)destroy(); }
bool Engine::destroy() {
if (!fg_.destroy()) {
DDFG_LOGE("native: retaining the input ring because GPU completion is unknown");
return false;
}
if (!destroyRing(true)) {
DDFG_LOGE("native: could not release the input ring during teardown");
return false;
}
dev_ = VK_NULL_HANDLE;
unavailable_ = true;
return true;
}
void Engine::abandon() {
fg_.abandon();
ring_[0] = Slot{};
ring_[1] = Slot{};
dev_ = VK_NULL_HANDLE;
queue_ = VK_NULL_HANDLE;
phys_ = VK_NULL_HANDLE;
unavailable_ = true;
}
bool Engine::init(const VkTable& table, VkPhysicalDevice phys, VkDevice dev,
uint32_t queueFamily, VkQueue queue) {
@@ -59,15 +83,29 @@ bool Engine::prepare(uint32_t w, uint32_t h, VkFormat fmt) {
if (unavailable_ || w == 0 || h == 0 || fmt == VK_FORMAT_UNDEFINED) return false;
if (builtW_ == w && builtH_ == h && builtFmt_ == fmt && fg_.valid()) return true;
if (!fg_.onResize(VkExtent2D{w, h}, fmt, false)) {
const bool formatChanged = fmt != builtFmt_;
if (!fg_.onResize(VkExtent2D{w, h}, fmt, formatChanged)) {
DDFG_LOGE("native: onResize %ux%u failed; frame generation unavailable", w, h);
unavailable_ = true;
return false;
}
destroyRing();
bool deviceLost = false;
if (!destroyRing(false, &deviceLost)) {
DDFG_LOGE("native: could not safely release the previous input ring");
unavailable_ = true;
return false;
}
if (deviceLost) {
DDFG_LOGE("native: device lost while releasing the input ring");
unavailable_ = true;
return false;
}
for (Slot& s : ring_) {
if (!makeSlot(s, w, h, fmt)) { destroyRing(); unavailable_ = true; return false; }
if (!makeSlot(s, w, h, fmt)) {
destroyRing(true);
unavailable_ = true;
return false;
}
}
builtW_ = w; builtH_ = h; builtFmt_ = fmt;
history_ = 0; curr_ = 0; frames_ = 0;
@@ -178,11 +216,37 @@ void Engine::destroySlot(Slot& s) {
s = Slot{};
}
void Engine::destroyRing() {
if (dev_ == VK_NULL_HANDLE || !dd_.DeviceWaitIdle) return;
if (ring_[0].img || ring_[1].img) dd_.DeviceWaitIdle(dev_);
destroySlot(ring_[0]); destroySlot(ring_[1]);
bool Engine::destroyRing(bool deviceIdleConfirmed, bool* deviceLost) {
if (deviceLost) *deviceLost = false;
const bool hasResources = ring_[0].img || ring_[0].mem || ring_[0].view ||
ring_[1].img || ring_[1].mem || ring_[1].view;
if (!hasResources) {
history_ = 0;
return true;
}
if (dev_ == VK_NULL_HANDLE) {
DDFG_LOGE("native: cannot release the input ring without a valid device");
return false;
}
if (!deviceIdleConfirmed) {
if (!dd_.DeviceWaitIdle) {
DDFG_LOGE("native: cannot release the input ring without vkDeviceWaitIdle");
return false;
}
const VkResult result = dd_.DeviceWaitIdle(dev_);
if (result == VK_ERROR_DEVICE_LOST) {
if (deviceLost) *deviceLost = true;
unavailable_ = true;
} else if (result != VK_SUCCESS) {
DDFG_LOGE("native: DeviceWaitIdle failed (%d); retaining the input ring", (int)result);
unavailable_ = true;
return false;
}
}
destroySlot(ring_[0]);
destroySlot(ring_[1]);
history_ = 0;
return true;
}
}
+3 -1
View File
@@ -36,13 +36,15 @@ public:
uint32_t width, uint32_t height);
void reset();
bool destroy();
void abandon();
private:
struct Slot { VkImage img = VK_NULL_HANDLE; VkDeviceMemory mem = VK_NULL_HANDLE;
VkImageView view = VK_NULL_HANDLE; bool valid = false; };
bool makeSlot(Slot& s, uint32_t w, uint32_t h, VkFormat fmt);
void destroySlot(Slot& s);
void destroyRing();
bool destroyRing(bool deviceIdleConfirmed = false, bool* deviceLost = nullptr);
uint32_t memType(uint32_t bits, VkMemoryPropertyFlags props) const;
DeviceDispatch dd_{};
+115 -27
View File
@@ -7,6 +7,31 @@
namespace ddfg {
struct ScratchState {
VkDevice ownerDevice = VK_NULL_HANDLE;
VkBuffer synthUbo[ddfg::FrameGen::kSynthSlots]{};
VkDeviceMemory synthUboMem[ddfg::FrameGen::kSynthSlots]{};
void* synthUboPtr[ddfg::FrameGen::kSynthSlots]{};
std::vector<VkBuffer> flowUbo; std::vector<VkDeviceMemory> flowUboMem; std::vector<void*> flowUboPtr;
VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr;
VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr;
VkBuffer gmUbo[ddfg::FrameGen::kGmSlots]{};
VkDeviceMemory gmUboMem[ddfg::FrameGen::kGmSlots]{};
void* gmUboPtr[ddfg::FrameGen::kGmSlots]{};
VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> sDownA, sDownB, sFlow;
VkDescriptorSet sExpand[ddfg::FrameGen::kGmSlots]{};
VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE;
VkDescriptorSet sSynth[ddfg::FrameGen::kSynthSlots]{};
VkDescriptorSet sGmReduce[ddfg::FrameGen::kGmSlots]{};
std::vector<VkDescriptorSet> sGmPrewarp[ddfg::FrameGen::kGmSlots];
VkExtent2D builtFor{0,0};
uint64_t builtGeneration = 0;
bool built = false;
bool flowInited = false;
bool flowReady = false;
};
#define VKOK(x) do { if ((x) != VK_SUCCESS) { DDFG_LOGE("vk fail: %s", #x); return false; } } while (0)
uint32_t FrameGen::findMemType(uint32_t bits, VkMemoryPropertyFlags props) const {
@@ -108,6 +133,10 @@ static bool buildSetLayout(const DeviceDispatch* dd, VkDevice dev,
bool FrameGen::init(const DeviceDispatch* dd, const InstanceDispatch* id,
VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue) {
if (device_ || completionUnknown_ || deviceLost_) {
DDFG_LOGE("framegen: refusing to initialize an instance that still owns device resources");
return false;
}
dd_ = dd; id_ = id; phys_ = phys; device_ = dev; queueFamily_ = queueFamily; queue_ = queue;
id_->GetPhysicalDeviceMemoryProperties(phys_, &memProps_);
@@ -166,16 +195,19 @@ static VkExtent2D levelExtent(VkExtent2D e, int l) {
}
bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
if (!force && ready_ && extent.width == extent_.width && extent.height == extent_.height) return true;
if (ready_) {
const VkResult idleResult = dd_->DeviceWaitIdle(device_);
if (idleResult != VK_SUCCESS) {
DDFG_LOGE("framegen resize: DeviceWaitIdle failed (%d); keeping existing images", (int)idleResult);
return false;
}
if (completionUnknown_ || deviceLost_) return false;
if (!device_) {
DDFG_LOGE("framegen: cannot resize before device initialization");
return false;
}
if (!force && ready_ && extent.width == extent_.width && extent.height == extent_.height) return true;
if (ready_ && !waitIdle("resize")) return false;
if (scratch_ && scratch_->ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) {
DDFG_LOGE("framegen resize: scratch cleanup failed; retaining the previous image set");
return false;
}
ready_ = false;
++imageGeneration_;
for (auto& i : pyrA_) destroyImage(i); pyrA_.clear();
for (auto& i : pyrB_) destroyImage(i); pyrB_.clear();
@@ -183,7 +215,17 @@ bool FrameGen::onResize(VkExtent2D extent, VkFormat , bool force) {
for (auto& i : flowLvl_) destroyImage(i); flowLvl_.clear();
destroyImage(flowExpA_); destroyImage(flowExpB_);
destroyImage(flowRegA_); destroyImage(flowRegB_);
extent_ = extent; ready_ = false;
extent_ = extent;
for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0;
for (int s = 0; s < kGmSlots; ++s) {
gmSlotValid_[s] = false;
for (int i = 0; i < 6; ++i) gmLinAt_[s][i] = 0.0;
}
gmHaveEst_ = false;
gmEngaged_ = false;
gmStableCount_ = 0;
gmLastTransPx_ = 0.0f;
const VkImageUsageFlags lumaUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT;
const VkImageUsageFlags flowUsage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
@@ -234,21 +276,37 @@ void FrameGen::initializeImage(VkCommandBuffer cmd, VkImage img, VkImageLayout t
}
void FrameGen::destroy() {
if (!device_) return;
const VkResult idleResult = dd_->DeviceWaitIdle(device_);
if (idleResult != VK_SUCCESS && idleResult != VK_ERROR_DEVICE_LOST) {
DDFG_LOGE("framegen destroy: DeviceWaitIdle failed (%d); preserving resources for safe retry", (int)idleResult);
return;
}
if (idleResult == VK_ERROR_DEVICE_LOST) {
// A lost device cannot become idle again. Still explicitly destroy its
// child objects; skip descriptor-pool reset and release scratch ownership.
DDFG_LOGE("framegen destroy: device lost; releasing owned resources without waiting");
destroyScratchResources(false);
} else {
destroyScratchResources();
bool FrameGen::destroy() {
if (!device_) return true;
if (!deviceLost_) {
// A previous wait failure leaves completion unknown, but a later
// teardown attempt may safely retry the wait before releasing resources.
if (!dd_ || !dd_->DeviceWaitIdle) {
ready_ = false;
completionUnknown_ = true;
DDFG_LOGE("framegen destroy: vkDeviceWaitIdle is unavailable; preserving GPU resources");
return false;
}
const VkResult idleResult = dd_->DeviceWaitIdle(device_);
if (idleResult == VK_SUCCESS) completionUnknown_ = false;
if (idleResult != VK_SUCCESS) {
ready_ = false;
if (idleResult == VK_ERROR_DEVICE_LOST) {
deviceLost_ = true;
DDFG_LOGE("framegen destroy: device lost; releasing owned resources without waiting");
} else {
completionUnknown_ = true;
DDFG_LOGE("framegen destroy: DeviceWaitIdle failed (%d); preserving resources because GPU completion is unknown",
(int)idleResult);
return false;
}
}
}
ready_ = false;
if (descPool_) dd_->DestroyDescriptorPool(device_, descPool_, nullptr);
descPool_ = VK_NULL_HANDLE;
releaseScratch();
for (auto& i : pyrA_) destroyImage(i); pyrA_.clear();
for (auto& i : pyrB_) destroyImage(i); pyrB_.clear();
for (auto& i : pyrAs_) destroyImage(i); pyrAs_.clear();
@@ -260,15 +318,45 @@ void FrameGen::destroy() {
destroyPipe(pGmReduce_); destroyPipe(pGmPrewarp_);
destroyPipe(pFlowReg_);
for (int s = 0; s < kGmSlots; ++s) {
if (gmSsboMem_[s]) dd_->UnmapMemory(device_, gmSsboMem_[s]);
if (gmSsboPtr_[s] && gmSsboMem_[s]) dd_->UnmapMemory(device_, gmSsboMem_[s]);
if (gmSsbo_[s]) dd_->DestroyBuffer(device_, gmSsbo_[s], nullptr);
if (gmSsboMem_[s]) dd_->FreeMemory(device_, gmSsboMem_[s], nullptr);
gmSsbo_[s] = VK_NULL_HANDLE; gmSsboMem_[s] = VK_NULL_HANDLE; gmSsboPtr_[s] = nullptr;
}
gmBuffersReady_ = false;
if (descPool_) dd_->DestroyDescriptorPool(device_, descPool_, nullptr);
if (linear_) dd_->DestroySampler(device_, linear_, nullptr);
descPool_ = VK_NULL_HANDLE; linear_ = VK_NULL_HANDLE; device_ = VK_NULL_HANDLE; ready_ = false;
linear_ = VK_NULL_HANDLE;
device_ = VK_NULL_HANDLE;
ready_ = false;
deviceLost_ = false;
return true;
}
void FrameGen::abandon() {
device_ = VK_NULL_HANDLE;
dd_ = nullptr;
id_ = nullptr;
phys_ = VK_NULL_HANDLE;
queue_ = VK_NULL_HANDLE;
linear_ = VK_NULL_HANDLE;
descPool_ = VK_NULL_HANDLE;
scratch_.reset();
pyrA_.clear(); pyrB_.clear(); pyrAs_.clear(); flowLvl_.clear();
flowExpA_ = Img{}; flowExpB_ = Img{};
flowRegA_ = Img{}; flowRegB_ = Img{};
pLuma_ = Pipe{}; pDown_ = Pipe{}; pFlow_ = Pipe{}; pFlowM4_ = Pipe{};
pExpand_ = Pipe{}; pExpandM4_ = Pipe{}; pSynth_ = Pipe{};
pGmReduce_ = Pipe{}; pGmPrewarp_ = Pipe{}; pFlowReg_ = Pipe{};
for (int s = 0; s < kGmSlots; ++s) {
gmSsbo_[s] = VK_NULL_HANDLE;
gmSsboMem_[s] = VK_NULL_HANDLE;
gmSsboPtr_[s] = nullptr;
gmSlotValid_[s] = false;
}
gmBuffersReady_ = false;
ready_ = false;
completionUnknown_ = false;
deviceLost_ = false;
}
}
+16 -2
View File
@@ -1,12 +1,20 @@
#pragma once
#include "vk_dispatch.hpp"
#include "config.hpp"
#include <memory>
#include <vector>
namespace ddfg {
struct ScratchState;
class FrameGen {
public:
FrameGen();
~FrameGen();
FrameGen(const FrameGen&) = delete;
FrameGen& operator=(const FrameGen&) = delete;
bool init(const DeviceDispatch* dd, const InstanceDispatch* id,
VkPhysicalDevice phys, VkDevice dev, uint32_t queueFamily, VkQueue queue);
void configure(const Config& c);
@@ -14,7 +22,8 @@ public:
void record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView,
VkImageView outView, float alpha, uint32_t gmSlot = 0,
uint32_t synthSlot = 0, bool reuseFlow = false);
void destroy();
bool destroy();
void abandon();
bool valid() const { return device_ != VK_NULL_HANDLE && ready_; }
const Config& config() const { return cfg_; }
@@ -64,7 +73,9 @@ private:
void destroyPipe(Pipe& p);
void barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to);
void initializeImage(VkCommandBuffer cmd, VkImage img, VkImageLayout to);
void destroyScratchResources(bool resetPool = true);
bool waitIdle(const char* operation);
bool destroyScratchResources(bool resetPool = true);
void releaseScratch();
const DeviceDispatch* dd_ = nullptr;
const InstanceDispatch* id_ = nullptr;
@@ -80,7 +91,10 @@ private:
VkExtent2D extent_{};
uint64_t imageGeneration_ = 0;
bool ready_ = false;
bool completionUnknown_ = false;
bool deviceLost_ = false;
int flowFinest_ = kFlowFinestDefault;
std::unique_ptr<ScratchState> scratch_;
Pipe pLuma_, pDown_, pFlow_, pFlowM4_, pExpand_, pExpandM4_, pSynth_;
Pipe pGmReduce_, pGmPrewarp_;
+95 -89
View File
@@ -1,33 +1,7 @@
namespace {
struct ScratchState {
VkDevice ownerDevice = VK_NULL_HANDLE;
VkBuffer synthUbo[ddfg::FrameGen::kSynthSlots]{};
VkDeviceMemory synthUboMem[ddfg::FrameGen::kSynthSlots]{};
void* synthUboPtr[ddfg::FrameGen::kSynthSlots]{};
std::vector<VkBuffer> flowUbo; std::vector<VkDeviceMemory> flowUboMem; std::vector<void*> flowUboPtr;
VkBuffer expandUbo = VK_NULL_HANDLE; VkDeviceMemory expandUboMem = VK_NULL_HANDLE; void* expandUboPtr = nullptr;
VkBuffer flowRegUbo = VK_NULL_HANDLE; VkDeviceMemory flowRegUboMem = VK_NULL_HANDLE; void* flowRegUboPtr = nullptr;
VkBuffer gmUbo[ddfg::FrameGen::kGmSlots]{};
VkDeviceMemory gmUboMem[ddfg::FrameGen::kGmSlots]{};
void* gmUboPtr[ddfg::FrameGen::kGmSlots]{};
VkDescriptorSet sLumaCurr = VK_NULL_HANDLE, sLumaPrev = VK_NULL_HANDLE;
std::vector<VkDescriptorSet> sDownA, sDownB, sFlow;
VkDescriptorSet sExpand[ddfg::FrameGen::kGmSlots]{};
VkDescriptorSet sFlowReg0 = VK_NULL_HANDLE, sFlowRegAB = VK_NULL_HANDLE, sFlowRegBA = VK_NULL_HANDLE;
VkDescriptorSet sSynth[ddfg::FrameGen::kSynthSlots]{};
VkDescriptorSet sGmReduce[ddfg::FrameGen::kGmSlots]{};
std::vector<VkDescriptorSet> sGmPrewarp[ddfg::FrameGen::kGmSlots];
VkExtent2D builtFor{0,0};
uint64_t builtGeneration = 0;
bool built = false;
bool flowInited = false;
bool flowReady = false;
};
ScratchState g_scratch;
namespace ddfg {
FrameGen::FrameGen() : scratch_(std::make_unique<ScratchState>()) {}
FrameGen::~FrameGen() { (void)destroy(); }
}
static bool makeUbo(const ddfg::DeviceDispatch* dd, VkDevice dev,
@@ -144,7 +118,7 @@ static void mulAff(const double A[3][3], const double B[3][3], double out[3][3])
namespace ddfg {
static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
static bool ensureScratch(ScratchState& S, FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool,
VkSampler samp, VkExtent2D ext,
std::vector<FrameGen::Img>& pyrA, std::vector<FrameGen::Img>& pyrB,
@@ -157,30 +131,72 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
FrameGen::Img& flowRegA, FrameGen::Img& flowRegB, VkBuffer* gmSsbo,
int kLevels, const Config& cfg, uint64_t imageGeneration);
static void destroyScratch(const DeviceDispatch* dd, VkDevice dev, VkDescriptorPool pool,
bool resetPool = true) {
if (g_scratch.ownerDevice != VK_NULL_HANDLE && g_scratch.ownerDevice != dev) return;
bool FrameGen::waitIdle(const char* operation) {
if (completionUnknown_ || deviceLost_ || !device_) return false;
if (!dd_ || !dd_->DeviceWaitIdle) {
completionUnknown_ = true;
ready_ = false;
DDFG_LOGE("framegen: %s cannot confirm GPU completion; this instance is stopped and its resources are retained",
operation);
return false;
}
const VkResult result = dd_->DeviceWaitIdle(device_);
if (result == VK_SUCCESS) return true;
ready_ = false;
if (result == VK_ERROR_DEVICE_LOST) {
deviceLost_ = true;
DDFG_LOGE("framegen: %s reported device loss; cleanup will skip further waits", operation);
} else {
completionUnknown_ = true;
DDFG_LOGE("framegen: %s vkDeviceWaitIdle failed (%d); this instance is stopped and its GPU resources retained",
operation, (int)result);
}
return false;
}
bool FrameGen::destroyScratchResources(bool resetPool) {
if (!scratch_) return true;
if (resetPool && descPool_ && !deviceLost_) {
if (!dd_ || !dd_->ResetDescriptorPool) {
ready_ = false;
DDFG_LOGE("framegen: descriptor-pool reset is unavailable; retaining scratch resources");
return false;
}
const VkResult result = dd_->ResetDescriptorPool(device_, descPool_, 0);
if (result != VK_SUCCESS) {
ready_ = false;
if (result == VK_ERROR_DEVICE_LOST) deviceLost_ = true;
DDFG_LOGE("framegen: descriptor-pool reset failed (%d); retaining scratch resources",
(int)result);
return false;
}
}
releaseScratch();
return true;
}
void FrameGen::releaseScratch() {
if (!scratch_) return;
auto& S = *scratch_;
auto freeUbo = [&](VkBuffer& b, VkDeviceMemory& m, void*& p) {
if (m) dd->UnmapMemory(dev, m);
if (b) dd->DestroyBuffer(dev, b, nullptr);
if (m) dd->FreeMemory(dev, m, nullptr);
b = VK_NULL_HANDLE; m = VK_NULL_HANDLE; p = nullptr;
if (p && m) dd_->UnmapMemory(device_, m);
if (b) dd_->DestroyBuffer(device_, b, nullptr);
if (m) dd_->FreeMemory(device_, m, nullptr);
b = VK_NULL_HANDLE;
m = VK_NULL_HANDLE;
p = nullptr;
};
auto& S = g_scratch;
for (int s = 0; s < FrameGen::kSynthSlots; ++s) freeUbo(S.synthUbo[s], S.synthUboMem[s], S.synthUboPtr[s]);
freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr);
freeUbo(S.expandUbo, S.expandUboMem, S.expandUboPtr);
freeUbo(S.flowRegUbo, S.flowRegUboMem, S.flowRegUboPtr);
for (size_t i = 0; i < S.flowUbo.size(); ++i) freeUbo(S.flowUbo[i], S.flowUboMem[i], S.flowUboPtr[i]);
for (int s = 0; s < FrameGen::kGmSlots; ++s) freeUbo(S.gmUbo[s], S.gmUboMem[s], S.gmUboPtr[s]);
if (resetPool && pool && dd->ResetDescriptorPool) dd->ResetDescriptorPool(dev, pool, 0);
S = ScratchState{};
}
void FrameGen::destroyScratchResources(bool resetPool) {
destroyScratch(dd_, device_, descPool_, resetPool);
}
void FrameGen::configure(const Config& c) {
if (completionUnknown_ || deviceLost_) return;
Config nextCfg = c;
nextCfg.sanitize();
int want = flowFinestForPreset(nextCfg.perfPreset);
@@ -203,16 +219,12 @@ void FrameGen::configure(const Config& c) {
return;
}
// Keep the previous configuration and image set if the device cannot idle.
const VkResult idleResult = dd_->DeviceWaitIdle(device_);
if (idleResult != VK_SUCCESS) {
DDFG_LOGE("framegen configure: DeviceWaitIdle failed (%d); keeping previous configuration and images",
(int)idleResult);
if (!waitIdle("live preset rebuild")) return;
if (scratch_ && scratch_->ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) {
DDFG_LOGE("perf-preset live rebuild: scratch cleanup failed; keeping the previous configuration");
return;
}
// The device is idle, so reset motion history before rebuilding. This
// also leaves the predictor reset if onResize fails.
for (int i = 0; i < 6; ++i) gmRun_[i] = 0.0;
for (int s = 0; s < kGmSlots; ++s) {
gmSlotValid_[s] = false;
@@ -223,20 +235,17 @@ void FrameGen::configure(const Config& c) {
gmStableCount_ = 0;
gmLastTransPx_ = 0.0f;
// Prevent onResize from issuing a second wait.
destroyScratch(dd_, device_, descPool_);
cfg_ = nextCfg;
flowFinest_ = want;
ready_ = false;
if (!onResize(extent_, VK_FORMAT_UNDEFINED, true)) {
ready_ = false;
DDFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - FG disabled until next resize",
DDFG_LOGE("perf-preset live rebuild: onResize FAILED at %ux%u - frame generation unavailable",
extent_.width, extent_.height);
return;
}
DDFG_LOGI("perf-preset live rebuild DONE (kFlowFinest=%d, flow predictor reset)", flowFinest_);
}
bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) {
++gmFrames_;
if (!gmBuffersReady_ || cfg_.gmMode == 2 ) {
@@ -306,35 +315,33 @@ bool FrameGen::updateGlobalMotion(uint32_t gmSlot, VkExtent2D fullExtent) {
void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView currView,
VkImageView outView, float alpha, uint32_t gmSlot, uint32_t synthSlot, bool reuseFlow) {
if (!valid()) return;
auto& S = *scratch_;
if (gmSlot >= (uint32_t)kGmSlots) gmSlot = 0;
if (synthSlot >= (uint32_t)kSynthSlots) synthSlot = 0;
const bool m4 = (cfg_.model == 4);
const Pipe& flowP = m4 ? pFlowM4_ : pFlow_;
const Pipe& expandP = m4 ? pExpandM4_ : pExpand_;
if (!g_scratch.built || g_scratch.builtFor.width != extent_.width ||
g_scratch.builtFor.height != extent_.height ||
g_scratch.builtGeneration != imageGeneration_) {
if (g_scratch.built) {
const VkResult idleResult = dd_->DeviceWaitIdle(device_);
if (idleResult != VK_SUCCESS) {
DDFG_LOGE("framegen record: DeviceWaitIdle failed (%d); skipping scratch rebuild", (int)idleResult);
return;
}
destroyScratch(dd_, device_, descPool_);
if (!S.built || S.builtFor.width != extent_.width ||
S.builtFor.height != extent_.height ||
S.builtGeneration != imageGeneration_) {
if (S.built && !waitIdle("scratch rebuild")) return;
if (S.ownerDevice != VK_NULL_HANDLE && !destroyScratchResources()) {
DDFG_LOGE("framegen record: scratch cleanup failed; skipping this frame");
return;
}
if (!ensureScratch(this, dd_, device_, memProps_, descPool_, linear_, extent_,
if (!ensureScratch(S, this, dd_, device_, memProps_, descPool_, linear_, extent_,
pyrA_, pyrB_, pyrAs_, flowLvl_, flowExpA_, flowExpB_,
pLuma_, pDown_, flowP, expandP, pSynth_, pGmReduce_, pGmPrewarp_,
pFlowReg_, flowRegA_, flowRegB_, gmSsbo_, kLevels, cfg_, imageGeneration_))
return;
}
if (g_scratch.ownerDevice != device_) return;
if (reuseFlow && !g_scratch.flowReady) return;
if (S.ownerDevice != device_) return;
if (reuseFlow && !S.flowReady) return;
if (!reuseFlow) {
bool gmEngaged = updateGlobalMotion(gmSlot, extent_);
if (g_scratch.gmUboPtr[gmSlot]) {
if (S.gmUboPtr[gmSlot]) {
GMUBO g{};
g.lin[0]=(float)gmRun_[0]; g.lin[1]=(float)gmRun_[1]; g.lin[2]=(float)gmRun_[2]; g.lin[3]=(float)gmRun_[3];
g.linT[0]=(float)gmRun_[4]; g.linT[1]=(float)gmRun_[5]; g.linT[2]=gmEngaged?1.0f:0.0f; g.linT[3]=0.0f;
@@ -342,7 +349,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
g.app[0]=(float)gmRun_[0]; g.app[1]=(float)gmRun_[1]; g.app[2]=(float)gmRun_[2]; g.app[3]=(float)gmRun_[3];
g.appT[0]=(float)gmRun_[4]; g.appT[1]=(float)gmRun_[5];
}
std::memcpy(g_scratch.gmUboPtr[gmSlot], &g, sizeof(g));
std::memcpy(S.gmUboPtr[gmSlot], &g, sizeof(g));
}
{
static int lastEng = -1;
@@ -353,7 +360,7 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
}
}
const VkDescriptorSet lumaSets[] = {g_scratch.sLumaCurr, g_scratch.sLumaPrev};
const VkDescriptorSet lumaSets[] = {S.sLumaCurr, S.sLumaPrev};
const uint32_t lumaBindings[] = {32, 32};
const VkDescriptorType lumaTypes[] = {
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER};
@@ -367,9 +374,9 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
SynthUBO su{cfg_.flowScale, alpha, cfg_.beta, cfg_.lambda, cfg_.epsilon, cfg_.photoScale, 0, 0,
cfg_.hudX0, cfg_.hudY0, cfg_.hudX1, cfg_.hudY1};
if (g_scratch.synthUboPtr[synthSlot]) std::memcpy(g_scratch.synthUboPtr[synthSlot], &su, sizeof(su));
if (S.synthUboPtr[synthSlot]) std::memcpy(S.synthUboPtr[synthSlot], &su, sizeof(su));
const VkDescriptorSet synthSet = g_scratch.sSynth[synthSlot];
const VkDescriptorSet synthSet = S.sSynth[synthSlot];
const VkDescriptorSet synthSets[] = {synthSet, synthSet, synthSet};
const uint32_t synthBindings[] = {32, 33, 48};
const VkDescriptorType synthTypes[] = {
@@ -468,17 +475,17 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &b);
}
disp(pLuma_, g_scratch.sLumaCurr, levelExtent(extent_, 0));
disp(pLuma_, g_scratch.sLumaPrev, levelExtent(extent_, 0));
disp(pLuma_, S.sLumaCurr, levelExtent(extent_, 0));
disp(pLuma_, S.sLumaPrev, levelExtent(extent_, 0));
barPair(pyrA_[0], pyrB_[0]);
for (int l = 1; l < kLevels; ++l) {
disp(pDown_, g_scratch.sDownA[l - 1], levelExtent(extent_, l));
disp(pDown_, g_scratch.sDownB[l - 1], levelExtent(extent_, l));
disp(pDown_, S.sDownA[l - 1], levelExtent(extent_, l));
disp(pDown_, S.sDownB[l - 1], levelExtent(extent_, l));
barPair(pyrA_[l], pyrB_[l]);
}
if (gmBuffersReady_ && g_scratch.sGmReduce[gmSlot]) {
if (gmBuffersReady_ && S.sGmReduce[gmSlot]) {
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.pipeline);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &g_scratch.sGmReduce[gmSlot], 0, nullptr);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pGmReduce_.layout, 0, 1, &S.sGmReduce[gmSlot], 0, nullptr);
dd_->CmdDispatch(cmd, (uint32_t)(kGmThreads / 64), 1, 1);
VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER};
mb.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; mb.dstAccessMask = VK_ACCESS_HOST_READ_BIT;
@@ -486,27 +493,27 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
0, 1, &mb, 0, nullptr, 0, nullptr);
}
for (int l = flowFinest_; l < kLevels; ++l) {
disp(pGmPrewarp_, g_scratch.sGmPrewarp[gmSlot][l], levelExtent(extent_, l));
disp(pGmPrewarp_, S.sGmPrewarp[gmSlot][l], levelExtent(extent_, l));
bar(pyrAs_[l]);
}
for (int l = kLevels - 1; l >= flowFinest_; --l) {
disp(flowP, g_scratch.sFlow[l], levelExtent(extent_, l));
disp(flowP, S.sFlow[l], levelExtent(extent_, l));
bar(flowLvl_[l]);
}
if (frEngaged) {
const int F = flowFinest_;
const VkExtent2D fe = levelExtent(extent_, F);
if (g_scratch.flowRegUboPtr) {
if (S.flowRegUboPtr) {
FlowRegUBO fu{cfg_.frDt, cfg_.frLambda, cfg_.frEdge, cfg_.frEps};
std::memcpy(g_scratch.flowRegUboPtr, &fu, sizeof(fu));
std::memcpy(S.flowRegUboPtr, &fu, sizeof(fu));
}
FrameGen::Img* last = nullptr;
for (int it = 0; it < cfg_.frIters; ++it) {
VkDescriptorSet set; FrameGen::Img* outImg;
if (it == 0) { set = g_scratch.sFlowReg0; outImg = &flowRegA_; }
else if (it % 2 == 1) { set = g_scratch.sFlowRegAB; outImg = &flowRegB_; }
else { set = g_scratch.sFlowRegBA; outImg = &flowRegA_; }
if (it == 0) { set = S.sFlowReg0; outImg = &flowRegA_; }
else if (it % 2 == 1) { set = S.sFlowRegAB; outImg = &flowRegB_; }
else { set = S.sFlowRegBA; outImg = &flowRegA_; }
dd_->CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.pipeline);
dd_->CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pFlowReg_.layout, 0, 1, &set, 0, nullptr);
dd_->CmdDispatch(cmd, (fe.width + 15) / 16, (fe.height + 15) / 16, 1);
@@ -540,14 +547,14 @@ void FrameGen::record(VkCommandBuffer cmd, VkImageView prevView, VkImageView cur
}
}
disp(expandP, g_scratch.sExpand[gmSlot], levelExtent(extent_, 0));
disp(expandP, S.sExpand[gmSlot], levelExtent(extent_, 0));
barPair(flowExpA_, flowExpB_);
g_scratch.flowReady = true;
S.flowReady = true;
}
disp(pSynth_, synthSet, levelExtent(extent_, 0));
}
static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
static bool ensureScratch(ScratchState& S, FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
const VkPhysicalDeviceMemoryProperties& mp, VkDescriptorPool pool,
VkSampler samp, VkExtent2D ext,
std::vector<FrameGen::Img>& pyrA, std::vector<FrameGen::Img>& pyrB,
@@ -559,7 +566,6 @@ static bool ensureScratch(FrameGen* fg, const DeviceDispatch* dd, VkDevice dev,
const FrameGen::Pipe& pGmPrewarp, const FrameGen::Pipe& pFlowReg,
FrameGen::Img& flowRegA, FrameGen::Img& flowRegB, VkBuffer* gmSsbo,
int kLevels, const Config& cfg, uint64_t imageGeneration) {
auto& S = g_scratch;
if (S.ownerDevice != VK_NULL_HANDLE && S.ownerDevice != dev) return false;
S = ScratchState{};
S.ownerDevice = dev;
@@ -7,6 +7,7 @@
#include "droiddeck-ahb-v1-server-protocol.h"
#include <android/hardware_buffer.h>
#include <errno.h>
#include <linux/sync_file.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
@@ -145,6 +146,12 @@ static void handle_released(uint64_t id, int fd) {
if (poll(&p, 1, 0) > 0) {
close(fd);
} else {
if (ab->fence_src) {
struct sync_merge_data m = {.name = "droiddeck-release", .fd2 = fd};
if (ioctl(ab->fence_fd, SYNC_IOC_MERGE, &m) == 0) { close(fd); fd = m.fence; }
wl_event_source_remove(ab->fence_src);
close(ab->fence_fd);
}
ab->fence_fd = fd;
ab->fence_src = wl_event_loop_add_fd(g_loop, fd, WL_EVENT_READABLE, on_fence_readable, ab);
if (!ab->fence_src) { close(fd); ab->fence_fd = -1; }
@@ -152,6 +159,7 @@ static void handle_released(uint64_t id, int fd) {
}
}
}
if (ab->fence_src) return;
send_deferred_release(ab);
maybe_free(ab);
}
+210 -86
View File
@@ -3,6 +3,7 @@
#include "blend_pass.h"
#include "vk_loader.h"
#include "vk_present.h"
#include "framegen_bridge.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
@@ -69,6 +70,7 @@ static struct fx_settings g_set = {
.gamma = 1.0f, .saturation = 1.0f, .s_raw = 100.0f, .look = "Off"};
static volatile int g_changed;
static struct fx_settings g_cur;
static struct fx_settings g_generated_settings;
static int g_cur_valid;
static void set_begin(void) { pthread_mutex_lock(&g_lock); }
@@ -235,13 +237,24 @@ static VkDescriptorPool g_dpool;
static VkSampler g_sampler;
enum { P_SGSR, P_SGSR_HQ, P_NIS, P_EASU, P_RCAS, P_CAS, P_COLOR, P_FXAA, P_FXAA_TOON, P_SMAA_EDGE, P_SMAA_WEIGHTS, P_SMAA_BLEND, P_TOON, P_TOON_COLOR, P_HDR, P_NTSC, P_CRT, P_DEBAND, P_NIS_LUMA, P_COUNT };
static VkPipeline g_pipe[P_COUNT];
static struct fx_target g_t[2], g_mid, g_smaa_edges, g_smaa_weights;
struct fx_context {
struct fx_target targets[2], mid, nissrc;
struct { VkImage img; VkImageView view; VkDescriptorSet ds; int w, h; } scene;
};
#define FX_CONTEXTS (VKP_FG_MAX_GENERATIONS + 2)
static struct fx_context g_contexts[FX_CONTEXTS];
static int g_context;
#define g_t (g_contexts[g_context].targets)
#define g_mid (g_contexts[g_context].mid)
#define g_nissrc (g_contexts[g_context].nissrc)
static struct fx_target g_smaa_edges, g_smaa_weights;
/* Half set: NIS = nis_luma prepass (scene rgb + luma in alpha, scene size) into g_nissrc, then
* nis3 gathers its luma from that alpha, its coefficient banks (nis_coef.h) in a uniform buffer
* at descriptor set 1 (g_pl_nis = {g_dsl, g_coef_dsl}, same push-constant range as g_pl).
* Old set (or no buffer): nis.frag on the scene, P_NIS_LUMA unused. */
static struct fx_target g_nissrc;
static int g_nis_fast;
static int g_nis_attempted;
static int g_upscale_half;
static VkDescriptorSetLayout g_coef_dsl;
static VkPipelineLayout g_pl_nis;
static VkDescriptorPool g_coef_pool;
@@ -249,7 +262,7 @@ static VkDescriptorSet g_coef_ds;
static VkBuffer g_coef_buf;
static VkDeviceMemory g_coef_mem;
static struct { VkImage img; VkImageView view; VkDescriptorSet ds; int w, h; } g_scene;
#define g_scene (g_contexts[g_context].scene)
void vkp_effects_bind_device(VkDevice dev, VkPhysicalDevice pd,
const VkPhysicalDeviceMemoryProperties *memprops) {
@@ -347,7 +360,15 @@ static void scene_release(void) {
}
void vkp_effects_forget_image(VkImage img) {
if (img && g_scene.img == img) scene_release();
int saved = g_context;
for (g_context = 0; g_context < FX_CONTEXTS; g_context++)
if (img && g_scene.img == img) scene_release();
g_context = saved;
}
void vkp_effects_release_generated_sources(void) {
for (g_context = 1; g_context < FX_CONTEXTS; g_context++) scene_release();
g_context = 0;
}
static int scene_ensure(VkImage img, int w, int h) {
@@ -473,9 +494,14 @@ static int upscale_half_set(void) {
static void objects_destroy(void) {
if (!g_dev) return;
scene_release();
target_destroy(&g_t[0]); target_destroy(&g_t[1]); target_destroy(&g_mid);
target_destroy(&g_smaa_edges); target_destroy(&g_smaa_weights); target_destroy(&g_nissrc);
int saved = g_context;
for (g_context = 0; g_context < FX_CONTEXTS; g_context++) {
scene_release();
target_destroy(&g_t[0]); target_destroy(&g_t[1]); target_destroy(&g_mid);
target_destroy(&g_nissrc);
}
g_context = saved;
target_destroy(&g_smaa_edges); target_destroy(&g_smaa_weights);
for (int i = 0; i < P_COUNT; i++) { if (g_pipe[i]) g_vk.DestroyPipeline(g_dev, g_pipe[i], NULL); g_pipe[i] = VK_NULL_HANDLE; }
if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL);
if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL);
@@ -486,6 +512,7 @@ static void objects_destroy(void) {
if (g_rp) g_vk.DestroyRenderPass(g_dev, g_rp, NULL);
g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE; g_dsl = VK_NULL_HANDLE;
g_sampler = VK_NULL_HANDLE; g_rp = VK_NULL_HANDLE; g_smaa_rp = VK_NULL_HANDLE;
g_nis_fast = 0; g_nis_attempted = 0; g_upscale_half = 0;
g_ready = 0;
}
@@ -505,7 +532,9 @@ void vkp_effects_set_formats(VkFormat scene_fmt, VkFormat target_fmt, int scene_
: target_fmt == VK_FORMAT_R16G16B16A16_SFLOAT ? "the HDR picture for frame generation"
: "the HDR composition's picture: PQ, or tone-mapped SDR with HDR output off");
} else if (scene_fmt != g_scene_fmt) {
scene_release();
int saved = g_context;
for (g_context = 0; g_context < FX_CONTEXTS; g_context++) scene_release();
g_context = saved;
g_scene_fmt = scene_fmt;
}
}
@@ -556,75 +585,17 @@ static int objects_ensure(void) {
VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 2, .pSetLayouts = set_layouts,
.pushConstantRangeCount = 1, .pPushConstantRanges = &pcr};
if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail;
VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 10};
VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, FX_CONTEXTS * 5 + 2};
VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = 10,
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = FX_CONTEXTS * 5 + 2,
.poolSizeCount = 1, .pPoolSizes = &ps};
if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail;
VkShaderModule vert = shader(upscale_vert_code, sizeof(upscale_vert_code));
if (!vert) goto fail;
#define MKL(slot, code, name, layout) do { g_pipe[slot] = post_pipeline_for_renderpass(vert, code, sizeof(code), g_rp, name, layout); if (!g_pipe[slot]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; } } while (0)
#define MK(slot, code, name) MKL(slot, code, name, g_pl)
const int half = upscale_half_set();
g_upscale_half = upscale_half_set();
g_nis_fast = 0;
if (half && !fx_alpha_holds_luma(g_fx_fmt))
droiddeck_log("effects", "NIS uses nis.frag: the chain format has no 8-bit alpha for the luma prepass");
else if (half && coef_create() != 0)
droiddeck_log("effects", "NIS coefficient buffer unavailable; NIS uses nis.frag");
else if (half)
g_nis_fast = 1;
if (half) {
MK(P_SGSR, sgsr_half_code, "sgsr_half");
MK(P_SGSR_HQ, sgsr_quality_half_code, "sgsr_quality_half");
if (g_nis_fast) {
/* optional: a driver that rejects either fast NIS pipeline gets nis.frag, not a dead chain */
g_pipe[P_NIS] = post_pipeline_for_renderpass(vert, nis3_half_code, sizeof(nis3_half_code), g_rp, "nis3_half", g_pl_nis);
g_pipe[P_NIS_LUMA] = g_pipe[P_NIS]
? post_pipeline_for_renderpass(vert, nis_luma_half_code, sizeof(nis_luma_half_code), g_rp, "nis_luma_half", g_pl)
: VK_NULL_HANDLE;
if (!g_pipe[P_NIS] || !g_pipe[P_NIS_LUMA]) {
if (g_pipe[P_NIS]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS], NULL);
g_pipe[P_NIS] = VK_NULL_HANDLE;
coef_destroy();
g_nis_fast = 0;
droiddeck_log("effects", "fast NIS pipelines failed to build; NIS uses nis.frag");
}
}
if (!g_nis_fast) MK(P_NIS, nis_code, "nis");
MK(P_EASU, fsr_easu_half_code, "fsr_easu_half");
MK(P_RCAS, fsr_rcas_half_code, "fsr_rcas_half");
MK(P_CAS, cas_ffx_half_code, "cas_ffx_half");
} else {
MK(P_SGSR, sgsr_code, "sgsr");
MK(P_SGSR_HQ, sgsr_quality_code, "sgsr_quality");
MK(P_NIS, nis_code, "nis");
MK(P_EASU, fsr_easu_code, "fsr_easu");
MK(P_RCAS, fsr_rcas_code, "fsr_rcas");
MK(P_CAS, cas_code, "cas");
}
MK(P_COLOR, color_code, "color");
MK(P_FXAA, fxaa_code, "fxaa");
MK(P_FXAA_TOON, fxaa_toon_code, "fxaa_toon");
g_pipe[P_SMAA_EDGE] = post_pipeline_for_renderpass(
vert, smaa_edge_code, sizeof(smaa_edge_code), g_smaa_rp, "smaa_edge", g_pl);
if (!g_pipe[P_SMAA_EDGE]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; }
g_pipe[P_SMAA_WEIGHTS] = post_pipeline_for_renderpass(
vert, smaa_weights_code, sizeof(smaa_weights_code), g_smaa_rp, "smaa_weights", g_pl);
if (!g_pipe[P_SMAA_WEIGHTS]) { g_vk.DestroyShaderModule(g_dev, vert, NULL); goto fail; }
MK(P_SMAA_BLEND, smaa_blend_code, "smaa_blend");
MK(P_TOON, toon_code, "toon");
MK(P_TOON_COLOR, toon_color_code, "toon_color");
MK(P_HDR, hdr_code, "hdr");
MK(P_NTSC, ntsc_code, "ntsc");
MK(P_CRT, crt_code, "crt");
MK(P_DEBAND, deband_code, "deband");
#undef MK
#undef MKL
g_vk.DestroyShaderModule(g_dev, vert, NULL);
g_nis_attempted = 0;
g_ready = 1;
droiddeck_log("effects", "chain ready: 16 pipelines (SGSR, SGSR HQ, NIS, FSR EASU+RCAS, CAS, colour, FXAA, SMAA edge/weights/blend, Toon, HDR, NTSC, CRT, deband), %s upscalers%s, on %s",
half ? "half-precision" : "old fp32", g_nis_fast ? " + NIS luma prepass" : "", vkp_gpu_name());
droiddeck_log("effects", "shared resources ready on %s; effect pipelines are created when needed", vkp_gpu_name());
return 0;
fail:
objects_destroy();
@@ -633,6 +604,95 @@ fail:
return -1;
}
static int chain_failed(void) {
objects_destroy();
g_ready = -1;
droiddeck_log("error", "effects: the screen-effect chain could not be built on this driver; effects are off for this session");
return -1;
}
static int pipelines_ensure(int spatial, const struct fx_settings *s) {
VkShaderModule vert = VK_NULL_HANDLE;
#define MKL(needed, slot, code, name, render_pass, layout) do { \
if ((needed) && !g_pipe[slot]) { \
if (!vert && !(vert = shader(upscale_vert_code, sizeof(upscale_vert_code)))) goto fail; \
g_pipe[slot] = post_pipeline_for_renderpass(vert, code, sizeof(code), render_pass, name, layout); \
if (!g_pipe[slot]) goto fail; \
} \
} while (0)
#define MK(needed, slot, code, name) MKL(needed, slot, code, name, g_rp, g_pl)
if (spatial == 3) {
if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code, "sgsr_half");
else MK(1, P_SGSR, sgsr_code, "sgsr");
}
if (spatial == 8) {
if (g_upscale_half) MK(1, P_SGSR_HQ, sgsr_quality_half_code, "sgsr_quality_half");
else MK(1, P_SGSR_HQ, sgsr_quality_code, "sgsr_quality");
}
if (spatial == 4 || spatial == 5) {
if (g_upscale_half) MK(1, P_EASU, fsr_easu_half_code, "fsr_easu_half");
else MK(1, P_EASU, fsr_easu_code, "fsr_easu");
if (s->sharp_pct != 0) {
if (g_upscale_half) MK(1, P_RCAS, fsr_rcas_half_code, "fsr_rcas_half");
else MK(1, P_RCAS, fsr_rcas_code, "fsr_rcas");
}
}
if (spatial == 6) {
if (g_upscale_half) MK(1, P_RCAS, fsr_rcas_half_code, "fsr_rcas_half");
else MK(1, P_RCAS, fsr_rcas_code, "fsr_rcas");
}
if (spatial == 7) {
if (g_upscale_half && !g_nis_attempted) {
g_nis_attempted = 1;
if (!fx_alpha_holds_luma(g_fx_fmt))
droiddeck_log("effects", "NIS uses nis.frag: the chain format has no 8-bit alpha for the luma prepass");
else if (coef_create() != 0)
droiddeck_log("effects", "NIS coefficient buffer unavailable; NIS uses nis.frag");
else {
if (!vert && !(vert = shader(upscale_vert_code, sizeof(upscale_vert_code)))) goto fail;
g_pipe[P_NIS] = post_pipeline_for_renderpass(vert, nis3_half_code, sizeof(nis3_half_code), g_rp, "nis3_half", g_pl_nis);
if (g_pipe[P_NIS])
g_pipe[P_NIS_LUMA] = post_pipeline_for_renderpass(vert, nis_luma_half_code, sizeof(nis_luma_half_code), g_rp, "nis_luma_half", g_pl);
if (g_pipe[P_NIS] && g_pipe[P_NIS_LUMA]) g_nis_fast = 1;
else {
if (g_pipe[P_NIS]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS], NULL);
if (g_pipe[P_NIS_LUMA]) g_vk.DestroyPipeline(g_dev, g_pipe[P_NIS_LUMA], NULL);
g_pipe[P_NIS] = VK_NULL_HANDLE;
g_pipe[P_NIS_LUMA] = VK_NULL_HANDLE;
coef_destroy();
droiddeck_log("effects", "fast NIS pipelines failed to build; NIS uses nis.frag");
}
}
}
if (!g_nis_fast) MK(1, P_NIS, nis_code, "nis");
else if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code, "sgsr_half");
}
if (cas_active(s)) {
if (g_upscale_half) MK(1, P_CAS, cas_ffx_half_code, "cas_ffx_half");
else MK(1, P_CAS, cas_code, "cas");
}
if (s->color_on && !(s->toon && g_fx_fmt == FX_FORMAT)) MK(1, P_COLOR, color_code, "color");
if (s->aa_mode == 1 || s->aa_mode == 2) MK(1, P_FXAA, fxaa_code, "fxaa");
if (s->aa_mode == 2) {
MKL(1, P_SMAA_EDGE, smaa_edge_code, "smaa_edge", g_smaa_rp, g_pl);
MKL(1, P_SMAA_WEIGHTS, smaa_weights_code, "smaa_weights", g_smaa_rp, g_pl);
MK(1, P_SMAA_BLEND, smaa_blend_code, "smaa_blend");
}
if (s->toon && s->color_on && g_fx_fmt == FX_FORMAT) MK(1, P_TOON_COLOR, toon_color_code, "toon_color");
else if (s->toon) MK(1, P_TOON, toon_code, "toon");
if (s->hdr_on) MK(1, P_HDR, hdr_code, "hdr");
if (s->ntsc) MK(1, P_NTSC, ntsc_code, "ntsc");
if (s->crt) MK(1, P_CRT, crt_code, "crt");
if (deband_active(s)) MK(1, P_DEBAND, deband_code, "deband");
#undef MK
#undef MKL
if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL);
return 0;
fail:
if (vert) g_vk.DestroyShaderModule(g_dev, vert, NULL);
return chain_failed();
}
static void barrier(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to,
VkPipelineStageFlags src_stage, VkAccessFlags src_access,
@@ -681,14 +741,26 @@ static void pass_dual(VkCommandBuffer cmd, VkPipeline p, struct fx_target *dst,
static const float FULL_NDC[4] = {-1.0f, -1.0f, 1.0f, 1.0f};
#define SET_NDC(pc) memcpy((pc).ndc, FULL_NDC, sizeof(FULL_NDC))
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
int out_w, int out_h, int *res_w, int *res_h) {
struct fx_source_state {
VkImageLayout layout;
VkPipelineStageFlags stage;
VkAccessFlags access;
};
static VkImage effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
int out_w, int out_h, int *res_w, int *res_h,
VkImageLayout input_layout, const struct fx_settings *frozen,
struct fx_source_state *source_state) {
struct fx_settings snapshot;
const struct fx_settings *s;
vkp_effects_sync();
pthread_mutex_lock(&g_lock);
snapshot = g_cur;
pthread_mutex_unlock(&g_lock);
if (frozen) {
snapshot = *frozen;
} else {
vkp_effects_sync();
pthread_mutex_lock(&g_lock);
snapshot = g_cur;
pthread_mutex_unlock(&g_lock);
}
s = &snapshot;
*res_w = scene_w; *res_h = scene_h;
@@ -723,7 +795,7 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
effect_count(s) - (fuse_toon_color ? 1 : 0) -
(fuse_fxaa_toon ? 1 : 0);
if ((spatial || nfx) && objects_ensure() == 0 && scene_ensure(scene, scene_w, scene_h) == 0 &&
if ((spatial || nfx) && objects_ensure() == 0 && pipelines_ensure(spatial, s) == 0 && scene_ensure(scene, scene_w, scene_h) == 0 &&
target_ensure(&g_t[0], cw, ch, FX_TARGET_USAGE, "chain") == 0 && (chain_passes < 2 || target_ensure(&g_t[1], cw, ch, FX_TARGET_USAGE, "chain") == 0) &&
(!(spatial == 4 || spatial == 5) || s->sharp_pct == 0 ||
target_ensure(&g_mid, cw, ch, FX_SCRATCH_USAGE, "EASU") == 0)) {
@@ -748,8 +820,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
g_vk.CmdSetScissor(cmd, 0, 1, &chain_sc);
if (spatial) {
barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT};
barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT);
struct fx_target *dst = FREE_TARGET();
if (spatial == 3 || spatial == 8 || spatial == 7) {
@@ -809,8 +883,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
cur = dst; cur_ds = dst->ds;
} else if (resize) {
struct fx_target *dst = FREE_TARGET();
barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT};
barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
barrier(cmd, dst->img, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT);
@@ -823,8 +899,10 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT);
cur = dst; cur_ds = dst->ds;
} else {
barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT};
barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_READ_BIT);
cur = NULL; cur_ds = g_scene.ds;
}
@@ -907,8 +985,54 @@ VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int sce
return scene;
}
barrier(cmd, scene, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT,
if (source_state) *source_state = (struct fx_source_state){VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT};
barrier(cmd, scene, input_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
return scene;
}
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
int out_w, int out_h, int *res_w, int *res_h) {
return effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, NULL, NULL);
}
int vkp_effects_prepare_generated(void) {
vkp_effects_sync();
pthread_mutex_lock(&g_lock);
g_generated_settings = g_cur;
pthread_mutex_unlock(&g_lock);
return spatial_mode(g_generated_settings.scaling) && g_generated_settings.scaling != 6 &&
effect_count(&g_generated_settings) == 0;
}
VkImage vkp_effects_run_before_generated(VkCommandBuffer cmd, VkImage scene, int w, int h,
int *res_w, int *res_h) {
struct fx_settings settings = g_generated_settings;
settings.scaling = 0;
return effects_run(cmd, scene, w, h, w, h, res_w, res_h,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &settings, NULL);
}
VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
int out_w, int out_h, int slot, int *res_w, int *res_h) {
if (slot < 0 || slot > VKP_FG_MAX_GENERATIONS) {
*res_w = scene_w; *res_h = scene_h;
return scene;
}
g_context = slot + 1;
struct fx_source_state source_state = {0};
VkImage result = effects_run(cmd, scene, scene_w, scene_h, out_w, out_h, res_w, res_h,
VK_IMAGE_LAYOUT_GENERAL, &g_generated_settings, &source_state);
barrier(cmd, result, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_READ_BIT);
if (result != scene)
barrier(cmd, scene, source_state.layout, VK_IMAGE_LAYOUT_GENERAL,
source_state.stage, source_state.access,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_MEMORY_READ_BIT | VK_ACCESS_MEMORY_WRITE_BIT);
g_context = 0;
return result;
}
@@ -18,6 +18,12 @@ VkFilter vkp_effects_blit_filter(void);
VkImage vkp_effects_run(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
int out_w, int out_h, int *res_w, int *res_h);
int vkp_effects_prepare_generated(void);
void vkp_effects_release_generated_sources(void);
VkImage vkp_effects_run_before_generated(VkCommandBuffer cmd, VkImage scene, int w, int h,
int *res_w, int *res_h);
VkImage vkp_effects_run_generated(VkCommandBuffer cmd, VkImage scene, int scene_w, int scene_h,
int out_w, int out_h, int slot, int *res_w, int *res_h);
void vkp_effects_destroy(void);
@@ -1,6 +1,7 @@
#define _POSIX_C_SOURCE 200809L
#include "framegen_bridge.h"
#include "framegen_engine.h"
#include "effects_chain.h"
#include "vk_loader.h"
#include <pthread.h>
#include <stdatomic.h>
@@ -226,7 +227,10 @@ static void destroy_ring(void) {
if (vk.DeviceWaitIdle) vk.DeviceWaitIdle(g_dev);
for (uint32_t i = 0; i < g_ring_n; i++) {
if (g_ring[i].view) vk.DestroyImageView(g_dev, g_ring[i].view, NULL);
if (g_ring[i].img) vk.DestroyImage(g_dev, g_ring[i].img, NULL);
if (g_ring[i].img) {
vkp_effects_forget_image(g_ring[i].img);
vk.DestroyImage(g_dev, g_ring[i].img, NULL);
}
if (g_ring[i].mem) vk.FreeMemory(g_dev, g_ring[i].mem, NULL);
memset(&g_ring[i], 0, sizeof(g_ring[i]));
}
@@ -31,6 +31,7 @@ bool g_probed = false, g_ready = false;
std::unique_ptr<lsfg::Engine> g_lsfg;
std::unique_ptr<ddfg::Engine> g_ddfg;
std::vector<std::unique_ptr<ddfg::Engine>> g_retained_ddfg;
int g_kind = -1;
char g_build[96] = "";
@@ -128,7 +129,14 @@ void fge_device_ready(PFN_vkGetInstanceProcAddr gipa, VkInstance inst, VkPhysica
void fge_device_lost(void) {
g_lsfg.reset();
g_ddfg.reset();
if (g_ddfg) {
if (g_ddfg->destroy()) g_ddfg.reset();
else g_retained_ddfg.push_back(std::move(g_ddfg));
}
// The device is being torn down. Unknown-completion resources must not be
// passed to Vulkan destruction calls; the VkDevice teardown reclaims them.
for (auto& engine : g_retained_ddfg) engine->abandon();
g_retained_ddfg.clear();
g_kind = -1;
g_dev = VK_NULL_HANDLE;
g_queue = VK_NULL_HANDLE;
@@ -193,9 +201,21 @@ int fge_start(int kind, const char *cache_path) {
}
void fge_stop(void) {
if ((g_lsfg || g_ddfg) && g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev);
g_lsfg.reset();
g_ddfg.reset();
if (g_lsfg) {
if (g_table.DeviceWaitIdle && g_dev) g_table.DeviceWaitIdle(g_dev);
g_lsfg.reset();
}
for (auto it = g_retained_ddfg.begin(); it != g_retained_ddfg.end();) {
if ((*it)->destroy()) it = g_retained_ddfg.erase(it);
else ++it;
}
if (g_ddfg) {
if (g_ddfg->destroy()) g_ddfg.reset();
else {
ELOGE("ddfg-native: retaining engine until GPU completion is known or device teardown");
g_retained_ddfg.push_back(std::move(g_ddfg));
}
}
g_kind = -1;
}
+32 -3
View File
@@ -2759,6 +2759,21 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
pass_n = 1;
overlay_start = source_end;
}
const int upscale_w = (int)(scene_w * g_map.kx + 0.5f);
const int upscale_h = (int)(scene_h * g_map.ky + 0.5f);
const int post_upscale = fx && fg && !hf && !cb && vkp_effects_upscaling() &&
vkp_effects_prepare_generated() &&
(upscale_w > input_w || upscale_h > input_h);
if (post_upscale) {
static int last_input_w, last_input_h, last_output_w, last_output_h;
if (input_w != last_input_w || input_h != last_input_h ||
upscale_w != last_output_w || upscale_h != last_output_h) {
droiddeck_log("framegen", "post-upscale: interpolate %dx%d, spatial filter each present to %dx%d",
input_w, input_h, upscale_w, upscale_h);
last_input_w = input_w; last_input_h = input_h;
last_output_w = upscale_w; last_output_h = upscale_h;
}
}
const int deep = hf && n > 0 && fg && g_swap_is_hdr && !hf->tonemap && vkp_framegen_format_ok(FG_HDR_FMT) &&
ensure_img(&g_fgscene, scene_w, scene_h, FG_HDR_FMT,
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |
@@ -2894,8 +2909,11 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (fx) {
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
if (fg && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; }
if (post_upscale) { mapped_w = input_w; mapped_h = input_h; }
vkp_effects_set_formats(scene_fmt, scene_fmt, hdr_how == 1 || hdr_unconverted);
result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
result = post_upscale
? vkp_effects_run_before_generated(cmd, scene_img, input_w, input_h, &rw, &rh)
: vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh);
effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h,
draws ? draws + overlay_start : NULL, n - overlay_start);
release_external_client_draws(cmd, draws, n);
@@ -2918,7 +2936,12 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
if (ngen > VKP_FG_MAX_GENERATIONS) ngen = VKP_FG_MAX_GENERATIONS;
}
record_screen_blit(cmd, ngen ? gens[0] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb);
VkImage screen = ngen ? gens[0] : result;
int screen_w = rw, screen_h = rh;
if (post_upscale)
screen = vkp_effects_run_generated(cmd, screen, rw, rh, upscale_w, upscale_h,
0, &screen_w, &screen_h);
record_screen_blit(cmd, screen, screen_w, screen_h, scene_w, scene_h, img, blit_filter, cb);
}
g_vk.EndCommandBuffer(cmd);
@@ -2942,7 +2965,12 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkCommandBuffer ck = g_cmds[k];
g_vk.ResetCommandBuffer(ck, 0);
g_vk.BeginCommandBuffer(ck, &bi);
record_screen_blit(ck, k < ngen ? gens[k] : result, rw, rh, scene_w, scene_h, img, blit_filter, cb);
VkImage screen = k < ngen ? gens[k] : result;
int screen_w = rw, screen_h = rh;
if (post_upscale)
screen = vkp_effects_run_generated(ck, screen, rw, rh, upscale_w, upscale_h,
k, &screen_w, &screen_h);
record_screen_blit(ck, screen, screen_w, screen_h, scene_w, scene_h, img, blit_filter, cb);
g_vk.EndCommandBuffer(ck);
}
const int last = (k + 1 == presents);
@@ -2988,6 +3016,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
VkResult fr = timed_wait(g_fence, UINT64_MAX);
if (fr == VK_ERROR_DEVICE_LOST || pr == VK_ERROR_DEVICE_LOST) { device_lost("present"); return -1; }
if (fr != VK_SUCCESS) return -1;
vkp_effects_release_generated_sources();
if (fg) vkp_framegen_presented(presented_gen);
if (pr == VK_ERROR_OUT_OF_DATE_KHR || pr == VK_ERROR_SURFACE_LOST_KHR) {
droiddeck_log("gpu", "screen surface %s on present: rebuilding the swapchain", vk_result_name(pr));
@@ -2264,7 +2264,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
!com.droiddeck.launcher.input.PadBridge.isControllerMotionEvent(event)) return
val device = event.device ?: return
val rxRy = com.droiddeck.launcher.input.PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts)
?: return
?: run {
if (rightStickScrollDeviceId == event.deviceId) stopRightStickScroll()
return
}
val axis = if (rxRy) android.view.MotionEvent.AXIS_RY else android.view.MotionEvent.AXIS_RZ
val value = event.getAxisValue(axis)
if (kotlin.math.abs(value) < 0.55f) {
@@ -8,8 +8,11 @@ import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.WirelessAdbFix
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.QuestExperimental
import java.io.File
import java.util.concurrent.TimeUnit
@@ -88,6 +91,8 @@ object AgentSetup {
private fun completedKey(harness: AgentHarness) = "setup_completed_${harness.id}"
private val main = Handler(Looper.getMainLooper())
/** Advanced by every Allow, so a connection check started before it cannot overwrite what it found. */
private var connectionGeneration = 0
private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git"
private const val CHECKOUT = "/root/DroidDeck"
private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl", "droiddeck-scenario")
@@ -104,6 +109,7 @@ object AgentSetup {
val harness = AgentHost.harness
keys = harness.keys(LinuxRuntime.rootDir(app))
val probes = mutableListOf<Pair<Step, List<String>>>()
val generation = connectionGeneration
for (step in Step.entries) if (status[step] != Status.WORKING) {
when (step) {
Step.INSTALL -> set(step, if (harness.files.all { AgentHost.guestFileExists(app, it) }) Status.DONE else Status.TODO)
@@ -114,7 +120,9 @@ object AgentSetup {
detail.remove(step)
Thread({
val live = com.droiddeck.launcher.core.WirelessAdbFix.liveConnectAddress(app) != null
set(step, if (live) Status.DONE else Status.TODO)
main.post {
if (generation == connectionGeneration && status[step] != Status.WORKING) status[step] = if (live) Status.DONE else Status.TODO
}
}, "agent-connection").start()
} else probes += step to listOf("sh", "-c",
"for i in 1 2 3; do adb connect \"\$ADB_SERIAL\" >/dev/null 2>&1; " +
@@ -123,7 +131,7 @@ object AgentSetup {
Step.GITHUB -> probes += step to listOf("gh", "auth", "status")
}
}
Thread({ for ((step, command) in probes) probe(app, harness, step, command) }, "agent-checks").start()
Thread({ for ((step, command) in probes) probe(app, harness, step, command, generation) }, "agent-checks").start()
}
/** The last failed refresh ends the script: the installs after it would run from stale indexes and could report success. */
@@ -141,6 +149,22 @@ object AgentSetup {
/** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */
fun run(context: Context, step: Step) = run(context, step, null)
/** The [Step.CONNECTION] action on a Quest, which has no pairing screen; see [WirelessAdbFix.trustOnDevice]. */
fun trustOnDevice(context: Context) {
val app = context.applicationContext
connectionGeneration++
status[Step.CONNECTION] = Status.WORKING
detail[Step.CONNECTION] = app.getString(R.string.agent_connection_quest_waiting)
Thread({
val ok = runCatching { WirelessAdbFix.trustOnDevice(app) }.isSuccess
main.post {
status[Step.CONNECTION] = if (ok) Status.DONE else Status.FAILED
if (ok) detail.remove(Step.CONNECTION) else detail[Step.CONNECTION] = app.getString(R.string.agent_connection_quest_failed)
if (ok) check(app)
}
}, "agent-quest-trust").start()
}
/** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */
fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page))
@@ -216,7 +240,7 @@ object AgentSetup {
detail.clear()
}
private fun probe(app: Context, harness: AgentHarness, step: Step, command: List<String>) {
private fun probe(app: Context, harness: AgentHarness, step: Step, command: List<String>, generation: Int) {
var output = ""
val ok = runCatching {
val child = AgentHost.guest(app, command, connectAdb = step == Step.CONNECTION).start()
@@ -232,11 +256,14 @@ object AgentSetup {
}.onFailure { output = it.message.orEmpty() }.getOrDefault(false)
main.post {
if (AgentHost.harness != harness) return@post
// A running or newer Allow owns the row, including the instructions it shows while it waits.
if (step == Step.CONNECTION && (generation != connectionGeneration || status[step] == Status.WORKING)) return@post
if (status[step] != Status.WORKING) status[step] = if (ok) Status.DONE else Status.TODO
val last = output.lines().lastOrNull { it.isNotBlank() && !noise(it.trim()) }?.trim()?.take(160)
when {
ok -> detail.remove(step)
step == Step.CONNECTION -> detail[step] = app.getString(com.droiddeck.launcher.R.string.agent_connection_off)
step == Step.CONNECTION -> detail[step] = app.getString(
if (QuestExperimental.isSupported()) R.string.agent_connection_quest_off else R.string.agent_connection_off)
step.required && last != null -> detail[step] = last
}
if (ready) AgentHost.prefs(app).edit().putBoolean(completedKey(harness), true).apply()
@@ -1,6 +1,7 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
@@ -19,4 +20,14 @@ object GlobalSettings {
fun developerOptionsOn(context: Context): Boolean = isOn(context, Settings.Global.DEVELOPMENT_SETTINGS_ENABLED)
fun wirelessDebuggingOn(context: Context): Boolean = isOn(context, "adb_wifi_enabled")
/**
* True when it was off and is now on. Quest only, where Settings has no switch for it; it needs
* WRITE_SECURE_SETTINGS granted over adb.
*/
fun turnOnWirelessDebugging(context: Context): Boolean {
if (!com.droiddeck.launcher.session.QuestExperimental.isSupported() || wirelessDebuggingOn(context)) return false
if (context.checkSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS) != PackageManager.PERMISSION_GRANTED) return false
return runCatching { Settings.Global.putInt(context.contentResolver, "adb_wifi_enabled", 1) }.getOrDefault(false)
}
}
@@ -22,6 +22,9 @@ object WirelessAdbFix {
private const val HOST_FILE = "wireless-adb-host.txt"
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
const val LOOPBACK = "127.0.0.1"
private const val TCP_PORT = 5555
private const val WIRELESS_START_MS = 2_000L
private const val NETWORK_PROMPT_MS = 30_000L
private data class SavedConnection(val host: String, val port: Int?)
@@ -55,6 +58,23 @@ object WirelessAdbFix {
writeAtomically(context, File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
}
/**
* Quest has no pairing screen. adbd in TCP mode (`adb tcpip 5555`) asks "Allow debugging?" for an
* unknown key, and Wireless debugging accepts a key allowed there, so this stands in for pairing.
* Blocks until the prompt is answered or times out.
*/
fun trustOnDevice(context: Context) {
val app = context.applicationContext
// Already trusted, as after a reboot: Wireless debugging takes the key, and port 5555 is closed by then.
val live = if (savedConnection(app) != null) liveConnectAddress(app) else null
if (live != null && acceptsKey(app, live.substringBeforeLast(':').trim('[', ']'), live.substringAfterLast(':').toInt())) return
GlobalSettings.turnOnWirelessDebugging(app)
loadOrCreateIdentity(app)
Kadb.create(LOOPBACK, TCP_PORT, 2_000, 120_000).use { check(it.shell("true").exitCode == 0) }
writeAtomically(app, File(app.noBackupFilesDir, HOST_FILE), LOOPBACK.toByteArray())
writeAtomically(app, File(app.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
}
private fun savedConnection(context: Context): SavedConnection? {
val directory = context.applicationContext.noBackupFilesDir
if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null
@@ -78,10 +98,17 @@ object WirelessAdbFix {
fun liveConnectAddress(context: Context): String? {
val app = context.applicationContext
val saved = savedConnection(app) ?: return null
val turnedOn = GlobalSettings.turnOnWirelessDebugging(app)
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
saved.port?.takeIf { answers(saved.host, it) }?.let { return "$host:$it" }
if (!turnedOn) saved.port?.takeIf { answers(saved.host, it) }?.let { return "$host:$it" }
val loopback = runCatching { InetAddress.getByName(saved.host).isLoopbackAddress }.getOrDefault(false)
val port = if (loopback) loopbackAdbPort(app) else findConnectPort(app, saved.host, accept = { answers(saved.host, it) })
// Turning it on can first ask "Allow wireless debugging on this network?", so keep looking while that is answered.
val deadline = android.os.SystemClock.elapsedRealtime() + if (turnedOn) NETWORK_PROMPT_MS else 0L
var port: Int?
do {
if (turnedOn) Thread.sleep(WIRELESS_START_MS)
port = if (loopback) loopbackAdbPort(app) else findConnectPort(app, saved.host, accept = { answers(saved.host, it) })
} while (port == null && android.os.SystemClock.elapsedRealtime() < deadline)
port ?: return null
saveConnection(app, saved.host, port)
return "$host:$port"
@@ -105,10 +132,12 @@ object WirelessAdbFix {
}
}.apply { start() }
}.forEach { it.join() }
return open.sorted().firstOrNull { port -> acceptsKey(app, LOOPBACK, port) }
}
private fun acceptsKey(app: Context, host: String, port: Int): Boolean {
loadOrCreateIdentity(app)
return open.sorted().firstOrNull { port ->
runCatching { Kadb.create(LOOPBACK, port, 1_000, 3_000).use { it.shell("true").exitCode == 0 } }.getOrDefault(false)
}
return runCatching { Kadb.create(host, port, 1_000, 3_000).use { it.shell("true").exitCode == 0 } }.getOrDefault(false)
}
private val EPHEMERAL_PORTS = 32768..60999
@@ -59,13 +59,18 @@ object GameStorage {
return when {
pref == SessionPrefs.GAME_STORAGE_OFF -> null
pref.isEmpty() -> options(context).firstOrNull()?.let { Option(it.name, it.path) }
else -> Option(SessionPrefs.gameStorageLabel(context), pref).takeIf { attached(File(pref)) }
else -> reachable(pref).let { path -> Option(SessionPrefs.gameStorageLabel(context), path).takeIf { attached(File(path)) } }
}
}
fun disconnected(context: Context): Boolean {
val pref = SessionPrefs.gameStorage(context)
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(pref))
return pref.isNotEmpty() && pref != SessionPrefs.GAME_STORAGE_OFF && !attached(File(reachable(pref)))
}
internal fun reachable(path: String, usable: (File) -> Boolean = { it.isDirectory && it.canWrite() }): String {
val alias = UsbLink.storagePath(path)
return if (alias != path && !usable(File(path)) && usable(File(alias))) alias else path
}
internal fun attached(
@@ -46,7 +46,16 @@ object SecondaryLibrary {
}
fun privateRoot(files: File, library: File): File {
val digest = MessageDigest.getInstance("SHA-256").digest(library.canonicalPath.toByteArray())
val own = privateDir(files, library.canonicalPath)
if (own.exists()) return own
val raw = UsbLink.rawPath(library.absolutePath)
val alias = if (raw != library.absolutePath) raw else UsbLink.storagePath(library.absolutePath)
if (alias == library.absolutePath) return own
return privateDir(files, runCatching { File(alias).canonicalPath }.getOrDefault(alias)).takeIf { it.exists() } ?: own
}
private fun privateDir(files: File, path: String): File {
val digest = MessageDigest.getInstance("SHA-256").digest(path.toByteArray())
.joinToString("") { "%02x".format(it.toInt() and 255) }
return File(files, "steam-libraries/$digest")
}
@@ -7,6 +7,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
@@ -130,13 +131,13 @@ object BattleNetClient {
StoresState.post { opener?.invoke(args) }
}
fun library(context: Context, root: File = preferred(context)): List<String> =
AddedGames.guestPath(context, StoreInstallRoot.storeDir(root, Store.BATTLENET))?.let { listOf("--library", it) }.orEmpty()
fun library(context: Context, root: File? = preferred(context)): List<String> =
root?.let { AddedGames.guestPath(context, StoreInstallRoot.storeDir(it, Store.BATTLENET)) }?.let { listOf("--library", it) }.orEmpty()
internal fun preferred(context: Context): File {
internal fun preferred(context: Context): File? {
val second = StoreInstallRoot.libraryRoot(context)?.absolutePath
return StoreInstallRoot.targets(context).firstOrNull { it.root.absolutePath == second && (it.root.isDirectory || it.root.mkdirs()) }?.root
?: StoreInstallRoot.internalRoot(context)
?: StoreInstallRoot.internalRoot(context).takeIf { second == null && !GameStorage.disconnected(context) }
}
fun installGame(context: Context, uid: String, root: File) {
@@ -46,6 +46,7 @@ import androidx.compose.ui.platform.testTag
import com.droiddeck.launcher.agent.AgentSetup.Status
import com.droiddeck.launcher.agent.AgentSetup.Step
import com.droiddeck.launcher.core.WirelessAdbPairingService
import com.droiddeck.launcher.session.QuestExperimental
@Composable
internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifier, onDone: () -> Unit = {}) {
@@ -104,11 +105,16 @@ internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifie
var keyOpen by rememberSaveable(harness.id) { mutableStateOf(false) }
val (title, hint) = labels(step, harness.name, keyed)
val lab = AgentHost.lab?.takeIf { it.prepare && it.running }
val questConnection = step == Step.CONNECTION && status != Status.DONE && QuestExperimental.isSupported()
val detail = when {
step == Step.PREPARE && lab != null ->
stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0)))
keyed && status == Status.DONE && AgentSetup.detail[step] == null ->
harness.providers.filter { it.id in AgentSetup.keys }.joinToString(" · ") { it.name }.ifEmpty { stringResource(R.string.agent_step_free_models) }
// The Quest hint holds the one-time commands, so it stays under the status until the step passes.
questConnection -> AgentSetup.detail[step]?.let { "$it\n$hint" } ?: hint
// The Quest hint is setup instructions; once connected, the row says what it is for.
step == Step.CONNECTION && QuestExperimental.isSupported() -> AgentSetup.detail[step] ?: stringResource(R.string.agent_step_connection_hint)
else -> AgentSetup.detail[step] ?: hint
}
// Shown while the sign-in is pending, so it is still there after a trip to the browser for the key.
@@ -121,6 +127,7 @@ internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifie
Status.TODO, Status.FAILED -> CheckState.WARN
},
title, detail, divider = index < steps.lastIndex && !showKey,
detailLines = if (questConnection) Int.MAX_VALUE else 2,
) {
val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) ||
(step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE)
@@ -258,7 +265,9 @@ internal fun agentStorageWarning(item: AgentStorage.Item) = when (item) {
@Composable
private fun labels(step: Step, harness: String, keyed: Boolean = false): Pair<String, String> = when (step) {
Step.CONNECTION -> stringResource(R.string.agent_step_connection) to stringResource(R.string.agent_step_connection_hint)
Step.CONNECTION -> stringResource(R.string.agent_step_connection) to
if (QuestExperimental.isSupported()) stringResource(R.string.agent_step_connection_quest_hint, LocalContext.current.packageName)
else stringResource(R.string.agent_step_connection_hint)
Step.INSTALL -> stringResource(R.string.agent_step_install, harness) to stringResource(R.string.agent_step_install_hint)
Step.SIGN_IN -> stringResource(R.string.agent_step_sign_in, harness) to stringResource(if (keyed) R.string.agent_step_sign_in_key_hint else R.string.agent_step_sign_in_hint)
Step.GITHUB -> stringResource(R.string.agent_step_github) to stringResource(R.string.agent_step_github_hint)
@@ -267,7 +276,7 @@ private fun labels(step: Step, harness: String, keyed: Boolean = false): Pair<St
}
private fun action(step: Step): Int = when (step) {
Step.CONNECTION -> R.string.agent_action_pair
Step.CONNECTION -> if (QuestExperimental.isSupported()) R.string.agent_action_allow else R.string.agent_action_pair
Step.INSTALL -> R.string.agent_action_install
Step.SIGN_IN, Step.GITHUB -> R.string.agent_action_sign_in
Step.BUILD_TOOLS -> R.string.agent_action_install
@@ -276,6 +285,7 @@ private fun action(step: Step): Int = when (step) {
/** The pairing DroidDeck already uses for the phantom process fix; the agent reuses its key. */
private fun pair(context: android.content.Context) {
if (QuestExperimental.isSupported()) return AgentSetup.trustOnDevice(context)
if (!WirelessAdbPairingService.notificationsEnabled(context)) {
context.startActivity(android.content.Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, context.packageName)
@@ -103,7 +103,7 @@ internal object SetupTabs {
}
@Composable
internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) {
internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, detailLines: Int = 2, action: (@Composable () -> Unit)? = null) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val tint = when (state) {
@@ -135,7 +135,7 @@ internal fun CheckRow(state: CheckState, title: String, detail: String?, divider
}
Column(modifier = Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
if (detail != null) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = detailLines, overflow = TextOverflow.Ellipsis)
}
if (action != null) action()
}
@@ -174,14 +174,15 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
detail = if (library.usersOfBindings(b.id).size > 1) stringResource(R.string.input_shared_detail, b.name, library.usersOfBindings(b.id).size)
else "${profile.name} · ${roleLabel(role)}", onSave = { action ->
if (update { l ->
val currentPreset = l.preset(editing.preset)
val geometry = if (!editing.click && elementProperties != null && layout != null) l.withLayout(layout.copy(elements = layout.elements.map {
if (it.id == elementProperties!!.id) elementProperties!!.copy(name = elementProperties!!.name.trim().ifBlank { it.name }) else it
})) else l
geometry.withPreset(when {
editing.element != null && editing.click -> b.copy(clicks = b.clicks + (editing.element.id to action))
editing.element != null -> b.copy(elements = b.elements + (editing.element.id to action))
editing.key != null -> b.copy(keys = b.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action))
else -> b.copy(controls = b.controls + (editing.control to action))
editing.element != null && editing.click -> currentPreset.copy(clicks = currentPreset.clicks + (editing.element.id to action))
editing.element != null -> currentPreset.copy(elements = currentPreset.elements + (editing.element.id to action))
editing.key != null -> currentPreset.copy(keys = currentPreset.keys.filterNot { it.key == editing.key } + PhysicalInputBinding(editing.key, action))
else -> currentPreset.copy(controls = currentPreset.controls + (editing.control to action))
}) }) edit = null
})
} else if (!surface) key(page, profileId, role) {
+5
View File
@@ -1265,6 +1265,11 @@
<string name="agent_action_prepare">تحضير</string>
<string name="agent_connection_off">تعذّر الوصول إلى تصحيح الأخطاء اللاسلكي؛ زر الاقتران يشغّله</string>
<string name="agent_action_pair">اقتران</string>
<string name="agent_step_connection_quest_hint">لا يحتوي Quest على شاشة اقتران. من حاسوب، شغّل مرة واحدة: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS و adb tcpip 5555. ثم اضغط «السماح» واقبل الطلب في النظارة</string>
<string name="agent_action_allow">السماح</string>
<string name="agent_connection_quest_waiting">اقبل «السماح بتصحيح الأخطاء؟» في النظارة مع تحديد «السماح دائمًا»</string>
<string name="agent_connection_quest_failed">تعذّر الاتصال. اقبل طلب تصحيح الأخطاء في النظارة، وإن لم يظهر، شغّل adb tcpip 5555 من حاسوب ثم حاول مجددًا</string>
<string name="agent_connection_quest_off">تعذّر الوصول إلى تصحيح الأخطاء اللاسلكي. اضغط «السماح» لإعداده من جديد</string>
<string name="agent_action_install">تثبيت</string>
<string name="agent_action_sign_in">تسجيل الدخول</string>
<string name="upd_pr">PR #%1$d</string>
@@ -1280,6 +1280,11 @@
<string name="agent_action_prepare">Preparar</string>
<string name="agent_connection_off">No se puede acceder a la depuración inalámbrica; Vincular la activa</string>
<string name="agent_action_pair">Vincular</string>
<string name="agent_step_connection_quest_hint">Quest no tiene pantalla de vinculación. Desde una computadora, ejecuta una vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS y adb tcpip 5555. Luego toca Permitir y acepta el aviso en el visor</string>
<string name="agent_action_allow">Permitir</string>
<string name="agent_connection_quest_waiting">Acepta «¿Permitir depuración?» en el visor, con Permitir siempre marcado</string>
<string name="agent_connection_quest_failed">No se pudo conectar. Acepta el aviso de depuración en el visor o, si no apareció, ejecuta adb tcpip 5555 desde una computadora y vuelve a intentarlo</string>
<string name="agent_connection_quest_off">No se puede acceder a la depuración inalámbrica. Toca Permitir para configurarla de nuevo</string>
<string name="agent_action_install">Instalar</string>
<string name="agent_action_sign_in">Iniciar sesión</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Подготви</string>
<string name="agent_connection_off">Безжичното отстраняване на грешки не е достъпно; сдвояването го включва</string>
<string name="agent_action_pair">Сдвой</string>
<string name="agent_step_connection_quest_hint">Quest няма екран за сдвояване. От компютър изпълнете веднъж: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS и adb tcpip 5555. След това докоснете „Разреши“ и приемете запитването в шлема</string>
<string name="agent_action_allow">Разреши</string>
<string name="agent_connection_quest_waiting">Приемете „Разрешаване на отстраняването на грешки?“ в шлема с отметка „Винаги разрешавай“</string>
<string name="agent_connection_quest_failed">Неуспешно свързване. Приемете запитването за отстраняване на грешки в шлема, а ако не се е появило, изпълнете adb tcpip 5555 от компютър и опитайте отново</string>
<string name="agent_connection_quest_off">Безжичното отстраняване на грешки не е достъпно. Докоснете „Разреши“, за да го настроите отново</string>
<string name="agent_action_install">Инсталирай</string>
<string name="agent_action_sign_in">Влез</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1257,6 +1257,11 @@
<string name="agent_action_prepare">Připravit</string>
<string name="agent_connection_off">Bezdrátové ladění není dostupné; Spárovat ho zapne</string>
<string name="agent_action_pair">Spárovat</string>
<string name="agent_step_connection_quest_hint">Quest nemá obrazovku párování. Z počítače jednou spusťte: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS a adb tcpip 5555. Pak klepněte na Povolit a potvrďte výzvu v headsetu</string>
<string name="agent_action_allow">Povolit</string>
<string name="agent_connection_quest_waiting">V headsetu potvrďte „Povolit ladění?“ se zaškrtnutým Vždy povolit</string>
<string name="agent_connection_quest_failed">Nepodařilo se připojit. Potvrďte výzvu k ladění v headsetu, a pokud se neobjevila, spusťte z počítače adb tcpip 5555 a zkuste to znovu</string>
<string name="agent_connection_quest_off">Bezdrátové ladění není dostupné. Klepnutím na Povolit ho nastavíte znovu</string>
<string name="agent_action_install">Instalovat</string>
<string name="agent_action_sign_in">Přihlásit se</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Forbered</string>
<string name="agent_connection_off">Trådløs fejlfinding kan ikke nås; Par slår den til</string>
<string name="agent_action_pair">Par</string>
<string name="agent_step_connection_quest_hint">Quest har ingen parringsskærm. Kør én gang fra en computer: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS og adb tcpip 5555. Tryk derefter på Tillad, og godkend prompten i headsettet</string>
<string name="agent_action_allow">Tillad</string>
<string name="agent_connection_quest_waiting">Godkend “Tillad fejlretning?” i headsettet med Tillad altid markeret</string>
<string name="agent_connection_quest_failed">Kunne ikke oprette forbindelse. Godkend fejlretningsprompten i headsettet, eller kør adb tcpip 5555 fra en computer og prøv igen, hvis den ikke dukkede op</string>
<string name="agent_connection_quest_off">Trådløs fejlretning kan ikke nås. Tryk på Tillad for at konfigurere den igen</string>
<string name="agent_action_install">Installer</string>
<string name="agent_action_sign_in">Log ind</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1241,6 +1241,11 @@
<string name="agent_action_prepare">Vorbereiten</string>
<string name="agent_connection_off">Wireless-Debugging ist nicht erreichbar; Koppeln schaltet es ein</string>
<string name="agent_action_pair">Koppeln</string>
<string name="agent_step_connection_quest_hint">Quest hat keinen Kopplungsbildschirm. Führe einmal an einem Computer aus: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS und adb tcpip 5555. Tippe dann auf Zulassen und bestätige die Abfrage im Headset</string>
<string name="agent_action_allow">Zulassen</string>
<string name="agent_connection_quest_waiting">Bestätige „Debugging zulassen?“ im Headset mit aktiviertem „Immer zulassen“</string>
<string name="agent_connection_quest_failed">Verbindung fehlgeschlagen. Bestätige die Debugging-Abfrage im Headset. Falls keine erschienen ist, führe adb tcpip 5555 an einem Computer aus und versuche es erneut</string>
<string name="agent_connection_quest_off">Kabelloses Debugging ist nicht erreichbar. Tippe auf Zulassen, um es neu einzurichten</string>
<string name="agent_action_install">Installieren</string>
<string name="agent_action_sign_in">Anmelden</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Προετοιμασία</string>
<string name="agent_connection_off">Η ασύρματη αποσφαλμάτωση δεν είναι προσβάσιμη · η Σύζευξη την ενεργοποιεί</string>
<string name="agent_action_pair">Σύζευξη</string>
<string name="agent_step_connection_quest_hint">Το Quest δεν έχει οθόνη σύζευξης. Από έναν υπολογιστή, εκτελέστε μία φορά: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS και adb tcpip 5555. Μετά πατήστε «Να επιτραπεί» και αποδεχτείτε το μήνυμα στο headset</string>
<string name="agent_action_allow">Να επιτραπεί</string>
<string name="agent_connection_quest_waiting">Αποδεχτείτε το «Να επιτραπεί ο εντοπισμός σφαλμάτων;» στο headset, με επιλεγμένο το «Να επιτρέπεται πάντα»</string>
<string name="agent_connection_quest_failed">Δεν ήταν δυνατή η σύνδεση. Αποδεχτείτε το μήνυμα εντοπισμού σφαλμάτων στο headset ή, αν δεν εμφανίστηκε, εκτελέστε adb tcpip 5555 από υπολογιστή και δοκιμάστε ξανά</string>
<string name="agent_connection_quest_off">Ο ασύρματος εντοπισμός σφαλμάτων δεν είναι προσβάσιμος. Πατήστε «Να επιτραπεί» για να τον ρυθμίσετε ξανά</string>
<string name="agent_action_install">Εγκατάσταση</string>
<string name="agent_action_sign_in">Σύνδεση</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1253,6 +1253,11 @@
<string name="agent_action_prepare">Preparar</string>
<string name="agent_connection_off">No se puede acceder a la depuración inalámbrica; Emparejar la activa</string>
<string name="agent_action_pair">Emparejar</string>
<string name="agent_step_connection_quest_hint">Quest no tiene pantalla de vinculación. Desde un ordenador, ejecuta una vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS y adb tcpip 5555. Después toca Permitir y acepta el aviso en el visor</string>
<string name="agent_action_allow">Permitir</string>
<string name="agent_connection_quest_waiting">Acepta «¿Permitir depuración?» en el visor, con Permitir siempre marcado</string>
<string name="agent_connection_quest_failed">No se pudo conectar. Acepta el aviso de depuración en el visor o, si no apareció, ejecuta adb tcpip 5555 desde un ordenador y vuelve a intentarlo</string>
<string name="agent_connection_quest_off">No se puede acceder a la depuración inalámbrica. Toca Permitir para configurarla de nuevo</string>
<string name="agent_action_install">Instalar</string>
<string name="agent_action_sign_in">Iniciar sesión</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Valmistele</string>
<string name="agent_connection_off">Langaton virheenkorjaus ei ole tavoitettavissa; Parita ottaa sen käyttöön</string>
<string name="agent_action_pair">Parita</string>
<string name="agent_step_connection_quest_hint">Questissa ei ole laiteparinäkymää. Suorita kerran tietokoneelta: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS ja adb tcpip 5555. Napauta sitten Salli ja hyväksy kehote laseissa</string>
<string name="agent_action_allow">Salli</string>
<string name="agent_connection_quest_waiting">Hyväksy ”Sallitaanko virheenkorjaus?” laseissa, kun Salli aina on valittuna</string>
<string name="agent_connection_quest_failed">Yhteyttä ei saatu. Hyväksy virheenkorjauskehote laseissa, tai jos sitä ei näkynyt, suorita adb tcpip 5555 tietokoneelta ja yritä uudelleen</string>
<string name="agent_connection_quest_off">Langatonta virheenkorjausta ei tavoiteta. Määritä se uudelleen napauttamalla Salli</string>
<string name="agent_action_install">Asenna</string>
<string name="agent_action_sign_in">Kirjaudu sisään</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1252,6 +1252,11 @@
<string name="agent_action_prepare">Préparer</string>
<string name="agent_connection_off">Le débogage sans fil n\'est pas accessible ; « Associer » l\'active</string>
<string name="agent_action_pair">Associer</string>
<string name="agent_step_connection_quest_hint">Le Quest n\'a pas d\'écran d\'association. Depuis un ordinateur, exécutez une fois : adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS et adb tcpip 5555. Touchez ensuite Autoriser et acceptez la demande dans le casque</string>
<string name="agent_action_allow">Autoriser</string>
<string name="agent_connection_quest_waiting">Acceptez « Autoriser le débogage ? » dans le casque, avec Toujours autoriser coché</string>
<string name="agent_connection_quest_failed">Connexion impossible. Acceptez la demande de débogage dans le casque ou, si elle n\'est pas apparue, exécutez adb tcpip 5555 depuis un ordinateur et réessayez</string>
<string name="agent_connection_quest_off">Le débogage sans fil est injoignable. Touchez Autoriser pour le configurer à nouveau</string>
<string name="agent_action_install">Installer</string>
<string name="agent_action_sign_in">Se connecter</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">तैयार करें</string>
<string name="agent_connection_off">वायरलेस डिबगिंग से कनेक्ट नहीं हो पा रहा; पेयर करने से यह चालू हो जाता है</string>
<string name="agent_action_pair">पेयर करें</string>
<string name="agent_step_connection_quest_hint">Quest में पेयरिंग स्क्रीन नहीं है। किसी कंप्यूटर से एक बार चलाएँ: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS और adb tcpip 5555। फिर अनुमति दें पर टैप करें और हेडसेट में संकेत स्वीकार करें</string>
<string name="agent_action_allow">अनुमति दें</string>
<string name="agent_connection_quest_waiting">हेडसेट में “डीबगिंग की अनुमति दें?” स्वीकार करें, हमेशा अनुमति दें चुना हुआ रखें</string>
<string name="agent_connection_quest_failed">कनेक्ट नहीं हो सका। हेडसेट में डीबगिंग संकेत स्वीकार करें, या अगर वह नहीं दिखा, तो कंप्यूटर से adb tcpip 5555 चलाएँ और दोबारा कोशिश करें</string>
<string name="agent_connection_quest_off">वायरलेस डीबगिंग तक नहीं पहुँचा जा सकता। इसे फिर से सेट करने के लिए अनुमति दें पर टैप करें</string>
<string name="agent_action_install">इंस्टॉल करें</string>
<string name="agent_action_sign_in">साइन इन करें</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Előkészítés</string>
<string name="agent_connection_off">A vezeték nélküli hibakeresés nem érhető el; a Párosítás bekapcsolja</string>
<string name="agent_action_pair">Párosítás</string>
<string name="agent_step_connection_quest_hint">A Quest nem rendelkezik párosítási képernyővel. Egy számítógépről futtasd egyszer: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS és adb tcpip 5555. Ezután koppints az Engedélyezés gombra, és fogadd el a kérdést a headsetben</string>
<string name="agent_action_allow">Engedélyezés</string>
<string name="agent_connection_quest_waiting">Fogadd el az „Engedélyezed a hibakeresést?” kérdést a headsetben, a Mindig engedélyez bejelölésével</string>
<string name="agent_connection_quest_failed">Nem sikerült csatlakozni. Fogadd el a hibakeresési kérdést a headsetben, vagy ha nem jelent meg, futtasd az adb tcpip 5555 parancsot egy számítógépről, és próbáld újra</string>
<string name="agent_connection_quest_off">A vezeték nélküli hibakeresés nem érhető el. Koppints az Engedélyezés gombra az újbóli beállításhoz</string>
<string name="agent_action_install">Telepítés</string>
<string name="agent_action_sign_in">Bejelentkezés</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1246,6 +1246,11 @@
<string name="agent_action_prepare">Siapkan</string>
<string name="agent_connection_off">Debug nirkabel tidak dapat dijangkau; Pasangkan menyalakannya</string>
<string name="agent_action_pair">Pasangkan</string>
<string name="agent_step_connection_quest_hint">Quest tidak memiliki layar penyambungan. Dari komputer, jalankan sekali: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS dan adb tcpip 5555. Lalu ketuk Izinkan dan terima permintaan di headset</string>
<string name="agent_action_allow">Izinkan</string>
<string name="agent_connection_quest_waiting">Terima “Izinkan debugging?” di headset, dengan Selalu izinkan dicentang</string>
<string name="agent_connection_quest_failed">Tidak dapat terhubung. Terima permintaan debugging di headset, atau jika tidak muncul, jalankan adb tcpip 5555 dari komputer lalu coba lagi</string>
<string name="agent_connection_quest_off">Debugging nirkabel tidak dapat dijangkau. Ketuk Izinkan untuk menyiapkannya lagi</string>
<string name="agent_action_install">Pasang</string>
<string name="agent_action_sign_in">Masuk</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1244,6 +1244,11 @@
<string name="agent_action_prepare">Prepara</string>
<string name="agent_connection_off">Il debug wireless non è raggiungibile; Associa lo attiva</string>
<string name="agent_action_pair">Associa</string>
<string name="agent_step_connection_quest_hint">Quest non ha una schermata di accoppiamento. Da un computer, esegui una volta: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS e adb tcpip 5555. Poi tocca Consenti e accetta la richiesta nel visore</string>
<string name="agent_action_allow">Consenti</string>
<string name="agent_connection_quest_waiting">Accetta «Consentire il debug?» nel visore, con Consenti sempre selezionato</string>
<string name="agent_connection_quest_failed">Impossibile connettersi. Accetta la richiesta di debug nel visore oppure, se non è comparsa, esegui adb tcpip 5555 da un computer e riprova</string>
<string name="agent_connection_quest_off">Il debug wireless non è raggiungibile. Tocca Consenti per configurarlo di nuovo</string>
<string name="agent_action_install">Installa</string>
<string name="agent_action_sign_in">Accedi</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1246,6 +1246,11 @@
<string name="agent_action_prepare">準備</string>
<string name="agent_connection_off">ワイヤレスデバッグに接続できません。ペアリングで有効になります</string>
<string name="agent_action_pair">ペアリング</string>
<string name="agent_step_connection_quest_hint">Quest にはペア設定画面がありません。パソコンから一度だけ adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS と adb tcpip 5555 を実行し、[許可] をタップしてヘッドセットの確認を承認してください</string>
<string name="agent_action_allow">許可</string>
<string name="agent_connection_quest_waiting">ヘッドセットで「デバッグを許可しますか?」を、[常に許可] にチェックを入れて承認してください</string>
<string name="agent_connection_quest_failed">接続できませんでした。ヘッドセットでデバッグの確認を承認してください。表示されなかった場合は、パソコンから adb tcpip 5555 を実行してもう一度お試しください</string>
<string name="agent_connection_quest_off">ワイヤレス デバッグに接続できません。[許可] をタップして設定し直してください</string>
<string name="agent_action_install">インストール</string>
<string name="agent_action_sign_in">サインイン</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1246,6 +1246,11 @@
<string name="agent_action_prepare">준비</string>
<string name="agent_connection_off">무선 디버깅에 연결할 수 없습니다. 페어링하면 켜집니다</string>
<string name="agent_action_pair">페어링</string>
<string name="agent_step_connection_quest_hint">Quest에는 페어링 화면이 없습니다. 컴퓨터에서 한 번 실행하세요: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 및 adb tcpip 5555. 그런 다음 허용을 탭하고 헤드셋에서 요청을 수락하세요</string>
<string name="agent_action_allow">허용</string>
<string name="agent_connection_quest_waiting">헤드셋에서 \'디버깅을 허용하시겠습니까?\'를 항상 허용을 선택한 채로 수락하세요</string>
<string name="agent_connection_quest_failed">연결하지 못했습니다. 헤드셋에서 디버깅 요청을 수락하거나, 요청이 나타나지 않았다면 컴퓨터에서 adb tcpip 5555를 실행한 뒤 다시 시도하세요</string>
<string name="agent_connection_quest_off">무선 디버깅에 연결할 수 없습니다. 허용을 탭해 다시 설정하세요</string>
<string name="agent_action_install">설치</string>
<string name="agent_action_sign_in">로그인</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1246,6 +1246,11 @@
<string name="agent_action_prepare">Sediakan</string>
<string name="agent_connection_off">Penyahpepijatan wayarles tidak dapat dicapai; Pasangkan menghidupkannya</string>
<string name="agent_action_pair">Pasangkan</string>
<string name="agent_step_connection_quest_hint">Quest tiada skrin pasangan. Dari komputer, jalankan sekali: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS dan adb tcpip 5555. Kemudian ketik Benarkan dan terima gesaan dalam set kepala</string>
<string name="agent_action_allow">Benarkan</string>
<string name="agent_connection_quest_waiting">Terima “Benarkan penyahpepijatan?” dalam set kepala, dengan Sentiasa benarkan ditanda</string>
<string name="agent_connection_quest_failed">Tidak dapat bersambung. Terima gesaan penyahpepijatan dalam set kepala, atau jika tiada, jalankan adb tcpip 5555 dari komputer dan cuba lagi</string>
<string name="agent_connection_quest_off">Penyahpepijatan wayarles tidak dapat dicapai. Ketik Benarkan untuk menyediakannya semula</string>
<string name="agent_action_install">Pasang</string>
<string name="agent_action_sign_in">Log masuk</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Forbered</string>
<string name="agent_connection_off">Trådløs feilsøking er ikke tilgjengelig; Par slår den på</string>
<string name="agent_action_pair">Par</string>
<string name="agent_step_connection_quest_hint">Quest har ingen sammenkoblingsskjerm. Kjør én gang fra en datamaskin: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS og adb tcpip 5555. Trykk deretter på Tillat og godta spørsmålet i hodesettet</string>
<string name="agent_action_allow">Tillat</string>
<string name="agent_connection_quest_waiting">Godta «Vil du tillate feilsøking?» i hodesettet med Tillat alltid avkrysset</string>
<string name="agent_connection_quest_failed">Kunne ikke koble til. Godta feilsøkingsspørsmålet i hodesettet, eller kjør adb tcpip 5555 fra en datamaskin og prøv igjen hvis det ikke dukket opp</string>
<string name="agent_connection_quest_off">Trådløs feilsøking kan ikke nås. Trykk på Tillat for å sette den opp på nytt</string>
<string name="agent_action_install">Installer</string>
<string name="agent_action_sign_in">Logg inn</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Voorbereiden</string>
<string name="agent_connection_off">Draadloze foutopsporing is niet bereikbaar; Koppelen schakelt dit in</string>
<string name="agent_action_pair">Koppelen</string>
<string name="agent_step_connection_quest_hint">Quest heeft geen koppelscherm. Voer vanaf een computer één keer uit: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS en adb tcpip 5555. Tik daarna op Toestaan en accepteer de melding in de headset</string>
<string name="agent_action_allow">Toestaan</string>
<string name="agent_connection_quest_waiting">Accepteer ‘Foutopsporing toestaan?’ in de headset, met Altijd toestaan aangevinkt</string>
<string name="agent_connection_quest_failed">Verbinden mislukt. Accepteer de foutopsporingsmelding in de headset, of voer adb tcpip 5555 uit vanaf een computer en probeer het opnieuw als er geen verscheen</string>
<string name="agent_connection_quest_off">Draadloze foutopsporing is niet bereikbaar. Tik op Toestaan om het opnieuw in te stellen</string>
<string name="agent_action_install">Installeren</string>
<string name="agent_action_sign_in">Inloggen</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1257,6 +1257,11 @@
<string name="agent_action_prepare">Przygotuj</string>
<string name="agent_connection_off">Debugowanie bezprzewodowe jest niedostępne; Paruj, aby je włączyć</string>
<string name="agent_action_pair">Paruj</string>
<string name="agent_step_connection_quest_hint">Quest nie ma ekranu parowania. Na komputerze uruchom raz: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS oraz adb tcpip 5555. Następnie dotknij Zezwól i zaakceptuj monit w goglach</string>
<string name="agent_action_allow">Zezwól</string>
<string name="agent_connection_quest_waiting">Zaakceptuj „Zezwolić na debugowanie?” w goglach z zaznaczonym Zawsze zezwalaj</string>
<string name="agent_connection_quest_failed">Nie udało się połączyć. Zaakceptuj monit debugowania w goglach, a jeśli się nie pojawił, uruchom adb tcpip 5555 na komputerze i spróbuj ponownie</string>
<string name="agent_connection_quest_off">Debugowanie bezprzewodowe jest nieosiągalne. Dotknij Zezwól, aby skonfigurować je ponownie</string>
<string name="agent_action_install">Zainstaluj</string>
<string name="agent_action_sign_in">Zaloguj się</string>
<string name="upd_pr">PR #%1$d</string>
@@ -1244,6 +1244,11 @@
<string name="agent_action_prepare">Preparar</string>
<string name="agent_connection_off">A depuração sem fios não está acessível; Emparelhar ativa-a</string>
<string name="agent_action_pair">Emparelhar</string>
<string name="agent_step_connection_quest_hint">O Quest não tem ecrã de emparelhamento. Num computador, execute uma vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS e adb tcpip 5555. Depois toque em Permitir e aceite o pedido no headset</string>
<string name="agent_action_allow">Permitir</string>
<string name="agent_connection_quest_waiting">Aceite “Permitir depuração?” no headset, com Permitir sempre assinalado</string>
<string name="agent_connection_quest_failed">Não foi possível ligar. Aceite o pedido de depuração no headset ou, se não apareceu, execute adb tcpip 5555 num computador e tente novamente</string>
<string name="agent_connection_quest_off">A depuração sem fios não está acessível. Toque em Permitir para a configurar de novo</string>
<string name="agent_action_install">Instalar</string>
<string name="agent_action_sign_in">Iniciar sessão</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1252,6 +1252,11 @@
<string name="agent_action_prepare">Preparar</string>
<string name="agent_connection_off">A depuração sem fio não está acessível; Parear a ativa</string>
<string name="agent_action_pair">Parear</string>
<string name="agent_step_connection_quest_hint">O Quest não tem tela de pareamento. Em um computador, execute uma vez: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS e adb tcpip 5555. Depois toque em Permitir e aceite o aviso no headset</string>
<string name="agent_action_allow">Permitir</string>
<string name="agent_connection_quest_waiting">Aceite “Permitir depuração?” no headset, com Sempre permitir marcado</string>
<string name="agent_connection_quest_failed">Não foi possível conectar. Aceite o aviso de depuração no headset ou, se ele não apareceu, execute adb tcpip 5555 em um computador e tente novamente</string>
<string name="agent_connection_quest_off">A depuração sem fio não está acessível. Toque em Permitir para configurá-la de novo</string>
<string name="agent_action_install">Instalar</string>
<string name="agent_action_sign_in">Entrar</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1253,6 +1253,11 @@
<string name="agent_action_prepare">Pregătește</string>
<string name="agent_connection_off">Depanarea fără fir nu este accesibilă; „Asociază” o activează</string>
<string name="agent_action_pair">Asociază</string>
<string name="agent_step_connection_quest_hint">Quest nu are ecran de asociere. De pe un computer, rulează o dată: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS și adb tcpip 5555. Apoi atinge Permite și acceptă solicitarea în cască</string>
<string name="agent_action_allow">Permite</string>
<string name="agent_connection_quest_waiting">Acceptă „Permiți remedierea erorilor?” în cască, cu Permite întotdeauna bifat</string>
<string name="agent_connection_quest_failed">Conectarea a eșuat. Acceptă solicitarea de remediere a erorilor în cască sau, dacă nu a apărut, rulează adb tcpip 5555 de pe un computer și încearcă din nou</string>
<string name="agent_connection_quest_off">Remedierea wireless a erorilor nu este accesibilă. Atinge Permite pentru a o configura din nou</string>
<string name="agent_action_install">Instalează</string>
<string name="agent_action_sign_in">Conectați-vă</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1257,6 +1257,11 @@
<string name="agent_action_prepare">Подготовить</string>
<string name="agent_connection_off">Беспроводная отладка недоступна; «Сопряжение» включит её</string>
<string name="agent_action_pair">Сопряжение</string>
<string name="agent_step_connection_quest_hint">В Quest нет экрана сопряжения. Один раз выполните на компьютере: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS и adb tcpip 5555. Затем нажмите «Разрешить» и подтвердите запрос в шлеме</string>
<string name="agent_action_allow">Разрешить</string>
<string name="agent_connection_quest_waiting">Подтвердите «Разрешить отладку?» в шлеме, отметив «Всегда разрешать»</string>
<string name="agent_connection_quest_failed">Не удалось подключиться. Подтвердите запрос на отладку в шлеме, а если он не появился, выполните adb tcpip 5555 на компьютере и повторите попытку</string>
<string name="agent_connection_quest_off">Беспроводная отладка недоступна. Нажмите «Разрешить», чтобы настроить её заново</string>
<string name="agent_action_install">Установить</string>
<string name="agent_action_sign_in">Войти</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1249,6 +1249,11 @@
<string name="agent_action_prepare">Förbered</string>
<string name="agent_connection_off">Trådlös felsökning kan inte nås; Para slår på den</string>
<string name="agent_action_pair">Para</string>
<string name="agent_step_connection_quest_hint">Quest har ingen parkopplingsskärm. Kör en gång från en dator: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS och adb tcpip 5555. Tryck sedan på Tillåt och godkänn frågan i headsetet</string>
<string name="agent_action_allow">Tillåt</string>
<string name="agent_connection_quest_waiting">Godkänn ”Tillåt felsökning?” i headsetet med Tillåt alltid markerat</string>
<string name="agent_connection_quest_failed">Det gick inte att ansluta. Godkänn felsökningsfrågan i headsetet, eller kör adb tcpip 5555 från en dator och försök igen om ingen visades</string>
<string name="agent_connection_quest_off">Trådlös felsökning går inte att nå. Tryck på Tillåt för att konfigurera den igen</string>
<string name="agent_action_install">Installera</string>
<string name="agent_action_sign_in">Logga in</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1246,6 +1246,11 @@
<string name="agent_action_prepare">เตรียม</string>
<string name="agent_connection_off">เชื่อมต่อการดีบักแบบไร้สายไม่ได้; จับคู่จะเปิดใช้งาน</string>
<string name="agent_action_pair">จับคู่</string>
<string name="agent_step_connection_quest_hint">Quest ไม่มีหน้าจอจับคู่ จากคอมพิวเตอร์ ให้รันหนึ่งครั้ง: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS และ adb tcpip 5555 จากนั้นแตะอนุญาตและยอมรับข้อความในเฮดเซ็ต</string>
<string name="agent_action_allow">อนุญาต</string>
<string name="agent_connection_quest_waiting">ยอมรับ “อนุญาตการแก้ไขข้อบกพร่องไหม” ในเฮดเซ็ต โดยเลือกอนุญาตเสมอ</string>
<string name="agent_connection_quest_failed">เชื่อมต่อไม่ได้ ยอมรับข้อความแก้ไขข้อบกพร่องในเฮดเซ็ต หรือหากไม่มีข้อความขึ้น ให้รัน adb tcpip 5555 จากคอมพิวเตอร์แล้วลองอีกครั้ง</string>
<string name="agent_connection_quest_off">เข้าถึงการแก้ไขข้อบกพร่องแบบไร้สายไม่ได้ แตะอนุญาตเพื่อตั้งค่าใหม่</string>
<string name="agent_action_install">ติดตั้ง</string>
<string name="agent_action_sign_in">ลงชื่อเข้าใช้</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1241,6 +1241,11 @@
<string name="agent_action_prepare">Hazırla</string>
<string name="agent_connection_off">Kablosuz hata ayıklamaya ulaşılamıyor; Eşleştir ile açılır</string>
<string name="agent_action_pair">Eşleştir</string>
<string name="agent_step_connection_quest_hint">Quest\'te eşleme ekranı yok. Bir bilgisayardan bir kez çalıştırın: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS ve adb tcpip 5555. Ardından İzin ver\'e dokunun ve kulaklıktaki istemi kabul edin</string>
<string name="agent_action_allow">İzin ver</string>
<string name="agent_connection_quest_waiting">Kulaklıkta “Hata ayıklamaya izin verilsin mi?” istemini Her zaman izin ver işaretliyken kabul edin</string>
<string name="agent_connection_quest_failed">Bağlanılamadı. Kulaklıktaki hata ayıklama istemini kabul edin veya istem görünmediyse bir bilgisayardan adb tcpip 5555 çalıştırıp tekrar deneyin</string>
<string name="agent_connection_quest_off">Kablosuz hata ayıklamaya ulaşılamıyor. Yeniden ayarlamak için İzin ver\'e dokunun</string>
<string name="agent_action_install">Yükle</string>
<string name="agent_action_sign_in">Giriş yap</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1257,6 +1257,11 @@
<string name="agent_action_prepare">Підготувати</string>
<string name="agent_connection_off">Бездротове налагодження недоступне; «Сполучити» увімкне його</string>
<string name="agent_action_pair">Сполучити</string>
<string name="agent_step_connection_quest_hint">У Quest немає екрана підключення. Один раз виконайте на комп’ютері: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS і adb tcpip 5555. Потім торкніться «Дозволити» й підтвердьте запит у шоломі</string>
<string name="agent_action_allow">Дозволити</string>
<string name="agent_connection_quest_waiting">Підтвердьте «Дозволити налагодження?» у шоломі, позначивши «Завжди дозволяти»</string>
<string name="agent_connection_quest_failed">Не вдалося підключитися. Підтвердьте запит на налагодження в шоломі, а якщо його не було, виконайте adb tcpip 5555 на комп’ютері й спробуйте ще раз</string>
<string name="agent_connection_quest_off">Бездротове налагодження недоступне. Торкніться «Дозволити», щоб налаштувати його знову</string>
<string name="agent_action_install">Установити</string>
<string name="agent_action_sign_in">Увійти</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1246,6 +1246,11 @@
<string name="agent_action_prepare">Chuẩn bị</string>
<string name="agent_connection_off">Không truy cập được gỡ lỗi không dây; Ghép đôi sẽ bật tính năng này</string>
<string name="agent_action_pair">Ghép đôi</string>
<string name="agent_step_connection_quest_hint">Quest không có màn hình ghép nối. Từ máy tính, chạy một lần: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS và adb tcpip 5555. Sau đó nhấn Cho phép và chấp nhận lời nhắc trong kính</string>
<string name="agent_action_allow">Cho phép</string>
<string name="agent_connection_quest_waiting">Chấp nhận “Cho phép gỡ lỗi?” trong kính, với Luôn cho phép được chọn</string>
<string name="agent_connection_quest_failed">Không thể kết nối. Chấp nhận lời nhắc gỡ lỗi trong kính, hoặc nếu không thấy lời nhắc, hãy chạy adb tcpip 5555 từ máy tính rồi thử lại</string>
<string name="agent_connection_quest_off">Không thể kết nối gỡ lỗi không dây. Nhấn Cho phép để thiết lập lại</string>
<string name="agent_action_install">Cài đặt</string>
<string name="agent_action_sign_in">Đăng nhập</string>
<string name="upd_pr">PR #%1$d</string>
@@ -1329,6 +1329,11 @@
<string name="agent_action_prepare">准备</string>
<string name="agent_connection_off">无线调试无法连接;配对即可开启</string>
<string name="agent_action_pair">配对</string>
<string name="agent_step_connection_quest_hint">Quest 没有配对界面。请在电脑上运行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 和 adb tcpip 5555。然后点按“允许”,并在头显中接受提示</string>
<string name="agent_action_allow">允许</string>
<string name="agent_connection_quest_waiting">在头显中接受“允许调试吗?”,并勾选“始终允许”</string>
<string name="agent_connection_quest_failed">无法连接。请在头显中接受调试提示;如果没有出现提示,请在电脑上运行 adb tcpip 5555 后重试</string>
<string name="agent_connection_quest_off">无法连接无线调试。点按“允许”重新设置</string>
<string name="agent_action_install">安装</string>
<string name="agent_action_sign_in">登录</string>
<string name="upd_pr">PR #%1$d</string>
@@ -1245,6 +1245,11 @@
<string name="agent_action_prepare">準備</string>
<string name="agent_connection_off">無線偵錯無法連線;按「配對」即可開啟</string>
<string name="agent_action_pair">配對</string>
<string name="agent_step_connection_quest_hint">Quest 沒有配對畫面。請在電腦上執行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 及 adb tcpip 5555。然後輕按「允許」,並在頭戴裝置中接受提示</string>
<string name="agent_action_allow">允許</string>
<string name="agent_connection_quest_waiting">在頭戴裝置中接受「要允許偵錯嗎?」,並剔選「一律允許」</string>
<string name="agent_connection_quest_failed">無法連接。請在頭戴裝置中接受偵錯提示;如果沒有出現提示,請在電腦上執行 adb tcpip 5555 後再試一次</string>
<string name="agent_connection_quest_off">無法連接無線偵錯。輕按「允許」重新設定</string>
<string name="agent_action_install">安裝</string>
<string name="agent_action_sign_in">登入</string>
<string name="upd_pr">PR #%1$d</string>
@@ -1245,6 +1245,11 @@
<string name="agent_action_prepare">準備</string>
<string name="agent_connection_off">無線偵錯無法連線;配對即可開啟</string>
<string name="agent_action_pair">配對</string>
<string name="agent_step_connection_quest_hint">Quest 沒有配對畫面。請在電腦上執行一次:adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS 和 adb tcpip 5555。接著輕觸「允許」,並在頭戴式裝置中接受提示</string>
<string name="agent_action_allow">允許</string>
<string name="agent_connection_quest_waiting">在頭戴式裝置中接受「要允許偵錯嗎?」,並勾選「一律允許」</string>
<string name="agent_connection_quest_failed">無法連線。請在頭戴式裝置中接受偵錯提示;如果沒有出現提示,請在電腦上執行 adb tcpip 5555 後再試一次</string>
<string name="agent_connection_quest_off">無法連上無線偵錯。輕觸「允許」重新設定</string>
<string name="agent_action_install">安裝</string>
<string name="agent_action_sign_in">登入</string>
<string name="upd_pr">PR #%1$d</string>
+5
View File
@@ -1392,6 +1392,11 @@
<string name="agent_action_prepare">Prepare</string>
<string name="agent_connection_off">Wireless debugging isn\'t reachable; Pair turns it on</string>
<string name="agent_action_pair">Pair</string>
<string name="agent_step_connection_quest_hint">Quest has no pairing screen. From a computer, run once: adb shell pm grant %1$s android.permission.WRITE_SECURE_SETTINGS and adb tcpip 5555. Then tap Allow and accept the prompt in the headset</string>
<string name="agent_action_allow">Allow</string>
<string name="agent_connection_quest_waiting">Accept “Allow debugging?” in the headset, with Always allow ticked</string>
<string name="agent_connection_quest_failed">Couldn\'t connect. Accept the debugging prompt in the headset, or if none appeared, run adb tcpip 5555 from a computer and try again</string>
<string name="agent_connection_quest_off">Wireless debugging isn\'t reachable. Tap Allow to set it up again</string>
<string name="agent_action_install">Install</string>
<string name="agent_action_sign_in">Sign in</string>
<string name="agent_action_free">Free models</string>
@@ -114,6 +114,19 @@ class GameStorageTest {
assertFalse(GameStorage.disconnected(app))
}
@Test fun aRawCardPathTheProcessCannotUseFallsBackToItsStoragePath() {
val usable = setOf("/storage/A042-9B16/Games")
assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { it.path in usable })
}
@Test fun aUsableRawPathAndOtherPathsAreKept() {
assertEquals("/mnt/media_rw/A042-9B16/Games", GameStorage.reachable("/mnt/media_rw/A042-9B16/Games") { true })
assertEquals("/mnt/media_rw/0000-0000/Games", GameStorage.reachable("/mnt/media_rw/0000-0000/Games") { false })
assertEquals("/storage/A042-9B16/Games", GameStorage.reachable("/storage/A042-9B16/Games") { false })
val folder = tmp.newFolder("library").path
assertEquals(folder, GameStorage.reachable(folder) { false })
}
@Test fun onlyAVfatMountCountsAsFat32() {
val mounts = """
/dev/fuse /storage/emulated fuse rw 0 0
@@ -21,6 +21,24 @@ class SecondaryLibraryTest {
assertFalse(SecondaryLibrary.privateRoot(files, content).exists())
}
@Test fun aCardReachedThroughItsOtherPathKeepsItsPrivateDirectories() {
val files = tmp.newFolder("files")
val raw = SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games")).apply { mkdirs() }
assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")))
val storage = SecondaryLibrary.privateRoot(files, File("/storage/B2BD-BCFC/Games")).apply { mkdirs() }
assertEquals(storage, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/B2BD-BCFC/Games")))
}
@Test fun aLibraryWithItsOwnPrivateDirectoriesKeepsThem() {
val files = tmp.newFolder("files")
val own = SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")).apply { mkdirs() }
val raw = File(own.parentFile, SecondaryLibrary.privateRoot(tmp.newFolder("other"), File("/mnt/media_rw/A042-9B16/Games")).name)
raw.mkdirs()
assertEquals(own, SecondaryLibrary.privateRoot(files, File("/storage/A042-9B16/Games")))
assertEquals(raw, SecondaryLibrary.privateRoot(files, File("/mnt/media_rw/A042-9B16/Games")))
assertFalse(SecondaryLibrary.privateRoot(files, File("/storage/emulated/0/Games")).exists())
}
@Test fun aWritableAliasIsSelectedAndItsProbeIsRemoved() {
val library = tmp.newFolder("shared")
val candidate = File(tmp.root, "direct")
@@ -0,0 +1,34 @@
package com.droiddeck.launcher.stores.battlenet
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class BattleNetLibraryTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Test fun aMissingLibraryLeavesBattleNetsInstallFolderAlone() {
SessionPrefs.setGameStorage(app, "/storage/0000-0000/Games", "SD card")
assertTrue(BattleNetClient.library(app).isEmpty())
}
@Test fun anAttachedLibraryIsHandedToBattleNet() {
SessionPrefs.setGameStorage(app, tmp.newFolder("card").path, "SD card")
assertEquals("--library", BattleNetClient.library(app).firstOrNull())
}
@Test fun internalStorageIsHandedToBattleNetWhenItIsTheChoice() {
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
assertEquals("--library", BattleNetClient.library(app).firstOrNull())
}
}
+28
View File
@@ -27,6 +27,28 @@ bytes for dimensions at least four pixels:
These are pixel payloads, not driver allocation sizes or measured FPS gains.
## Scratch ownership and rebuilds
Each `FrameGen` instance owns its scratch buffers, mappings and descriptor sets.
A size or live-preset rebuild first confirms GPU completion and resets that
instance's descriptor pool, then releases the old scratch and image resources.
Motion/history validity is reset with the rebuilt images. Repeated preparation
at the same size and ordinary frame recording do not add device-idle waits.
Healthy destruction releases the descriptor pool, mapped scratch buffers and
images. The native engine releases its input ring only after the chain confirms
completion, so an input image is not destroyed before the wait.
If `vkDeviceWaitIdle` fails with an error other than
`VK_ERROR_DEVICE_LOST`, the affected instance becomes unusable: further
recording and rebuilding stop, and its Vulkan resources and input ring are
intentionally retained because GPU completion is unknown. Device loss follows
a separate teardown path: `FrameGen::destroy()` releases its owned resources
without another wait and returns true, allowing the Engine to release the
input ring. This is local DD-FG containment, not compositor-wide GPU recovery.
A descriptor-pool reset failure also stops that resize without releasing the
resources, but healthy teardown can still release them.
## Validation
Run `python3 -m unittest discover -s tools/tests -p 'test_ddfg_flow_levels.py'`.
@@ -35,4 +57,10 @@ selected through the usual SDK/NDK environment variables. It compiles the actual
DD-FG chain against a mock Vulkan dispatch table and checks resource counts,
dispatch order and sizes, valid descriptor bindings, both models, every preset,
2x/3x/4x generation, small/odd extents, resize and live preset changes.
The same harness enforces descriptor-pool capacity, accounts for all live
resources, and models pending GPU work to reject early cleanup. Lifecycle cases
cover repeated rebuilds, same-size restarts, two simultaneous instances,
automatic/idempotent destruction, partial resize allocation, failed GPU waits,
and failed descriptor-pool resets. The actual native `Engine` is included to
check the input-ring destruction order.
It does not execute shaders on a GPU or replace on-device validation.
+68
View File
@@ -0,0 +1,68 @@
# Experimental spatial upscaling after frame generation
The compositor limits effects output to the logical scene size while frame
generation is active. This avoids running interpolation over the full phone
panel, but can make FSR/GSR/NIS see equal input and output sizes and skip their
spatial pass. Version 0.5.0 instead upscaled before interpolation, which made
the interpolation workload scale with panel resolution.
This experiment keeps the existing source-resolution selection and runs frame
generation at the effects input size. Each generated frame and the final real
frame then uses the selected spatial filter at the mapped display size.
It introduces no extra frame queue or CPU fence wait. Performance and latency
improvements are hypotheses, not measured results.
## Scope and activation
Use an SDR game with a real input buffer smaller than the mapped output.
Enable frame generation and select AMD FSR 1, FSR Fit, Snapdragon GSR/GSR HQ,
or NIS in the scaling filter setting. Keep additional effects (CAS, color,
FXAA, CRT, etc.) off for this experiment. Sharpen-only, linear, nearest,
frame-generation-off, HDR and cardboard paths retain their existing behavior.
Combining a spatial filter with additional effects also retains the old path;
this experiment does not claim to fix that combination.
Source selection remains conservative. A game already rendering a native-size
backbuffer cannot recover its lower internal rendering resolution here.
Overlays included in the low-resolution input are interpolated/upscaled with
that input; this is not a separate native-resolution HUD reconstruction.
GPU targets and source descriptors are separate for each presentation slot so
recording one generated frame cannot replace another frame's bindings.
Source views are released after the existing frame-completion fence; targets
are cached and destroyed with the effects device. This increases GPU memory
use with interpolation multiplier and panel resolution. Allocation failures
retain the input-sized image and the existing screen blit fallback.
## Applying and reverting
Install the test APK produced for this PR. Check its signing/package identity
before replacing an installed release: an Actions test-key APK is not a
release-signed update. An official signed test build requires the repository's
normal publication authorization. Back up session logs and record the exact
APK commit, GPU driver, engine and game settings for comparisons.
No setting migration is required. Disable frame generation or select Linear
to return to the previous presentation path. Do not mix this test with Vulkan
feature-level or game compatibility changes.
## Device validation required before merge
- Compare the same scene on baseline main and this branch: FG off/on, Linear,
FSR, GSR, GSR HQ, NIS, FSR Fit, sharpen-only and nearest.
- Test each supported interpolation multiplier, both engines, warm-up/no
generated frames, 720p-to-1080p and 1080p-to-panel scaling, and no upscale.
- Check real and generated frames for consistent sharpness, halos, ghosting,
text/cursor artifacts, black bars, stretching and frame-order errors.
- Change resolution/filter/engine/multiplier live; open Steam/QAM, rotate,
suspend/resume and stop/restart. Verify no stale image, GPU loss or crash.
- Confirm HDR, cardboard, FG-off and additional-effects fallback behavior.
- Compare sustained frame pacing, generated vs real FPS, GPU load, memory,
temperature and battery use after warm-up; do not treat output FPS alone as
lower input latency. Measure input-to-display latency if equipment permits.
- Test memory pressure and allocation failure fallback; inspect Vulkan
validation for descriptor lifetime, image layouts and synchronization.
Host harnesses exercise resolution routing, generated/real frame counts,
filter gates, fallback and source descriptor lifetime. They do not validate
shader output, mobile-driver behavior, performance or physical input latency.
+28
View File
@@ -0,0 +1,28 @@
# Screen-effect pipeline creation
The screen-effect chain creates its shared render passes, sampler, descriptor
layout/pool and pipeline layout when first used. Graphics pipelines are created
only when the frame's settings require them, then reused until output-format
reset or explicit chain teardown. Source-image and size changes keep the cache.
Pipeline preparation happens before any effect draw is recorded. If a required
pipeline fails to initialize, the chain follows its existing whole-chain
fallback and returns the unprocessed scene; it does not record a partial stack.
Settings are snapshotted at frame entry, so changes during recording apply to
the next invocation.
Spatial upscalers are prepared only when their dispatch path is active. FSR
creates EASU and creates RCAS only when sharpening is enabled; sharpen-only
mode creates RCAS. SMAA prepares its three passes only when selected, while
keeping FXAA available for the existing SMAA scratch-allocation fallback.
Half-precision shaders remain selected by the existing debug property. The
optional fast NIS path and its coefficient resources are deferred until NIS is
actually used; the existing fragment-shader fallback is retained.
This reduces unused pipeline creation and first-use setup work. It does not
reduce the shader work performed each frame, and first use of a newly selected
effect may still compile its pipelines. No background precompilation is added.
Pipeline-count reductions are not measurements of startup latency or FPS.
Validation still requires the native effect-chain tests and on-device visual
testing. Static source checks alone do not establish Vulkan runtime correctness.
+15 -3
View File
@@ -21,9 +21,10 @@ library list, before anything is published.
trip to Xwayland on the paint thread; with no image, wlserver's position is used as upstream does.
- `0101-nested-wayland-cursor-routing.patch` - this app: `gamescope_cursor_composite=2` lets the
nested Wayland session paint its cursor in the output using the real X pointer position; client
cursor surfaces are cleared to prevent a duplicate at the host pointer, while Gamescope's original
default host-cursor fallback is preserved when its no-keyboard-focus policy selects it. Empty
client cursor images and Gamescope's hidden flag still suppress the painted cursor.
cursor surfaces are cleared to prevent a duplicate at the host pointer, and so is Gamescope's
default host-cursor fallback, which would otherwise show a second arrow until Gamescope gets
keyboard focus. Empty client cursor images and Gamescope's hidden flag still suppress the
painted cursor.
- `0110-wayland-backend-touch.patch` - this app: the nested Wayland backend bound only the host's
pointer and keyboard, so a finger on the phone's screen never reached Steam. It now binds
`wl_touch` too and hands each finger to wlserver's touch path (`wlserver_touchdown` / `motion` /
@@ -484,3 +485,14 @@ not wait on fences attached to a dma-buf, so the composite now checks each outpu
It picks the next image that is neither held by the host nor still being scanned out. Only when every free image is
still on the display does it wait for one, up to 100 ms. On kernels that cannot attach the fence, the host keeps
waiting itself and nothing changes. `tools/gamescope/tests/nested-swapchain.cpp` covers the choice and the busy check.
## 0147 Wayland backend: a forwarded client buffer goes back to its client only after scanout
When no composite is needed, gamescope hands a client's own buffer to the host compositor as a plane. The host now
releases a buffer as soon as the display latches the next one and leaves its release fence on the buffer's dma-buf.
gamescope returned the buffer to the client on that release, and a client whose Vulkan driver does not wait on
fences attached to a dma-buf then drew into it while the display was still scanning it out, which showed as black
tiles in compressed buffers. A forwarded client buffer now stays held until `poll(POLLOUT)` on its dma-buf reports
that the display has finished with it, on a waiter thread so nothing else blocks. A release that arrives after the
buffer was shown again is dropped, so the later release decides. Composite output images keep the 0146 path, and a
host that waits for the fence itself releases buffers that are already idle, so nothing changes there.
@@ -74,7 +74,7 @@ index 0000000..d7c21da
+
+ constexpr bool CursorShouldBeForwardedToHost( int cursorCompositeMode, bool useHostCursorFallback )
+ {
+ return cursorCompositeMode != 2 || useHostCursorFallback;
+ return cursorCompositeMode != 2;
+ }
+
+ constexpr bool CursorImageShouldBePainted( bool imageEmpty, bool cursorHidden )
@@ -176,10 +176,10 @@ index 0000000..9c622db
+ REQUIRE( CursorShouldBeComposited( 2, false, false, true, false ) );
+}
+
+TEST_CASE("manual composition retains only the no-focus default cursor fallback", "[cursor_routing]")
+TEST_CASE("manual composition never forwards a cursor to the host", "[cursor_routing]")
+{
+ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, false ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 2, true ) );
+ REQUIRE_FALSE( CursorShouldBeForwardedToHost( 2, true ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 1, false ) );
+ REQUIRE( CursorShouldBeForwardedToHost( 0, false ) );
+}
@@ -0,0 +1,351 @@
diff --git a/src/Backends/WaylandBackend.cpp b/src/Backends/WaylandBackend.cpp
index 12f0f50..a0fedd4 100644
--- a/src/Backends/WaylandBackend.cpp
+++ b/src/Backends/WaylandBackend.cpp
@@ -3,24 +3,28 @@
#include "wlserver.hpp"
#include "vblankmanager.hpp"
#include "steamcompmgr.hpp"
#include "edid.h"
#include "Utils/Defer.h"
#include "Utils/Algorithm.h"
#include "convar.h"
#include "refresh_rate.h"
#include "waitable.h"
#include "Utils/TempFiles.h"
#include "Utils/CursorRouting.h"
#include "Utils/WaylandScaling.h"
+#include "output_image_pick.hpp"
+
+#include <fcntl.h>
+#include <mutex>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <csignal>
#include <sys/mman.h>
#include <poll.h>
#include <linux/input-event-codes.h>
#include <xkbcommon/xkbcommon.h>
#include <libdecor.h>
#include "wlr_begin.hpp"
@@ -485,44 +489,82 @@ namespace gamescope
// One backing plane plus every layer steamcompmgr can hand us.
CWaylandPlane m_Planes[k_nMaxLayers + 1];
bool m_bVisible = true;
std::atomic<bool> m_bDesiredFullscreenState = { false };
bool m_bHostCompositorIsCurrentlyVRR = false;
};
class CWaylandFb final : public CBaseBackendFb
{
public:
- CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer );
+ CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd = -1 );
~CWaylandFb();
void OnCompositorAcquire();
void OnCompositorRelease();
+ void OnScanoutDone( uint64_t ulAcquireSerial );
wl_buffer *GetHostBuffer() const { return m_pHostBuffer; }
wlr_buffer *GetClientBuffer() const { return m_pClientBuffer; }
bool HeldByHost() const override { return m_bCompositorAcquired; }
void Wayland_Buffer_Release( wl_buffer *pBuffer );
static const wl_buffer_listener s_BufferListener;
private:
CWaylandBackend *m_pBackend = nullptr;
wl_buffer *m_pHostBuffer = nullptr;
wlr_buffer *m_pClientBuffer = nullptr;
+ int m_nDmabufFd = -1;
+ std::mutex m_AcquireMutex;
+ uint64_t m_ulAcquireSerial = 0;
bool m_bCompositorAcquired = false;
};
+
+ class CWaylandScanoutRelease final : public IWaitable
+ {
+ public:
+ CWaylandScanoutRelease( CWaylandFb *pFb, int nFd, uint64_t ulAcquireSerial )
+ : m_pFb{ pFb }
+ , m_nFd{ nFd }
+ , m_ulAcquireSerial{ ulAcquireSerial }
+ {
+ }
+
+ int GetFD() override { return m_nFd; }
+ void OnPollOut() override { Finish(); }
+ void OnPollHangUp() override { Finish(); }
+
+ static CAsyncWaiter<> &Waiter()
+ {
+ static CAsyncWaiter<> s_Waiter{ "gamescope-scanout" };
+ return s_Waiter;
+ }
+
+ private:
+ void Finish()
+ {
+ Waiter().RemoveWaitable( this );
+ m_pFb->OnScanoutDone( m_ulAcquireSerial );
+ close( m_nFd );
+ delete this;
+ }
+
+ CWaylandFb *m_pFb;
+ int m_nFd;
+ uint64_t m_ulAcquireSerial;
+ };
const wl_buffer_listener CWaylandFb::s_BufferListener =
{
.release = WAYLAND_USERDATA_TO_THIS( CWaylandFb, Wayland_Buffer_Release ),
};
class CWaylandInputThread
{
public:
CWaylandInputThread();
~CWaylandInputThread();
bool Init( CWaylandBackend *pBackend );
@@ -969,73 +1011,108 @@ namespace gamescope
.action = WAYLAND_NULL(),
};
const zwp_primary_selection_source_v1_listener CWaylandBackend::s_PrimarySelectionSourceListener =
{
.send = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Send ),
.cancelled = WAYLAND_USERDATA_TO_THIS( CWaylandBackend, Wayland_PrimarySelectionSource_Cancelled ),
};
//////////////////
// CWaylandFb
//////////////////
- CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer )
+ CWaylandFb::CWaylandFb( CWaylandBackend *pBackend, wl_buffer *pHostBuffer, int nDmabufFd )
: CBaseBackendFb()
, m_pBackend { pBackend }
, m_pHostBuffer { pHostBuffer }
+ , m_nDmabufFd { nDmabufFd }
{
wl_buffer_add_listener( pHostBuffer, &s_BufferListener, this );
}
CWaylandFb::~CWaylandFb()
{
// I own the pHostBuffer.
wl_buffer_destroy( m_pHostBuffer );
m_pHostBuffer = nullptr;
+ if ( m_nDmabufFd >= 0 )
+ close( m_nDmabufFd );
}
void CWaylandFb::OnCompositorAcquire()
{
- // If the compositor has acquired us, track that
- // and increment the ref count.
- if ( !m_bCompositorAcquired )
+ bool bTakeRef = false;
{
+ std::scoped_lock lock( m_AcquireMutex );
+ m_ulAcquireSerial++;
+ bTakeRef = !m_bCompositorAcquired;
m_bCompositorAcquired = true;
- IncRef();
}
+
+ if ( bTakeRef )
+ IncRef();
}
void CWaylandFb::OnCompositorRelease()
{
- // Compositor has released us, decrement rc.
- //assert( m_bCompositorAcquired );
+ uint64_t ulSerial;
+ {
+ std::scoped_lock lock( m_AcquireMutex );
+ ulSerial = m_ulAcquireSerial;
+ }
+ OnScanoutDone( ulSerial );
+ }
- if ( m_bCompositorAcquired )
+ void CWaylandFb::OnScanoutDone( uint64_t ulAcquireSerial )
+ {
+ bool bDropRef = false;
{
+ std::scoped_lock lock( m_AcquireMutex );
+ if ( ulAcquireSerial != m_ulAcquireSerial )
+ return;
+ bDropRef = m_bCompositorAcquired;
m_bCompositorAcquired = false;
- DecRef();
}
+
+ if ( bDropRef )
+ DecRef();
else
- {
xdg_log.errorf( "Compositor released us but we were not acquired. Oh no." );
- }
}
void CWaylandFb::Wayland_Buffer_Release( wl_buffer *pBuffer )
{
assert( m_pHostBuffer );
assert( m_pHostBuffer == pBuffer );
xdg_log.debugf( "buffer_release: %p", pBuffer );
+ if ( ShowsClientBuffer() && gamescope::DmabufScanoutPending( m_nDmabufFd ) )
+ {
+ int nFd = fcntl( m_nDmabufFd, F_DUPFD_CLOEXEC, 0 );
+ if ( nFd >= 0 )
+ {
+ uint64_t ulSerial;
+ {
+ std::scoped_lock lock( m_AcquireMutex );
+ ulSerial = m_ulAcquireSerial;
+ }
+ auto *pWait = new CWaylandScanoutRelease( this, nFd, ulSerial );
+ if ( CWaylandScanoutRelease::Waiter().AddWaitable( pWait, EPOLLOUT | EPOLLHUP | EPOLLONESHOT ) )
+ return;
+ delete pWait;
+ close( nFd );
+ }
+ }
+
OnCompositorRelease();
}
//////////////////
// CWaylandConnector
//////////////////
CWaylandConnector::CWaylandConnector( CWaylandBackend *pBackend, uint64_t ulVirtualConnectorKey )
: CBaseBackendConnector{ ulVirtualConnectorKey }
, m_pBackend( pBackend )
, m_Planes{ this, this, this, this, this, this, this, this, this }
{
@@ -2349,25 +2426,26 @@ namespace gamescope
pDmaBuf->format,
0u );
if ( !pImportedBuffer )
{
xdg_log.errorf( "Failed to import dmabuf" );
zwp_linux_buffer_params_v1_destroy( pBufferParams );
return nullptr;
}
zwp_linux_buffer_params_v1_destroy( pBufferParams );
- return new CWaylandFb{ this, pImportedBuffer };
+ int nDmabufFd = pDmaBuf->n_planes > 0 ? fcntl( pDmaBuf->fd[0], F_DUPFD_CLOEXEC, 0 ) : -1;
+ return new CWaylandFb{ this, pImportedBuffer, nDmabufFd };
}
bool CWaylandBackend::UsesModifiers() const
{
if ( !cv_wayland_use_modifiers )
return false;
return m_bCanUseModifiers;
}
std::span<const uint64_t> CWaylandBackend::GetSupportedModifiers( uint32_t uDrmFormat ) const
{
auto iter = m_FormatModifiers.find( uDrmFormat );
diff --git a/src/backend.cpp b/src/backend.cpp
index cc91853..ec59c8b 100644
--- a/src/backend.cpp
+++ b/src/backend.cpp
@@ -109,41 +109,47 @@ namespace gamescope
wlserver_unlock();
}
// Potentially release now!
DecRefPrivate();
}
return uRefCount;
}
void CBaseBackendFb::SetBuffer( wlr_buffer *pClientBuffer )
{
+ if ( pClientBuffer )
+ m_bShowsClientBuffer = true;
+
if ( m_pClientBuffer == pClientBuffer )
return;
assert( m_pClientBuffer == nullptr );
m_pClientBuffer = pClientBuffer;
if ( GetRefCount() )
{
wlserver_lock();
wlr_buffer_lock( m_pClientBuffer );
wlserver_unlock( false );
}
m_pReleasePoint = nullptr;
}
void CBaseBackendFb::SetReleasePoint( std::shared_ptr<CReleaseTimelinePoint> pReleasePoint )
{
+ if ( pReleasePoint )
+ m_bShowsClientBuffer = true;
+
if ( m_pReleasePoint == pReleasePoint )
return;
m_pReleasePoint = pReleasePoint;
if ( m_pClientBuffer && GetRefCount() )
{
wlserver_lock();
wlr_buffer_unlock( m_pClientBuffer );
wlserver_unlock();
m_pClientBuffer = nullptr;
}
diff --git a/src/backend.h b/src/backend.h
index 30b42ca..9a27711 100644
--- a/src/backend.h
+++ b/src/backend.h
@@ -303,26 +303,29 @@ namespace gamescope
public:
CBaseBackendFb();
virtual ~CBaseBackendFb();
uint32_t IncRef() override;
uint32_t DecRef() override;
void SetBuffer( wlr_buffer *pClientBuffer ) override;
void SetReleasePoint( std::shared_ptr<CReleaseTimelinePoint> pReleasePoint ) override;
virtual IBackendFb *EnsureImported() override { return this; };
+ bool ShowsClientBuffer() const { return m_bShowsClientBuffer; }
+
private:
wlr_buffer *m_pClientBuffer = nullptr;
+ std::atomic<bool> m_bShowsClientBuffer = { false };
std::shared_ptr<CReleaseTimelinePoint> m_pReleasePoint;
};
class IBackend
{
public:
virtual ~IBackend() {}
virtual bool Init() = 0;
virtual bool PostInit() = 0;
virtual std::span<const char *const> GetInstanceExtensions() const = 0;
virtual std::span<const char *const> GetDeviceExtensions( VkPhysicalDevice pVkPhysicalDevice ) const = 0;
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-f3a45b31
GAMESCOPE_SHA256=3908af87b2ee8a328e9780fc805c6a7bddd11d7405b9992d717b94e16c019313
GAMESCOPE_TAG=gamescope-3.16.29-cb9c4861
GAMESCOPE_SHA256=89a3d70124a13bb5de0b4c67ff75d748a5d7ba6f29590194621754e3550b1f31
@@ -350,6 +350,17 @@ def keeps_open(root):
return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1]
def chosen_folder(root, current, library):
current = current.strip()
folder = windows_path(root, current) if current else None
if not folder or rootfs_drive(root, current) or not os.path.isdir(folder):
return False
try:
return volume_root(os.path.realpath(folder)) == volume_root(os.path.realpath(library))
except OSError:
return False
def write_config(root, library=None):
path = os.path.join(drive_c(root), *CONFIG)
key, value = LAUNCH_BEHAVIOR
@@ -374,6 +385,7 @@ def write_config(root, library=None):
client["HardwareAcceleration"] = "false"
changes.append("acceleration")
if library and isinstance(client.setdefault("Install", {}), dict) \
and not chosen_folder(root, str(client["Install"].get("DefaultInstallPath", "")), library) \
and str(client["Install"].get("DefaultInstallPath", "")).rstrip("/\\") != install_path(root, library).rstrip("\\"):
client["Install"]["DefaultInstallPath"] = install_path(root, library)
changes.append("library")
+4 -5
View File
@@ -739,10 +739,8 @@ char *getcwd(char *buf, size_t size) {
static char *(*orig_getcwd)(char *, size_t) = NULL;
if (!orig_getcwd) orig_getcwd = (char *(*)(char *, size_t))dlsym(RTLD_NEXT, "getcwd");
char *res = orig_getcwd ? orig_getcwd(buf, size) : NULL;
if (res) {
size_t len = strlen(res);
guest_path_of_mount_source(res, len, buf ? size : len + 1, NULL);
}
if (res && !buf) return guest_path_of_allocated_mount_source(res);
if (res) guest_path_of_mount_source(res, strlen(res), size, NULL);
return res;
}
@@ -790,7 +788,8 @@ char *realpath(const char *path, char *resolved_path) {
}
}
}
if (res) guest_path_of_mount_source(res, strlen(res), resolved_path ? PATH_MAX : strlen(res) + 1, NULL);
if (res && !resolved_path) return guest_path_of_allocated_mount_source(res);
if (res) guest_path_of_mount_source(res, strlen(res), PATH_MAX, NULL);
return res;
}
+14
View File
@@ -975,6 +975,20 @@ static size_t guest_path_of_mount_source(char *buf, size_t len, size_t cap, int
return best->dst_len + rest;
}
static char *guest_path_of_allocated_mount_source(char *res) {
size_t len = strlen(res);
char tmp[PATH_MAX];
if (len >= sizeof(tmp)) return res;
memcpy(tmp, res, len + 1);
int converted = 0;
size_t n = guest_path_of_mount_source(tmp, len, sizeof(tmp), &converted);
if (!converted) return res;
char *grown = realloc(res, n + 1);
if (!grown) return res;
memcpy(grown, tmp, n + 1);
return grown;
}
static ssize_t postprocess_readlink(const char *linkpath, char *buf, ssize_t ret, size_t bufsiz) {
if (ret <= 0) return ret;
if ((size_t)ret < bufsiz) {
+215 -20
View File
@@ -1,4 +1,5 @@
#include "framegen.hpp"
#include "ddfg_engine.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
@@ -25,12 +26,19 @@ std::map<VkBuffer, VkBufferCreateInfo> buffers;
std::map<VkDeviceMemory, Allocation> allocations;
std::map<VkBuffer, VkDeviceMemory> buffer_memory;
std::map<VkDescriptorSet, std::map<uint32_t, Binding>> descriptors;
std::map<VkDescriptorSet, VkDescriptorPool> set_pools;
std::map<VkDescriptorPool, uint32_t> pool_capacities;
std::map<VkPipeline, unsigned> pipelines;
std::map<VkImage, unsigned> image_ids;
std::map<VkBuffer, unsigned> buffer_ids;
std::vector<Dispatch> dispatches;
std::vector<VkImageView> external_views;
uintptr_t serial = 100;
unsigned buffer_creates, set_creates;
unsigned buffer_creates, set_creates, pipeline_creates, idle_calls, image_creates, fail_image_at;
bool gpu_pending;
VkResult idle_result = VK_SUCCESS, reset_result = VK_SUCCESS;
const ddfg::DeviceDispatch *engine_dispatch;
const ddfg::InstanceDispatch *engine_instance;
VkPipeline bound_pipeline;
VkDescriptorSet bound_set;
uint64_t command_hash = 14695981039346656037ull;
@@ -61,6 +69,7 @@ template<class T> void VKAPI_CALL destroy(VkDevice, T, const VkAllocationCallbac
VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo *info,
const VkAllocationCallbacks *, VkImage *out) {
if (++image_creates == fail_image_at) return VK_ERROR_OUT_OF_DEVICE_MEMORY;
*out = handle<VkImage>();
images[*out] = {info->extent, info->format, info->usage};
return VK_SUCCESS;
@@ -73,9 +82,11 @@ VkResult VKAPI_CALL create_view(VkDevice, const VkImageViewCreateInfo *info,
return VK_SUCCESS;
}
void VKAPI_CALL destroy_image(VkDevice, VkImage image, const VkAllocationCallbacks *) {
assert(!gpu_pending);
assert(images.erase(image) == 1);
}
void VKAPI_CALL destroy_view(VkDevice, VkImageView view, const VkAllocationCallbacks *) {
assert(!gpu_pending);
assert(views.erase(view) == 1);
}
VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info,
@@ -86,6 +97,7 @@ VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info,
return VK_SUCCESS;
}
void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks *) {
assert(!gpu_pending);
assert(buffers.erase(buffer) == 1);
buffer_memory.erase(buffer);
}
@@ -104,6 +116,7 @@ VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo *info,
return VK_SUCCESS;
}
void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks *) {
assert(!gpu_pending);
assert(allocations.erase(memory) == 1);
}
VkResult VKAPI_CALL bind_image(VkDevice, VkImage image, VkDeviceMemory memory, VkDeviceSize) {
@@ -123,8 +136,14 @@ VkResult VKAPI_CALL map_memory(VkDevice, VkDeviceMemory memory, VkDeviceSize off
*out = allocation.data.get();
return VK_SUCCESS;
}
void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) { assert(allocations.count(memory)); }
VkResult VKAPI_CALL idle(VkDevice) { return VK_SUCCESS; }
void VKAPI_CALL unmap(VkDevice, VkDeviceMemory memory) {
assert(!gpu_pending && allocations.count(memory));
}
VkResult VKAPI_CALL idle(VkDevice) {
idle_calls++;
if (idle_result == VK_SUCCESS) gpu_pending = false;
return idle_result;
}
void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties *out) {
*out = {};
out->memoryTypeCount = 1;
@@ -132,15 +151,42 @@ void VKAPI_CALL memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProper
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
}
VkResult VKAPI_CALL allocate_sets(VkDevice, const VkDescriptorSetAllocateInfo *info, VkDescriptorSet *out) {
const auto used = std::count_if(set_pools.begin(), set_pools.end(), [&](const auto &entry) {
return entry.second == info->descriptorPool;
});
if (used + info->descriptorSetCount > pool_capacities.at(info->descriptorPool))
return VK_ERROR_OUT_OF_POOL_MEMORY;
for (uint32_t i = 0; i < info->descriptorSetCount; i++) {
out[i] = handle<VkDescriptorSet>();
descriptors[out[i]] = {};
set_pools[out[i]] = info->descriptorPool;
set_creates++;
}
return VK_SUCCESS;
}
VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool, VkDescriptorPoolResetFlags) {
descriptors.clear();
VkResult VKAPI_CALL create_pool(VkDevice, const VkDescriptorPoolCreateInfo *info,
const VkAllocationCallbacks *, VkDescriptorPool *out) {
*out = handle<VkDescriptorPool>();
pool_capacities[*out] = info->maxSets;
return VK_SUCCESS;
}
void drop_sets(VkDescriptorPool pool) {
assert(!gpu_pending);
for (auto it = set_pools.begin(); it != set_pools.end();) {
if (it->second == pool) {
descriptors.erase(it->first);
it = set_pools.erase(it);
} else ++it;
}
}
void VKAPI_CALL destroy_pool(VkDevice, VkDescriptorPool pool, const VkAllocationCallbacks *) {
drop_sets(pool);
assert(pool_capacities.erase(pool) == 1);
}
VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool pool, VkDescriptorPoolResetFlags) {
assert(!gpu_pending);
if (reset_result != VK_SUCCESS) return reset_result;
drop_sets(pool);
return VK_SUCCESS;
}
void VKAPI_CALL update_sets(VkDevice, uint32_t count, const VkWriteDescriptorSet *writes,
@@ -164,12 +210,15 @@ VkResult VKAPI_CALL create_pipelines(VkDevice, VkPipelineCache, uint32_t count,
const VkComputePipelineCreateInfo *, const VkAllocationCallbacks *,
VkPipeline *out) {
for (uint32_t i = 0; i < count; i++) {
const auto index = static_cast<unsigned>(pipelines.size());
const auto index = pipeline_creates++ % 10;
out[i] = handle<VkPipeline>();
pipelines[out[i]] = index;
}
return VK_SUCCESS;
}
void VKAPI_CALL destroy_pipeline(VkDevice, VkPipeline pipeline, const VkAllocationCallbacks *) {
assert(!gpu_pending && pipelines.erase(pipeline) == 1);
}
void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline pipeline) {
assert(pipelines.count(pipeline));
bound_pipeline = pipeline;
@@ -248,10 +297,20 @@ VkImageView external_image(uint32_t width, uint32_t height) {
images[image] = {{width, height, 1}, VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT};
views[view] = image;
external_views.push_back(view);
return view;
}
void clear_external_images() {
for (auto view : external_views) {
images.erase(views.at(view));
views.erase(view);
}
external_views.clear();
}
void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsigned generations) {
gpu_pending = false;
const auto previous = external_image(width, height), current = external_image(width, height);
const auto first = dispatches.size();
for (unsigned i = 0; i < generations; i++)
@@ -275,14 +334,29 @@ void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsi
const auto &actual = dispatches[first + i], &want = expected[i];
assert(actual.pipeline == want.pipeline && actual.x == want.x && actual.y == want.y && actual.z == want.z);
}
for (auto it = views.begin(); it != views.end();) {
if (images.at(it->second).format == VK_FORMAT_R8G8B8A8_UNORM) {
images.erase(it->second);
it = views.erase(it);
} else ++it;
}
clear_external_images();
gpu_pending = true;
}
void check_empty() {
assert(images.empty() && views.empty() && buffers.empty() && allocations.empty());
assert(descriptors.empty() && set_pools.empty() && pool_capacities.empty() && pipelines.empty());
}
void check_working_set(const ddfg::FrameGen &fg) {
assert(images.size() == static_cast<size_t>(32 - 2 * fg.flowFinest()));
assert(buffers.size() == static_cast<size_t>(18 - fg.flowFinest()));
assert(descriptors.size() == static_cast<size_t>(54 - 4 * fg.flowFinest()));
assert(allocations.size() == images.size() + buffers.size());
}
}
struct VkTable {};
bool ddfgVkdInit(const VkTable &, ddfg::DeviceDispatch &dd, ddfg::InstanceDispatch &id) {
dd = *engine_dispatch;
id = *engine_instance;
return true;
}
int main(int argc, char **argv) {
@@ -312,25 +386,145 @@ int main(int argc, char **argv) {
dd.DestroyDescriptorSetLayout = destroy<VkDescriptorSetLayout>;
dd.CreatePipelineLayout = create<VkPipelineLayoutCreateInfo, VkPipelineLayout>;
dd.DestroyPipelineLayout = destroy<VkPipelineLayout>;
dd.CreateDescriptorPool = create<VkDescriptorPoolCreateInfo, VkDescriptorPool>;
dd.DestroyDescriptorPool = destroy<VkDescriptorPool>; dd.ResetDescriptorPool = reset_pool;
dd.CreateDescriptorPool = create_pool;
dd.DestroyDescriptorPool = destroy_pool; dd.ResetDescriptorPool = reset_pool;
dd.AllocateDescriptorSets = allocate_sets; dd.UpdateDescriptorSets = update_sets;
dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy<VkPipeline>;
dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy_pipeline;
dd.CmdBindPipeline = bind_pipeline; dd.CmdBindDescriptorSets = bind_sets; dd.CmdDispatch = dispatch;
dd.CmdPipelineBarrier = barrier; dd.CmdClearColorImage = clear_image; dd.CmdCopyImage = copy_image;
ddfg::FrameGen fg;
assert(fg.init(&dd, &id, reinterpret_cast<VkPhysicalDevice>(1), reinterpret_cast<VkDevice>(2),
0, reinterpret_cast<VkQueue>(3)));
engine_dispatch = &dd;
engine_instance = &id;
ddfg::Config cfg;
cfg.enabled = true; cfg.model = model; cfg.perfPreset = preset; cfg.flowScale = 0.6f;
fg.configure(cfg);
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
auto initialize = [&](ddfg::FrameGen &fg) {
assert(fg.init(&dd, &id, reinterpret_cast<VkPhysicalDevice>(1), reinterpret_cast<VkDevice>(2),
0, reinterpret_cast<VkQueue>(3)));
fg.configure(cfg);
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
};
if (mode == "steady" || mode == "automatic") {
const auto waits = idle_calls;
{
ddfg::FrameGen fg;
initialize(fg);
for (unsigned repeat = 0; repeat < repeats; repeat++) {
record(fg, model, width, height, generations);
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
assert(idle_calls == waits);
check_working_set(fg);
}
if (mode == "steady") {
fg.destroy();
fg.destroy();
assert(idle_calls == waits + 1);
}
}
check_empty();
assert(idle_calls == waits + 1);
std::puts("PASS lifecycle=steady-and-idempotent-destruction");
return 0;
}
if (mode == "restart" || mode == "instances") {
for (unsigned repeat = 0; repeat < repeats; repeat++) {
ddfg::FrameGen first;
initialize(first);
record(first, model, width, height, generations);
check_working_set(first);
if (mode == "instances") {
gpu_pending = false;
ddfg::FrameGen second;
initialize(second);
record(second, model, width, height, generations);
first.destroy();
record(second, model, width, height, generations);
check_working_set(second);
second.destroy();
} else first.destroy();
check_empty();
}
std::puts("PASS lifecycle=restart-and-instance-isolation");
return 0;
}
if (mode == "engine" || mode == "engine-failure") {
{
ddfg::Engine engine;
assert(engine.init(VkTable{}, reinterpret_cast<VkPhysicalDevice>(1),
reinterpret_cast<VkDevice>(2), 0, reinterpret_cast<VkQueue>(3)));
engine.configure(generations + 1, model, preset, 0.6f);
assert(engine.prepare(width, height, VK_FORMAT_R8G8B8A8_UNORM));
for (unsigned frame = 0; frame < 3; frame++) {
gpu_pending = false;
const auto source = external_image(width, height);
const auto output = external_image(width, height);
const auto count = engine.plan(generations);
engine.process(reinterpret_cast<VkCommandBuffer>(1), views.at(source), width, height, count);
for (unsigned generation = 0; generation < count; generation++)
engine.generateInto(reinterpret_cast<VkCommandBuffer>(1), generation, count,
views.at(output), output, width, height);
clear_external_images();
gpu_pending = true;
}
if (mode == "engine-failure") {
idle_result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
assert(!engine.prepare(width + 17, height + 9, VK_FORMAT_R8G8B8A8_UNORM));
assert(engine.unavailable() && !engine.valid());
}
}
if (mode == "engine") check_empty();
else assert(gpu_pending && !images.empty() && !buffers.empty() && !descriptors.empty());
std::puts("PASS lifecycle=engine-ownership");
return 0;
}
if (mode == "idle-failure" || mode == "destroy-failure" || mode == "reset-failure" || mode == "partial") {
{
ddfg::FrameGen fg;
initialize(fg);
record(fg, model, width, height, generations);
const auto prior_buffers = buffers.size(), prior_images = images.size(), prior_sets = descriptors.size();
if (mode == "partial") {
fail_image_at = image_creates + 2;
assert(!fg.onResize({width + 17, height + 9}, VK_FORMAT_R8G8B8A8_UNORM));
assert(!fg.valid());
} else {
if (mode == "reset-failure") reset_result = VK_ERROR_OUT_OF_HOST_MEMORY;
else idle_result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
if (mode == "destroy-failure") fg.destroy();
else assert(!fg.onResize({width + 17, height + 9}, VK_FORMAT_R8G8B8A8_UNORM));
assert(!fg.valid());
assert(buffers.size() == prior_buffers && images.size() == prior_images &&
descriptors.size() == prior_sets);
const auto prior_dispatches = dispatches.size();
const auto prior_waits = idle_calls;
fg.record(reinterpret_cast<VkCommandBuffer>(1), VK_NULL_HANDLE, VK_NULL_HANDLE, VK_NULL_HANDLE, 0.5f);
assert(dispatches.size() == prior_dispatches);
if (mode != "reset-failure") {
assert(!fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
cfg.perfPreset = (preset + 1) % 3;
fg.configure(cfg);
if (mode == "destroy-failure") {
idle_result = VK_SUCCESS;
assert(fg.destroy());
} else {
fg.destroy();
assert(idle_calls == prior_waits + 1);
}
}
}
}
if (mode == "reset-failure" || mode == "partial" || mode == "destroy-failure") check_empty();
else assert(gpu_pending && !images.empty() && !buffers.empty() && !descriptors.empty());
std::puts("PASS lifecycle=failure-containment");
return 0;
}
ddfg::FrameGen fg;
initialize(fg);
assert(mode == "resources" || mode == "record" || mode == "resize" || mode == "preset");
for (unsigned repeat = 0; repeat < repeats; repeat++) {
const auto old_buffers = buffer_creates, old_sets = set_creates;
if (mode != "record") check_images(width, height, fg.flowFinest());
record(fg, model, width, height, generations);
if (mode != "record") {
check_working_set(fg);
assert(buffer_creates - old_buffers == static_cast<unsigned>(15 - fg.flowFinest()));
assert(set_creates - old_sets == static_cast<unsigned>(54 - 4 * fg.flowFinest()));
}
@@ -356,4 +550,5 @@ int main(int argc, char **argv) {
dispatches.size(), static_cast<unsigned long long>(command_hash));
fg.destroy();
assert(images.empty() && views.empty());
if (mode != "record") check_empty();
}
+81 -1
View File
@@ -51,6 +51,73 @@ static VkResult VKAPI_CALL allocate_set(VkDevice dev, const VkDescriptorSetAlloc
*out = (VkDescriptorSet)(uintptr_t)(200 + ++sets);
return VK_SUCCESS;
}
static VkImageLayout restored_layout;
static VkPipelineStageFlags restored_stage;
static void VKAPI_CALL pipeline_barrier(VkCommandBuffer cmd, VkPipelineStageFlags src, VkPipelineStageFlags dst,
VkDependencyFlags flags, uint32_t nm, const VkMemoryBarrier *m, uint32_t nb,
const VkBufferMemoryBarrier *b, uint32_t ni, const VkImageMemoryBarrier *images) {
for (uint32_t k = 0; k < ni; k++) {
if (images[k].image == (VkImage)(uintptr_t)10 && images[k].newLayout == VK_IMAGE_LAYOUT_GENERAL) {
restored_layout = images[k].oldLayout;
restored_stage = src;
}
}
}
static void VKAPI_CALL begin_pass(VkCommandBuffer c, const VkRenderPassBeginInfo *i, VkSubpassContents s) {}
static void VKAPI_CALL viewport(VkCommandBuffer c, uint32_t f, uint32_t n, const VkViewport *v) {}
static void VKAPI_CALL scissor(VkCommandBuffer c, uint32_t f, uint32_t n, const VkRect2D *v) {}
static void VKAPI_CALL bind_pipeline(VkCommandBuffer c, VkPipelineBindPoint b, VkPipeline p) {}
static void VKAPI_CALL bind_sets(VkCommandBuffer c, VkPipelineBindPoint b, VkPipelineLayout l, uint32_t f,
uint32_t n, const VkDescriptorSet *s, uint32_t nd, const uint32_t *d) {}
static void VKAPI_CALL push(VkCommandBuffer c, VkPipelineLayout l, VkShaderStageFlags s, uint32_t o,
uint32_t n, const void *v) {}
static void VKAPI_CALL draw(VkCommandBuffer c, uint32_t n, uint32_t i, uint32_t f, uint32_t fi) {}
static void VKAPI_CALL end_pass(VkCommandBuffer c) {}
static void VKAPI_CALL blit(VkCommandBuffer c, VkImage a, VkImageLayout al, VkImage b, VkImageLayout bl,
uint32_t n, const VkImageBlit *r, VkFilter f) {}
static void check_generated_settings_and_layout(void) {
g_vk.CmdPipelineBarrier = pipeline_barrier;
g_vk.CmdBeginRenderPass = begin_pass;
g_vk.CmdSetViewport = viewport; g_vk.CmdSetScissor = scissor;
g_vk.CmdBindPipeline = bind_pipeline; g_vk.CmdBindDescriptorSets = bind_sets;
g_vk.CmdPushConstants = push; g_vk.CmdDraw = draw; g_vk.CmdEndRenderPass = end_pass;
g_vk.CmdBlitImage = blit;
g_rp = (VkRenderPass)(uintptr_t)5;
g_pipe[P_SGSR] = (VkPipeline)(uintptr_t)6;
g_pipe[P_COLOR] = (VkPipeline)(uintptr_t)7;
g_ready = 1;
for (int k = 0; k < 2; k++) {
struct fx_target *t = &g_contexts[1].targets[k];
t->img = (VkImage)(uintptr_t)(30 + k); t->w = 1920; t->h = 1080;
}
vkp_effects_set_scaling(3);
assert(vkp_effects_prepare_generated());
vkp_effects_set_scaling(0);
vkp_effects_set_cas(1, 75);
vkp_effects_sync();
assert(g_cur.scaling == 0 && cas_active(&g_cur));
assert(g_generated_settings.scaling == 3 && !effect_count(&g_generated_settings));
int w, h;
VkImage input = (VkImage)(uintptr_t)10;
assert(vkp_effects_run_before_generated(VK_NULL_HANDLE, input, 1280, 720, &w, &h) == input);
assert(w == 1280 && h == 720);
assert(vkp_effects_run_generated(VK_NULL_HANDLE, input, 1280, 720, 1920, 1080, 0, &w, &h) != input);
assert(w == 1920 && h == 1080);
assert(restored_layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
assert(restored_stage == VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT);
g_generated_settings.scaling = 0;
g_generated_settings.color_on = 1;
assert(vkp_effects_run_generated(VK_NULL_HANDLE, input, 1280, 720, 1920, 1080, 0, &w, &h) != input);
assert(restored_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
assert(restored_stage == VK_PIPELINE_STAGE_TRANSFER_BIT);
g_ready = -1;
assert(vkp_effects_run_generated(VK_NULL_HANDLE, input, 1280, 720, 1920, 1080, 0, &w, &h) == input);
assert(w == 1280 && h == 720);
assert(restored_layout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
assert(g_context == 0);
}
static void VKAPI_CALL update_set(VkDevice dev, uint32_t count, const VkWriteDescriptorSet *writes,
uint32_t copies, const VkCopyDescriptorSet *copy) {
(void)dev; (void)copies; (void)copy;
@@ -84,7 +151,20 @@ int main(int argc, char **argv) {
VkImage source = (VkImage)(uintptr_t)10;
assert(scene_ensure(source, 1280, 720) == 0);
VkImageView original = bound_view;
if (!strcmp(argv[1], "recycled")) {
if (!strcmp(argv[1], "generated-layout")) {
check_generated_settings_and_layout();
} else if (!strcmp(argv[1], "generated")) {
for (int k = 1; k < FX_CONTEXTS; k++) {
g_context = k;
assert(scene_ensure((VkImage)(uintptr_t)(10 + k), 1280, 720) == 0);
}
assert(sets == FX_CONTEXTS && !freed_sets);
vkp_effects_release_generated_sources();
assert(g_context == 0 && freed_sets == FX_CONTEXTS - 1);
assert(g_scene.img == source && g_scene.view == original);
vkp_effects_release_generated_sources();
assert(freed_sets == FX_CONTEXTS - 1);
} else if (!strcmp(argv[1], "recycled")) {
vkp_effects_forget_image(source);
assert(freed_sets == 1 && freed_views == 1);
assert(scene_ensure(source, 1280, 720) == 0);
+31
View File
@@ -295,6 +295,37 @@ class DriveTest(Temp):
self.assertEqual(BNET["install_path"](self.root, str(self.card)), "D:\\")
self.assertEqual(sorted(os.listdir(self.devices)), ["d:"])
def test_a_folder_chosen_in_battlenet_on_the_library_drive_is_kept(self):
path = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"])
BNET["write_config"](self.root)
self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library")
(self.card / "Battle.net").mkdir()
config = json.loads(path.read_text())
config["Client"]["Install"]["DefaultInstallPath"] = "D:\\Battle.net"
path.write_text(json.dumps(config))
self.assertIsNone(BNET["write_config"](self.root, str(self.library)))
self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Battle.net")
def test_a_chosen_folder_inside_the_native_rootfs_is_not_kept_whatever_its_spacing(self):
BNET["write_config"](self.root, str(self.library))
rootfs = self.card / "files/linuxfs"
(rootfs / "Games").mkdir(parents=True)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
for current in ("D:\\files\\linuxfs\\Games", " D:\\files\\linuxfs\\Games"):
self.assertFalse(BNET["chosen_folder"](self.root, current, str(self.library)))
def test_a_folder_on_another_drive_or_missing_moves_to_the_library(self):
path = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"])
BNET["write_config"](self.root, str(self.library))
internal = self.tmp / "root/Games/Stores/Battle.net"
internal.mkdir(parents=True)
for current in ("Z:" + str(internal), "D:\\Gone"):
config = json.loads(path.read_text())
config["Client"]["Install"]["DefaultInstallPath"] = current
path.write_text(json.dumps(config))
self.assertEqual(BNET["write_config"](self.root, str(self.library)), "library")
self.assertEqual(json.loads(path.read_text())["Client"]["Install"]["DefaultInstallPath"], "D:\\Games\\Battle.net")
def test_drives_in_use_and_the_ones_proton_owns_are_left_alone(self):
self.devices.mkdir(parents=True)
os.symlink("/somewhere/else", self.devices / "d:")
+33
View File
@@ -40,6 +40,7 @@ class DdfgFlowLevelsTest(unittest.TestCase):
"-Wno-missing-field-initializers", "-Wno-misleading-indentation",
"-I" + str(work / "include"), "-I" + str(CHAIN),
str(ROOT / "tools/tests/ddfg_flow_levels_harness.cpp"), str(CHAIN / "framegen.cpp"),
str(CHAIN / "ddfg_engine.cpp"),
"-o", str(cls.binary),
], capture_output=True, text=True, timeout=120)
if build.returncode:
@@ -97,6 +98,38 @@ class DdfgFlowLevelsTest(unittest.TestCase):
with self.subTest(model=model):
self.run_case("preset", model=model, generations=3, repeats=4)
def test_many_resizes_do_not_accumulate_scratch_resources(self):
for model in (3, 4):
for preset in range(3):
with self.subTest(model=model, preset=preset):
self.run_case("resize", model=model, preset=preset, generations=3, repeats=16)
def test_same_size_engine_restarts_use_fresh_scratch(self):
self.run_case("restart", generations=3, repeats=8)
def test_instances_do_not_share_or_destroy_each_others_scratch(self):
self.run_case("instances", generations=3, repeats=3)
def test_engine_teardown_waits_before_destroying_its_input_ring(self):
self.run_case("engine", generations=3)
def test_failed_gpu_wait_stops_recording_and_retains_resources(self):
for mode in ("idle-failure", "destroy-failure", "engine-failure"):
with self.subTest(mode=mode):
self.run_case(mode, generations=3)
def test_descriptor_pool_reset_failure_does_not_free_live_scratch(self):
self.run_case("reset-failure", generations=3)
def test_partial_resize_allocation_is_cleaned_up(self):
self.run_case("partial", generations=3)
def test_steady_frames_and_same_size_prepare_add_no_gpu_waits(self):
self.run_case("steady", generations=3, repeats=10)
def test_scope_exit_releases_resources_without_an_explicit_destroy(self):
self.run_case("automatic", generations=3, repeats=3)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,68 @@
import pathlib
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[2]
SOURCE = ROOT / "app/src/main/cpp/waylandcomp/src/effects_chain.c"
def function_body(source: str, signature: str) -> str:
start = source.index(signature)
opening = source.index("{", start)
depth = 0
for pos in range(opening, len(source)):
if source[pos] == "{":
depth += 1
elif source[pos] == "}":
depth -= 1
if depth == 0:
return source[opening + 1:pos]
raise AssertionError(f"unterminated function: {signature}")
class LazyEffectPipelineSourceTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.source = SOURCE.read_text(encoding="utf-8")
def test_shared_setup_does_not_create_graphics_pipelines(self):
body = function_body(self.source, "static int objects_ensure(void)")
self.assertNotIn("post_pipeline_for_renderpass(", body)
self.assertNotIn("shader(upscale_vert_code", body)
self.assertIn("effect pipelines are created when needed", body)
def test_pipelines_are_prepared_before_effect_chain_resources_and_draws(self):
body = function_body(self.source, "static VkImage effects_run(")
prepare = body.index("pipelines_ensure(spatial, s)")
scene = body.index("scene_ensure(scene, scene_w, scene_h)")
self.assertLess(prepare, scene)
self.assertIn("objects_ensure() == 0 && pipelines_ensure(spatial, s) == 0", body)
def test_lazy_path_covers_active_upscalers_and_effects(self):
body = function_body(self.source, "static int pipelines_ensure(")
for required in (
"spatial == 3", "spatial == 8", "spatial == 4 || spatial == 5",
"spatial == 6", "spatial == 7", "cas_active(s)",
"s->color_on", "s->aa_mode == 1 || s->aa_mode == 2",
"s->aa_mode == 2", "s->toon", "s->hdr_on", "s->ntsc",
"s->crt", "deband_active(s)",
):
with self.subTest(required=required):
self.assertIn(required, body)
def test_existing_fallback_pipelines_are_prepared(self):
body = function_body(self.source, "static int pipelines_ensure(")
self.assertIn("s->aa_mode == 1 || s->aa_mode == 2", body)
self.assertIn("else if (g_upscale_half) MK(1, P_SGSR, sgsr_half_code", body)
self.assertIn("if (!g_nis_fast) MK(1, P_NIS, nis_code", body)
def test_failed_preparation_uses_whole_chain_fallback(self):
body = function_body(self.source, "static int pipelines_ensure(")
self.assertIn("return chain_failed();", body)
failure = function_body(self.source, "static int chain_failed(void)")
self.assertIn("objects_destroy();", failure)
self.assertIn("g_ready = -1;", failure)
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -57,6 +57,12 @@ class EffectsSourceCacheTest(unittest.TestCase):
def test_resize_replaces_the_cached_view_and_descriptor(self):
self.check_cache('resize')
def test_generated_frames_keep_separate_descriptors_until_completion(self):
self.check_cache('generated')
def test_generated_settings_snapshot_and_source_layout_restoration(self):
self.check_cache('generated-layout')
if __name__ == '__main__':
unittest.main()
+80 -13
View File
@@ -106,6 +106,9 @@ class EffectsSourceResolutionTest(unittest.TestCase):
def test_frame_generation_keeps_upscaling_and_sharpening_at_panel_size(self):
self.check_case('framegen-sharpening')
def test_frame_generation_runs_spatial_post_upscale(self):
self.check_case('framegen-upscale')
TYPES = r'''
#include <assert.h>
@@ -157,7 +160,7 @@ typedef struct {
#define HDR_FMT 101
#define FG_HDR_FMT 102
#define VK_FORMAT_R8G8B8A8_UNORM SCENE_FMT
#define VKP_FG_MAX_GENERATIONS 2
#define VKP_FG_MAX_GENERATIONS 3
#define HDRC_OUT_PQ 1
#define HDRC_OUT_SDR 2
#define droiddeck_log(...) ((void)0)
@@ -204,7 +207,7 @@ static int g_dev_state = 1, g_window = 1, g_swapchain, g_swap_extra;
static int g_colorspace_ext, g_swap_hdr_unavailable, g_swap_is_hdr, g_swap_hdr_want;
static int g_plain_frame, g_first_frame_done, g_base_black;
static int g_qfam, g_queue, g_dev, g_fence, g_swap_fmt = SCENE_FMT;
static int g_cmds[3], g_acqs[3], g_rnds[3] = {11, 12, 13}, g_rnd_count = 3, images[1] = {2}, *g_images = images;
static int g_cmds[4], g_acqs[4], g_rnds[4] = {11, 12, 13, 14}, g_rnd_count = 4, images[1] = {2}, *g_images = images;
static uint32_t g_swap_md_identity;
static VkExtent2D g_extent = {1920, 1080};
static struct { float kx, ky, off_x, off_y; int rx, ry, rw, rh; } g_map;
@@ -277,8 +280,32 @@ static VkImage vkp_effects_run(int cmd, int source, int w, int h, int ow, int oh
if (fail_effects) { *rw = w; *rh = h; return source; }
*rw = ow; *rh = oh; return 4;
}
static int vkp_framegen_run(int cmd, int result, int depth, int w, int h, int format, int *generated) { return 0; }
static int vkp_effects_prepare_generated(void) {
return g_cur.scaling >= 3 && g_cur.scaling <= 8 && g_cur.scaling != 6 && !postprocessing;
}
static VkImage vkp_effects_run_before_generated(int cmd, int source, int w, int h, int *rw, int *rh) {
return vkp_effects_run(cmd, source, w, h, w, h, rw, rh);
}
static int generations, post_count, fg_w, fg_h;
static int post_sources[4], screen_widths[4], screen_heights[4], screen_images[4];
static int vkp_framegen_run(int cmd, int result, int depth, int w, int h, int format, int *generated) {
fg_w = w; fg_h = h;
for (int i = 0; i < generations; i++) generated[i] = 20 + i;
return generations;
}
static void vkp_effects_release_generated_sources(void) {}
static VkImage vkp_effects_run_generated(int cmd, int source, int w, int h, int ow, int oh,
int slot, int *rw, int *rh) {
assert(slot == post_count && slot < 4);
assert(w == fg_w && h == fg_h);
post_sources[post_count++] = source;
*rw = fail_effects ? w : ow; *rh = fail_effects ? h : oh;
return fail_effects ? source : 40 + slot;
}
static void record_screen_blit(int cmd, int result, int w, int h, int sw, int sh, int image, int filter, int cb) {
assert(screen_count < 4);
screen_widths[screen_count] = w; screen_heights[screen_count] = h;
screen_images[screen_count] = result;
screen_count++; logical_w = sw; logical_h = sh;
}
static void device_lost(const char *reason) {}
@@ -302,6 +329,7 @@ static void reset(void) {
effects_active = 1; g_cur = (struct fx_settings){4};
framegen = cardboard = fail_scene = fail_effects = postprocessing = g_plain_frame = 0;
g_pass.active = 0; g_extent = (VkExtent2D){1920, 1080};
generations = post_count = fg_w = fg_h = 0;
image.w = 1280; image.h = 720;
}
static void check_helper(void) {
@@ -575,24 +603,62 @@ static void check_allocation(void) {
assert(recorded_blits[1].dstOffsets[1].x == 1920 && recorded_blits[1].dstOffsets[1].y == 1080);
assert(target_w == 1920 && target_h == 1080);
}
static void check_framegen_output(int scaling, int cas, int grading, int panel) {
static void check_framegen_output(int scaling, int cas, int grading, int panel, int post_upscale) {
reset(); framegen = 1; postprocessing = grading;
g_cur = (struct fx_settings){scaling, cas, cas ? 60 : 0};
g_extent = (VkExtent2D){2880, 1620};
struct vkp_draw draw = fullscreen();
run_path(0, &draw, 1, NULL);
assert(effects_count == 1);
assert(output_w == (panel ? 2880 : 1920) && output_h == (panel ? 1620 : 1080));
if (post_upscale) {
assert(output_w == 1280 && output_h == 720);
assert(screen_count == 1);
assert(screen_widths[0] == 2880 && screen_heights[0] == 1620);
} else {
assert(output_w == (panel ? 2880 : 1920) && output_h == (panel ? 1620 : 1080));
}
}
static void check_framegen_sharpening(void) {
check_framegen_output(4, 0, 0, 1);
check_framegen_output(3, 0, 0, 1);
check_framegen_output(8, 0, 0, 1);
check_framegen_output(0, 1, 1, 1);
check_framegen_output(1, 1, 1, 1);
check_framegen_output(0, 0, 1, 0);
check_framegen_output(6, 0, 0, 0);
check_framegen_output(2, 0, 1, 0);
check_framegen_output(4, 0, 0, 1, 1);
check_framegen_output(3, 0, 0, 1, 1);
check_framegen_output(8, 0, 0, 1, 1);
check_framegen_output(0, 1, 1, 1, 0);
check_framegen_output(1, 1, 1, 1, 0);
check_framegen_output(0, 0, 1, 0, 0);
check_framegen_output(6, 0, 0, 0, 0);
check_framegen_output(2, 0, 1, 0, 0);
}
static void check_framegen_upscale(void) {
for (int count = 0; count <= VKP_FG_MAX_GENERATIONS; count++) {
reset(); framegen = 1; generations = count;
struct vkp_draw draw = fullscreen();
run_path(0, &draw, 1, NULL);
assert(fg_w == 1280 && fg_h == 720);
assert(post_count == count + 1 && screen_count == count + 1);
for (int k = 0; k < screen_count; k++) {
assert(screen_widths[k] == 1920 && screen_heights[k] == 1080);
assert(post_sources[k] == (k < count ? 20 + k : 4));
assert(screen_images[k] == 40 + k);
}
}
for (int mode = 0; mode <= 8; mode++) {
reset(); framegen = 1; g_cur.scaling = mode;
struct vkp_draw draw = fullscreen();
run_path(0, &draw, 1, NULL);
assert(post_count == (mode >= 3 && mode != 6));
}
reset(); framegen = 1; fail_effects = 1;
struct vkp_draw draw = fullscreen();
run_path(0, &draw, 1, NULL);
assert(post_count == 1 && screen_widths[0] == 1280 && screen_heights[0] == 720);
assert(screen_images[0] == 1);
reset(); framegen = 1; postprocessing = 1;
run_path(0, &draw, 1, NULL); assert(post_count == 0);
reset(); framegen = 1; cardboard = 1;
run_path(0, &draw, 1, NULL); assert(post_count == 0);
reset(); framegen = 1;
struct vkp_hdr_frame hdr = {0};
run_path(0, &draw, 1, &hdr); assert(post_count == 0);
}
int main(int argc, char **argv) {
assert(argc == 2); reset();
@@ -610,6 +676,7 @@ int main(int argc, char **argv) {
else if (!strcmp(argv[1], "overlay-barriers")) check_overlay_barriers();
else if (!strcmp(argv[1], "postprocessing")) check_postprocessing();
else if (!strcmp(argv[1], "framegen-sharpening")) check_framegen_sharpening();
else if (!strcmp(argv[1], "framegen-upscale")) check_framegen_upscale();
else assert(0);
puts("PASS");
}
+30
View File
@@ -0,0 +1,30 @@
from pathlib import Path
import re
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
def code_only(text):
"""The source without its comments and string literals."""
text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S)
text = re.sub(r"//[^\n]*", " ", text)
return re.sub(r'"(?:\\.|[^"\\\n])*"', '""', text)
class FakeinputBionicTest(unittest.TestCase):
# DroidDeck-Bionic preloads this library into its Wine processes (tools/bionic-runtime/build.sh). bionic
# exports no __chk_fail: a library that names it there cannot be loaded, so no Wine program starts
# ("cannot locate symbol "__chk_fail"").
def test_glibcs_fortify_failure_is_named_only_off_bionic(self):
code = code_only(SOURCE.read_text())
guarded = re.compile(r"#if defined\(__BIONIC__\)\n(?P<bionic>.*?)#else\n(?P<glibc>.*?)#endif\n", re.S)
blocks = [m for m in guarded.finditer(code) if "__chk_fail" in m.group("glibc")]
self.assertTrue(blocks, "the glibc-only __chk_fail is behind #if defined(__BIONIC__) ... #else")
for block in blocks:
self.assertNotIn("__chk_fail", block.group("bionic"))
self.assertNotIn("__chk_fail", guarded.sub("", code))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,59 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from test_vk_pending_completion import function
class FramegenRingLifetimeTest(unittest.TestCase):
def test_ring_forgets_effect_sources_before_releasing_images(self):
compiler = shutil.which(os.environ.get('CC', 'cc'))
if not compiler:
self.skipTest('A host C compiler is required')
root = Path(__file__).resolve().parents[2]
source = (root / 'app/src/main/cpp/waylandcomp/src/framegen_bridge.c').read_text()
code = r'''
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <stddef.h>
static int g_dev, g_engine_ok = 1, idle, forgotten[4], images, views, memory, engine;
static uint32_t g_ring_n = 3;
static struct { int img, view, mem; } g_ring[3];
static void wait_idle(int d) { idle++; }
static void vkp_effects_forget_image(int image) { assert(idle == 1); forgotten[image]++; }
static void destroy_image(int d, int image, const void *a) {
assert(forgotten[image] == 1); images++;
}
static void destroy_view(int d, int view, const void *a) { assert(idle == 1); views++; }
static void free_memory(int d, int mem, const void *a) { assert(images > memory); memory++; }
static void fge_forget_targets(void) { assert(images == 3); engine++; }
static struct {
void (*DeviceWaitIdle)(int);
void (*DestroyImage)(int, int, const void *);
void (*DestroyImageView)(int, int, const void *);
void (*FreeMemory)(int, int, const void *);
} vk = {wait_idle, destroy_image, destroy_view, free_memory};
'''
code += function(source, 'destroy_ring')
code += r'''
int main(void) {
for (int i = 0; i < 3; i++) g_ring[i].img = g_ring[i].view = g_ring[i].mem = i + 1;
destroy_ring();
assert(g_ring_n == 0 && images == 3 && views == 3 && memory == 3 && engine == 1);
for (int i = 0; i < 3; i++) assert(!g_ring[i].img && !g_ring[i].view && !g_ring[i].mem);
destroy_ring();
assert(idle == 1 && engine == 1);
}
'''
with tempfile.TemporaryDirectory() as tmp:
folder = Path(tmp)
probe = folder / 'ring.c'
binary = folder / 'ring'
probe.write_text(code)
subprocess.run([compiler, '-std=c11', str(probe), '-o', str(binary)], check=True,
capture_output=True, text=True)
subprocess.run([str(binary)], check=True, capture_output=True, timeout=10)
@@ -0,0 +1,222 @@
from pathlib import Path
import os
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
PATCHES = ROOT / "tools/gamescope/patches"
PICK = PATCHES / "0146-composite-waits-for-scanout.patch"
FORWARD = PATCHES / "0147-forwarded-buffers-wait-for-scanout.patch"
def post_image(patch, name):
out, current = [], None
for line in patch.read_text().splitlines():
if line.startswith("+++ "):
current = line[6:] if line.startswith("+++ b/") else line[4:]
continue
if current != name or line.startswith("--- ") or line.startswith("@@"):
continue
if line.startswith("+") or line.startswith(" "):
out.append(line[1:])
elif line == "":
out.append("")
return "\n".join(out)
def block(text, start, end="\n }\n"):
begin = text.index(start)
return text[begin:text.index(end, begin) + len(end)]
PREAMBLE = r'''
#include <atomic>
#include <cassert>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <fcntl.h>
#include <mutex>
#include <poll.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <vector>
struct wl_buffer {};
static struct { void debugf(const char *, ...) {} void errorf(const char *, ...) { ++oh_no; } int oh_no = 0; } xdg_log;
namespace droiddeck::frame_trace { enum class Event { OutputRelease }; inline void Record(Event) {} }
namespace gamescope
{
PICK
class IWaitable
{
public:
virtual ~IWaitable() {}
virtual int GetFD() { return -1; }
virtual void OnPollOut() {}
virtual void OnPollHangUp() {}
};
template <typename T = int>
class CAsyncWaiter
{
public:
CAsyncWaiter( const char * ) {}
bool AddWaitable( IWaitable *p, uint32_t ) { waiting.push_back( p ); return true; }
void RemoveWaitable( IWaitable *p ) { std::erase( waiting, p ); }
std::vector<IWaitable *> waiting;
};
class CWaylandBackend;
class CBaseBackendFb
{
public:
uint32_t IncRef() { return refs++; }
uint32_t DecRef() { return --refs; }
bool ShowsClientBuffer() const { return client; }
uint32_t refs = 1;
bool client = false;
};
class CWaylandFb final : public CBaseBackendFb
{
public:
CWaylandFb( int nDmabufFd ) : m_pHostBuffer{ &m_Buffer }, m_nDmabufFd{ nDmabufFd } {}
void OnCompositorAcquire();
void OnCompositorRelease();
void OnScanoutDone( uint64_t ulAcquireSerial );
void Wayland_Buffer_Release( wl_buffer *pBuffer );
wl_buffer m_Buffer;
wl_buffer *m_pHostBuffer;
int m_nDmabufFd = -1;
std::mutex m_AcquireMutex;
uint64_t m_ulAcquireSerial = 0;
bool m_bCompositorAcquired = false;
};
SCANOUT
METHODS
}
'''
MAIN = r'''
using namespace gamescope;
static CAsyncWaiter<> &waiter() { return CWaylandScanoutRelease::Waiter(); }
struct Display {
int fds[2];
Display() { assert( pipe2( fds, O_NONBLOCK ) == 0 ); }
~Display() { close( fds[0] ); close( fds[1] ); }
void scanning() { char b[4096] = {}; while ( write( fds[1], b, sizeof( b ) ) > 0 ) {} }
void done() { char b[4096]; while ( read( fds[0], b, sizeof( b ) ) > 0 ) {} }
int fd() { return fds[1]; }
};
static void fire() {
assert( waiter().waiting.size() == 1 );
waiter().waiting.front()->OnPollOut();
assert( waiter().waiting.empty() );
}
int main( int argc, char **argv ) {
std::string which = argv[1];
Display d;
CWaylandFb fb{ fcntl( d.fd(), F_DUPFD_CLOEXEC, 0 ) };
if ( which == "client-scanning" ) {
fb.client = true;
fb.OnCompositorAcquire();
assert( fb.refs == 2 );
d.scanning();
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
assert( fb.refs == 2 && fb.m_bCompositorAcquired );
d.done();
fire();
assert( fb.refs == 1 && !fb.m_bCompositorAcquired && xdg_log.oh_no == 0 );
} else if ( which == "client-idle" ) {
fb.client = true;
fb.OnCompositorAcquire();
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
assert( fb.refs == 1 && waiter().waiting.empty() );
} else if ( which == "composite-scanning" ) {
fb.OnCompositorAcquire();
d.scanning();
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
assert( fb.refs == 1 && waiter().waiting.empty() );
} else if ( which == "shown-again" ) {
fb.client = true;
fb.OnCompositorAcquire();
d.scanning();
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
fb.OnCompositorAcquire();
d.done();
fire();
assert( fb.refs == 2 && fb.m_bCompositorAcquired );
fb.Wayland_Buffer_Release( fb.m_pHostBuffer );
assert( fb.refs == 1 && !fb.m_bCompositorAcquired && xdg_log.oh_no == 0 );
} else if ( which == "no-dmabuf" ) {
CWaylandFb plain{ -1 };
plain.client = true;
plain.OnCompositorAcquire();
plain.Wayland_Buffer_Release( plain.m_pHostBuffer );
assert( plain.refs == 1 && waiter().waiting.empty() );
} else {
return 2;
}
return 0;
}
'''
class ForwardedBufferScanoutTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cxx = shutil.which(os.environ.get("CXX", "c++"))
if not cxx:
raise AssertionError("C++ compiler required")
pick = post_image(PICK, "src/output_image_pick.hpp")
pick = pick[pick.index("struct OutputImagePick"):pick.rindex("}")]
wayland = post_image(FORWARD, "src/Backends/WaylandBackend.cpp")
scanout = block(wayland, " class CWaylandScanoutRelease", "\n };\n")
methods = "\n".join(block(wayland, " void CWaylandFb::" + name) for name in
("OnCompositorAcquire()", "OnCompositorRelease()", "OnScanoutDone(", "Wayland_Buffer_Release("))
source = PREAMBLE.replace("PICK", pick).replace("SCANOUT", scanout).replace("METHODS", methods) + MAIN
cls.tmp = tempfile.TemporaryDirectory(prefix="droiddeck-forwarded-scanout-")
cls.addClassCleanup(cls.tmp.cleanup)
probe = Path(cls.tmp.name) / "probe.cpp"
probe.write_text(source)
cls.binary = probe.with_suffix("")
built = subprocess.run([cxx, "-std=c++20", "-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter", "-UNDEBUG",
"-include", "string", str(probe), "-o", str(cls.binary)], capture_output=True, text=True)
if built.returncode:
raise AssertionError(built.stdout + built.stderr)
def scenario(self, name):
result = subprocess.run([str(self.binary), name], capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_forwarded_buffer_is_held_until_scanout_ends(self):
self.scenario("client-scanning")
def test_idle_forwarded_buffer_is_released_at_once(self):
self.scenario("client-idle")
def test_composite_output_image_keeps_the_release_at_latch(self):
self.scenario("composite-scanning")
def test_buffer_shown_again_waits_for_its_next_release(self):
self.scenario("shown-again")
def test_buffer_without_dmabuf_is_released_at_once(self):
self.scenario("no-dmabuf")
if __name__ == "__main__":
unittest.main()
+25
View File
@@ -88,6 +88,18 @@ int main(int argc, char **argv) {
printf("%s\t%s\n", argv[i], ok ? cwd : "-");
continue;
}
if (strncmp(argv[i], "cdnull:", 7) == 0) {
char *got = chdir(argv[i] + 7) == 0 ? getcwd(NULL, 0) : NULL;
printf("%s\t%s\n", argv[i], got ? got : "-");
free(got);
continue;
}
if (strncmp(argv[i], "realnull:", 9) == 0) {
char *got = realpath(argv[i] + 9, NULL);
printf("%s\t%s\n", argv[i], got ? got : "-");
free(got);
continue;
}
if (strncmp(argv[i], "lstat:", 6) == 0) {
int ok = lstat(argv[i] + 6, &st) == 0;
printf("%s\t%d\t%d\n", argv[i], ok, ok && S_ISLNK(st.st_mode));
@@ -324,6 +336,19 @@ class NativeHookMountTest(unittest.TestCase):
arg = f"cd:/pfx/native/dosdevices/z:{GAME}/"
self.assertEqual(self.run_probe(arg)[arg], [GAME])
def test_allocated_working_directory_and_real_path_name_a_longer_guest_mount(self):
guest = "/root/Games/" + "g" * len(str(self.library))
binds = f"{self.library}:{guest}"
args = [f"cd:{guest}/Some Game", f"cdnull:{guest}/Some Game", f"realnull:{guest}/Some Game/game.txt"]
result = self.run_probe(*args, binds=binds)
self.assertEqual(result[args[0]], [f"{guest}/Some Game"])
self.assertEqual(result[args[1]], [f"{guest}/Some Game"])
self.assertEqual(result[args[2]], [f"{guest}/Some Game/game.txt"])
def test_allocated_working_directory_names_a_shorter_guest_mount(self):
arg = f"cdnull:{GAME}"
self.assertEqual(self.run_probe(arg)[arg], [GAME])
def test_rootfs_path_under_a_mount_point_reaches_the_mount(self):
path = f"{self.root}{GAME}/game.txt"
self.assertEqual(self.run_probe(path)[path], ["1", "library"])
+71 -6
View File
@@ -35,13 +35,21 @@ STRUCT
static struct wl_list g_bufs;
static struct wl_event_loop *g_loop;
static int g_import_failed_logged;
static int import_ok, imports, imported_flags, deferred_releases, frees, sources;
static struct wl_event_source g_source;
static int import_ok, imports, imported_flags, deferred_releases, frees, sources, removes, merge_ok, merges;
static struct wl_event_source g_sources[4];
static struct wl_event_source *g_removed;
void wl_list_init(struct wl_list *l) { l->prev = l; l->next = l; }
void wl_list_insert(struct wl_list *l, struct wl_list *e) {
e->next = l->next; e->prev = l; l->next->prev = e; l->next = e;
}
static int fake_ioctl(int fd, unsigned long req, void *arg) {
if (req == SYNC_IOC_MERGE) {
struct sync_merge_data *m = arg;
assert(fd >= 0 && m->fd2 >= 0 && fd != m->fd2);
++merges;
if (!merge_ok) { errno = ENOTTY; return -1; }
m->fence = dup(m->fd2); return 0;
}
struct droiddeck_dma_buf_sync_file *f = arg;
(void)fd;
assert(req == DROIDDECK_DMA_BUF_IOCTL_IMPORT_SYNC_FILE);
@@ -54,13 +62,17 @@ static int droiddeck_dmabuf_fd(struct dmabuf_buffer *b) { return b->fd; }
static void droiddeck_log(const char *tag, const char *fmt, ...) { (void)tag; (void)fmt; }
static struct wl_event_source *wl_event_loop_add_fd(struct wl_event_loop *l, int fd, uint32_t m,
int (*cb)(int, uint32_t, void *), void *d) {
(void)l; (void)fd; (void)m; (void)cb; (void)d; ++sources; return &g_source;
(void)l; (void)fd; (void)m; (void)cb; (void)d; return &g_sources[sources++];
}
static void wl_event_source_remove(struct wl_event_source *s) { assert(s); ++removes; g_removed = s; }
static int on_fence_readable(int fd, uint32_t mask, void *data) { (void)fd; (void)mask; (void)data; return 0; }
static void send_deferred_release(struct ahb_buf *ab) { ++deferred_releases; ab->release_pending = 0; }
static void maybe_free(struct ahb_buf *ab) { (void)ab; ++frees; }
FUNCTIONS
static void reset(void) { import_ok = imports = imported_flags = deferred_releases = frees = sources = 0; }
static void reset(void) {
import_ok = imports = imported_flags = deferred_releases = frees = sources = removes = merge_ok = merges = 0;
g_removed = NULL;
}
static void run(int display, int can_import, int fence_signalled) {
reset();
wl_list_init(&g_bufs);
@@ -78,12 +90,48 @@ static void run(int display, int can_import, int fence_signalled) {
assert(deferred_releases == 1 && frees == 1 && !ab.fence_src && ab.fence_fd == -1);
errno = 0; assert(fcntl(fds[0], F_GETFD) == -1 && errno == EBADF);
} else {
assert(deferred_releases == 0 && sources == 1 && ab.fence_src == &g_source && ab.fence_fd == fds[0]);
assert(deferred_releases == 0 && sources == 1 && ab.fence_src == &g_sources[0] && ab.fence_fd == fds[0]);
close(fds[0]);
}
close(fds[1]);
}
static int closed(int fd) { errno = 0; return fcntl(fd, F_GETFD) == -1 && errno == EBADF; }
static void rerelease(int can_merge, int second_import, int second_signalled) {
reset();
wl_list_init(&g_bufs);
struct dmabuf_buffer b = {.fd = 7};
struct ahb_buf ab;
memset(&ab, 0, sizeof(ab));
ab.id = 42; ab.b = &b; ab.on_layer = 1; ab.release_pending = 1; ab.fence_fd = -1;
wl_list_insert(&g_bufs, &ab.link);
int first[2], second[2];
assert(pipe(first) == 0 && pipe(second) == 0);
handle_released(42, first[0]);
assert(ab.fence_src == &g_sources[0] && ab.fence_fd == first[0] && deferred_releases == 0);
ab.on_layer = 1;
if (second_signalled) assert(write(second[1], "x", 1) == 1);
import_ok = second_import; merge_ok = can_merge;
handle_released(42, second[0]);
assert(!ab.on_layer && deferred_releases == 0 && frees == 0);
if (second_import || second_signalled) {
assert(removes == 0 && merges == 0 && sources == 1 && ab.fence_src == &g_sources[0] && ab.fence_fd == first[0]);
assert(closed(second[0]));
close(first[0]);
} else {
assert(merges == 1 && removes == 1 && g_removed == &g_sources[0]);
assert(sources == 2 && ab.fence_src == &g_sources[1] && ab.fence_fd >= 0);
assert(closed(first[0]));
if (can_merge) assert(closed(second[0]) && ab.fence_fd != second[0]);
else assert(ab.fence_fd == second[0]);
close(ab.fence_fd);
}
close(first[1]); close(second[1]);
}
int main(int argc, char **argv) {
if (argc == 5 && !strcmp(argv[1], "rerelease")) {
rerelease(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]));
return 0;
}
assert(argc == 4);
run(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]));
return 0;
@@ -103,7 +151,7 @@ class ZeroCopyReleaseAtLatchTest(unittest.TestCase):
ahb, re.M))
struct = re.search(r'struct ahb_buf \{.*?\n\};', ahb, re.S).group()
functions = '\n'.join(function(ahb, n) for n in ('find_buf', 'handle_released'))
source = HARNESS.replace('DEFINES', '#include <fcntl.h>\n#include <sys/ioctl.h>\n' + defines)
source = HARNESS.replace('DEFINES', '#include <fcntl.h>\n#include <linux/sync_file.h>\n#include <sys/ioctl.h>\n' + defines)
source = source.replace('STRUCT', struct).replace('FUNCTIONS', functions)
cls.tmp = tempfile.TemporaryDirectory(prefix='droiddeck-release-latch-')
cls.addClassCleanup(cls.tmp.cleanup)
@@ -136,6 +184,23 @@ class ZeroCopyReleaseAtLatchTest(unittest.TestCase):
def test_signalled_fence_releases_without_waiting(self):
self.scenario(1, 0, 1)
def rerelease(self, can_merge, second_import, second_signalled):
result = subprocess.run([str(self.binary), 'rerelease', str(can_merge), str(second_import), str(second_signalled)],
capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
def test_second_unsignalled_fence_merges_into_the_pending_wait(self):
self.rerelease(1, 0, 0)
def test_second_unsignalled_fence_replaces_the_wait_when_merge_fails(self):
self.rerelease(0, 0, 0)
def test_second_imported_fence_keeps_the_pending_wait(self):
self.rerelease(1, 1, 0)
def test_second_signalled_fence_keeps_the_pending_wait(self):
self.rerelease(1, 0, 1)
if __name__ == '__main__':
unittest.main()
+9
View File
@@ -82,6 +82,15 @@ int vkp_effects_active(void) { return 0; }
int vkp_effects_upscaling(void) { return 0; }
int vkp_effects_sharpening(void) { return 0; }
int vkp_effects_postprocessing(void) { return 0; }
void vkp_effects_release_generated_sources(void) {}
int vkp_effects_prepare_generated(void) { assert(0); return 0; }
VkImage vkp_effects_run_before_generated(VkCommandBuffer c, VkImage i, int w, int h, int *rw, int *rh) {
assert(0); *rw = w; *rh = h; return i;
}
VkImage vkp_effects_run_generated(VkCommandBuffer c, VkImage i, int w, int h,
int ow, int oh, int slot, int *rw, int *rh) {
assert(0); *rw = w; *rh = h; return i;
}
VkFilter vkp_effects_blit_filter(void) { return VK_FILTER_NEAREST; }
void vkp_effects_set_formats(VkFormat a, VkFormat b, int scene_is_pq) {}
VkImage vkp_effects_run(VkCommandBuffer c, VkImage i, int w, int h, int ow, int oh, int *rw, int *rh) {