fix: resolve zram focus conflicts

This commit is contained in:
Kurt Himebauch committed 2026-10-26 11:45:17 -04:00
commit 36135327f5
327 files changed
+20986 -2696

No files matched your search

+359
View File
@@ -0,0 +1,359 @@
#include "framegen.hpp"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace {
constexpr int levels = 7;
constexpr VkImageUsageFlags flow_usage =
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
enum Pipeline { LUMA, DOWNSAMPLE, FLOW3, FLOW4, EXPAND3, EXPAND4, GLOBAL_MOTION, PREWARP, FLOW_REG, SYNTH };
struct Image { VkExtent3D extent; VkFormat format; VkImageUsageFlags usage; };
struct Allocation { VkDeviceSize size; std::unique_ptr<uint8_t[]> data; };
struct Binding { VkDescriptorType type; VkImageView view; VkBuffer buffer; VkDeviceSize range; };
struct Dispatch { unsigned pipeline; uint32_t x, y, z; };
std::map<VkImage, Image> images;
std::map<VkImageView, VkImage> views;
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<VkPipeline, unsigned> pipelines;
std::map<VkImage, unsigned> image_ids;
std::map<VkBuffer, unsigned> buffer_ids;
std::vector<Dispatch> dispatches;
uintptr_t serial = 100;
unsigned buffer_creates, set_creates;
VkPipeline bound_pipeline;
VkDescriptorSet bound_set;
uint64_t command_hash = 14695981039346656037ull;
template<class T> T handle() { return reinterpret_cast<T>(++serial); }
void hash(uint64_t value) {
for (unsigned i = 0; i < 8; i++) {
command_hash = (command_hash ^ (value & 255)) * 1099511628211ull;
value >>= 8;
}
}
void hash_image(VkImage image) {
assert(images.count(image));
if (!image_ids.count(image)) image_ids[image] = static_cast<unsigned>(image_ids.size() + 1);
const auto &info = images.at(image);
hash(image_ids.at(image));
hash(info.extent.width); hash(info.extent.height); hash(info.format); hash(info.usage);
}
template<class Info, class Out>
VkResult VKAPI_CALL create(VkDevice, const Info *, const VkAllocationCallbacks *, Out *out) {
*out = handle<Out>();
return VK_SUCCESS;
}
template<class T> void VKAPI_CALL destroy(VkDevice, T, const VkAllocationCallbacks *) {}
VkResult VKAPI_CALL create_image(VkDevice, const VkImageCreateInfo *info,
const VkAllocationCallbacks *, VkImage *out) {
*out = handle<VkImage>();
images[*out] = {info->extent, info->format, info->usage};
return VK_SUCCESS;
}
VkResult VKAPI_CALL create_view(VkDevice, const VkImageViewCreateInfo *info,
const VkAllocationCallbacks *, VkImageView *out) {
assert(images.count(info->image));
*out = handle<VkImageView>();
views[*out] = info->image;
return VK_SUCCESS;
}
void VKAPI_CALL destroy_image(VkDevice, VkImage image, const VkAllocationCallbacks *) {
assert(images.erase(image) == 1);
}
void VKAPI_CALL destroy_view(VkDevice, VkImageView view, const VkAllocationCallbacks *) {
assert(views.erase(view) == 1);
}
VkResult VKAPI_CALL create_buffer(VkDevice, const VkBufferCreateInfo *info,
const VkAllocationCallbacks *, VkBuffer *out) {
*out = handle<VkBuffer>();
buffers[*out] = *info;
buffer_creates++;
return VK_SUCCESS;
}
void VKAPI_CALL destroy_buffer(VkDevice, VkBuffer buffer, const VkAllocationCallbacks *) {
assert(buffers.erase(buffer) == 1);
buffer_memory.erase(buffer);
}
void VKAPI_CALL image_requirements(VkDevice, VkImage image, VkMemoryRequirements *out) {
const auto &info = images.at(image);
const uint64_t bytes = info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8;
*out = {uint64_t(info.extent.width) * info.extent.height * bytes, 1, 1};
}
void VKAPI_CALL buffer_requirements(VkDevice, VkBuffer buffer, VkMemoryRequirements *out) {
*out = {buffers.at(buffer).size, 1, 1};
}
VkResult VKAPI_CALL allocate(VkDevice, const VkMemoryAllocateInfo *info,
const VkAllocationCallbacks *, VkDeviceMemory *out) {
*out = handle<VkDeviceMemory>();
allocations[*out].size = info->allocationSize;
return VK_SUCCESS;
}
void VKAPI_CALL free_memory(VkDevice, VkDeviceMemory memory, const VkAllocationCallbacks *) {
assert(allocations.erase(memory) == 1);
}
VkResult VKAPI_CALL bind_image(VkDevice, VkImage image, VkDeviceMemory memory, VkDeviceSize) {
assert(images.count(image) && allocations.count(memory));
return VK_SUCCESS;
}
VkResult VKAPI_CALL bind_buffer(VkDevice, VkBuffer buffer, VkDeviceMemory memory, VkDeviceSize) {
assert(buffers.count(buffer) && allocations.count(memory));
buffer_memory[buffer] = memory;
return VK_SUCCESS;
}
VkResult VKAPI_CALL map_memory(VkDevice, VkDeviceMemory memory, VkDeviceSize offset,
VkDeviceSize size, VkMemoryMapFlags, void **out) {
auto &allocation = allocations.at(memory);
assert(offset == 0 && size <= allocation.size);
allocation.data = std::make_unique<uint8_t[]>(allocation.size);
*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 memory_properties(VkPhysicalDevice, VkPhysicalDeviceMemoryProperties *out) {
*out = {};
out->memoryTypeCount = 1;
out->memoryTypes[0].propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
}
VkResult VKAPI_CALL allocate_sets(VkDevice, const VkDescriptorSetAllocateInfo *info, VkDescriptorSet *out) {
for (uint32_t i = 0; i < info->descriptorSetCount; i++) {
out[i] = handle<VkDescriptorSet>();
descriptors[out[i]] = {};
set_creates++;
}
return VK_SUCCESS;
}
VkResult VKAPI_CALL reset_pool(VkDevice, VkDescriptorPool, VkDescriptorPoolResetFlags) {
descriptors.clear();
return VK_SUCCESS;
}
void VKAPI_CALL update_sets(VkDevice, uint32_t count, const VkWriteDescriptorSet *writes,
uint32_t, const VkCopyDescriptorSet *) {
for (uint32_t i = 0; i < count; i++) {
const auto &write = writes[i];
assert(descriptors.count(write.dstSet) && write.descriptorCount == 1);
Binding binding{write.descriptorType, VK_NULL_HANDLE, VK_NULL_HANDLE, 0};
if (write.pImageInfo) {
binding.view = write.pImageInfo->imageView;
assert(views.count(binding.view));
} else {
binding.buffer = write.pBufferInfo->buffer;
binding.range = write.pBufferInfo->range;
assert(buffers.count(binding.buffer));
}
descriptors.at(write.dstSet)[write.dstBinding] = binding;
}
}
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());
out[i] = handle<VkPipeline>();
pipelines[out[i]] = index;
}
return VK_SUCCESS;
}
void VKAPI_CALL bind_pipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline pipeline) {
assert(pipelines.count(pipeline));
bound_pipeline = pipeline;
}
void VKAPI_CALL bind_sets(VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout,
uint32_t, uint32_t count, const VkDescriptorSet *sets,
uint32_t, const uint32_t *) {
assert(count == 1 && descriptors.count(sets[0]));
bound_set = sets[0];
}
void VKAPI_CALL dispatch(VkCommandBuffer, uint32_t x, uint32_t y, uint32_t z) {
const unsigned pipeline = pipelines.at(bound_pipeline);
dispatches.push_back({pipeline, x, y, z});
hash(1); hash(pipeline); hash(x); hash(y); hash(z);
for (const auto &[slot, binding] : descriptors.at(bound_set)) {
hash(slot); hash(binding.type);
if (binding.view) {
hash_image(views.at(binding.view));
} else {
if (!buffer_ids.count(binding.buffer))
buffer_ids[binding.buffer] = static_cast<unsigned>(buffer_ids.size() + 1);
const auto &allocation = allocations.at(buffer_memory.at(binding.buffer));
const auto size = binding.range == VK_WHOLE_SIZE ? allocation.size : binding.range;
assert(allocation.data && size <= allocation.size);
hash(buffer_ids.at(binding.buffer)); hash(size);
for (VkDeviceSize i = 0; i < size; i++) hash(allocation.data[i]);
}
}
}
void VKAPI_CALL barrier(VkCommandBuffer, VkPipelineStageFlags src, VkPipelineStageFlags dst,
VkDependencyFlags flags, uint32_t nm, const VkMemoryBarrier *memory,
uint32_t nb, const VkBufferMemoryBarrier *, uint32_t ni,
const VkImageMemoryBarrier *image) {
assert(nb == 0);
hash(2); hash(src); hash(dst); hash(flags); hash(nm); hash(ni);
for (uint32_t i = 0; i < nm; i++) {
hash(memory[i].srcAccessMask); hash(memory[i].dstAccessMask);
}
for (uint32_t i = 0; i < ni; i++) {
hash_image(image[i].image);
hash(image[i].oldLayout); hash(image[i].newLayout);
hash(image[i].srcAccessMask); hash(image[i].dstAccessMask);
hash(image[i].srcQueueFamilyIndex); hash(image[i].dstQueueFamilyIndex);
}
}
void VKAPI_CALL clear_image(VkCommandBuffer, VkImage image, VkImageLayout layout,
const VkClearColorValue *color, uint32_t count, const VkImageSubresourceRange *) {
assert(count == 1);
hash(3); hash_image(image); hash(layout);
for (unsigned i = 0; i < 4; i++) hash(color->uint32[i]);
}
void VKAPI_CALL copy_image(VkCommandBuffer, VkImage src, VkImageLayout sl, VkImage dst,
VkImageLayout dl, uint32_t count, const VkImageCopy *region) {
assert(count == 1);
hash(4); hash_image(src); hash(sl); hash_image(dst); hash(dl);
hash(region->extent.width); hash(region->extent.height); hash(region->extent.depth);
}
uint32_t dimension(uint32_t full, int level) { return std::max(full >> level, 1u); }
void check_images(uint32_t width, uint32_t height, int finest) {
assert(images.size() == static_cast<size_t>(32 - 2 * finest));
for (int level = finest; level < levels; level++) {
const auto w = dimension(width, level), h = dimension(height, level);
assert(std::any_of(images.begin(), images.end(), [=](const auto &entry) {
const auto &image = entry.second;
return image.format == VK_FORMAT_R16G16B16A16_SFLOAT && image.usage == flow_usage &&
image.extent.width == w && image.extent.height == h;
}));
}
}
VkImageView external_image(uint32_t width, uint32_t height) {
VkImage image = handle<VkImage>();
VkImageView view = handle<VkImageView>();
images[image] = {{width, height, 1}, VK_FORMAT_R8G8B8A8_UNORM,
VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT};
views[view] = image;
return view;
}
void record(ddfg::FrameGen &fg, int model, uint32_t width, uint32_t height, unsigned generations) {
const auto previous = external_image(width, height), current = external_image(width, height);
const auto first = dispatches.size();
for (unsigned i = 0; i < generations; i++)
fg.record(reinterpret_cast<VkCommandBuffer>(1), previous, current, external_image(width, height),
float(i + 1) / float(generations + 1), 0, i, i != 0);
std::vector<Dispatch> expected;
auto add = [&](unsigned pipeline, int level) {
expected.push_back({pipeline, (dimension(width, level) + 15) / 16,
(dimension(height, level) + 15) / 16, 1});
};
add(LUMA, 0); add(LUMA, 0);
for (int level = 1; level < levels; level++) { add(DOWNSAMPLE, level); add(DOWNSAMPLE, level); }
expected.push_back({GLOBAL_MOTION, 8, 1, 1});
for (int level = fg.flowFinest(); level < levels; level++) add(PREWARP, level);
for (int level = levels - 1; level >= fg.flowFinest(); level--) add(model == 4 ? FLOW4 : FLOW3, level);
for (int i = 0; i < 4; i++) add(FLOW_REG, fg.flowFinest());
add(model == 4 ? EXPAND4 : EXPAND3, 0);
for (unsigned i = 0; i < generations; i++) add(SYNTH, 0);
assert(dispatches.size() - first == expected.size());
for (size_t i = 0; i < expected.size(); i++) {
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;
}
}
}
int main(int argc, char **argv) {
assert(argc == 8);
const std::string mode = argv[1];
const int model = std::atoi(argv[2]), preset = std::atoi(argv[3]);
uint32_t width = static_cast<uint32_t>(std::atoi(argv[4]));
uint32_t height = static_cast<uint32_t>(std::atoi(argv[5]));
const unsigned generations = static_cast<unsigned>(std::atoi(argv[6]));
const unsigned repeats = static_cast<unsigned>(std::atoi(argv[7]));
assert((model == 3 || model == 4) && preset >= 0 && preset <= 2);
assert(width && height && generations >= 1 && generations <= 3 && repeats > 0);
ddfg::DeviceDispatch dd;
ddfg::InstanceDispatch id;
id.GetPhysicalDeviceMemoryProperties = memory_properties;
dd.CreateImage = create_image; dd.DestroyImage = destroy_image;
dd.CreateImageView = create_view; dd.DestroyImageView = destroy_view;
dd.CreateBuffer = create_buffer; dd.DestroyBuffer = destroy_buffer;
dd.GetImageMemoryRequirements = image_requirements; dd.GetBufferMemoryRequirements = buffer_requirements;
dd.AllocateMemory = allocate; dd.FreeMemory = free_memory;
dd.BindImageMemory = bind_image; dd.BindBufferMemory = bind_buffer;
dd.MapMemory = map_memory; dd.UnmapMemory = unmap; dd.DeviceWaitIdle = idle;
dd.CreateSampler = create<VkSamplerCreateInfo, VkSampler>; dd.DestroySampler = destroy<VkSampler>;
dd.CreateShaderModule = create<VkShaderModuleCreateInfo, VkShaderModule>;
dd.DestroyShaderModule = destroy<VkShaderModule>;
dd.CreateDescriptorSetLayout = create<VkDescriptorSetLayoutCreateInfo, VkDescriptorSetLayout>;
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.AllocateDescriptorSets = allocate_sets; dd.UpdateDescriptorSets = update_sets;
dd.CreateComputePipelines = create_pipelines; dd.DestroyPipeline = destroy<VkPipeline>;
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)));
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));
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") {
assert(buffer_creates - old_buffers == static_cast<unsigned>(15 - fg.flowFinest()));
assert(set_creates - old_sets == static_cast<unsigned>(54 - 4 * fg.flowFinest()));
}
if (repeat + 1 == repeats) break;
if (mode == "resize") {
width += 17; height += 9;
assert(fg.onResize({width, height}, VK_FORMAT_R8G8B8A8_UNORM));
} else if (mode == "preset") {
cfg.perfPreset = (cfg.perfPreset + 1) % 3;
fg.configure(cfg);
} else {
assert(mode == "record");
}
}
uint64_t bytes = 0;
for (const auto &[image, info] : images) {
(void)image;
bytes += uint64_t(info.extent.width) * info.extent.height *
(info.format == VK_FORMAT_R32_SFLOAT ? 4 : 8);
}
std::printf("PASS images=%zu bytes=%llu buffers=%u sets=%u dispatches=%zu trace=%016llx\n",
images.size(), static_cast<unsigned long long>(bytes), buffer_creates, set_creates,
dispatches.size(), static_cast<unsigned long long>(command_hash));
fg.destroy();
assert(images.empty() && views.empty());
}
File diff suppressed because it is too large. Load diff
+47 -2
View File
@@ -28,6 +28,7 @@ class ClientZramFocusTest(unittest.TestCase):
_bl_since=-1 _bl_packed=-1
_bl_pids=(123)
bl_game_focused() { [ "$focused" = 1 ]; }
bl_over_cap() { return 1; }
bl_zram_send() { echo "send:$1"; }
tick() {
SECONDS=$1 _bl_game=$2 focused=$3
@@ -44,8 +45,50 @@ tick 60 0 0
'''
result = run_bash(harness)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['refocus:-1', 'send:1', 'send:0'], result.stdout.splitlines())
def monitor_harness(self):
source = SCRIPT.read_text()
start = source.index(' bl_zram_scan\n if bl_cap_due; then')
stop = source.index(' nap 5', start)
return '''
_bl_since=-1 _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
_bl_pids=(123)
bl_zram_scan() { :; }
bl_game_focused() { [ "$focused" = 1 ]; }
bl_cap_due() { [ "$cap_due" = 1 ]; }
bl_over_cap() { [ "$over_cap" = 1 ]; }
bl_zram_send() { echo "send:$1:$3"; }
tick() {
SECONDS=$1 _bl_game=$2 focused=$3 over_cap=$4 cap_due=$5
''' + source[start:stop] + '\n}\n'
def test_client_toggle_still_disables_automatic_compression(self):
result = run_bash(self.monitor_harness() + '''
BL_ZRAM_CLIENT=0
tick 0 1 1 0 0
tick 25 1 1 0 0
tick 30 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual('', result.stdout)
def test_game_exit_defers_restore_until_the_session_is_under_the_ram_cap(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
tick 20 1 1 0 0
tick 25 1 0 0 0
tick 30 0 0 1 0
echo "deferred:$_bl_unpack:$_bl_packed"
tick 35 0 0 0 1
echo "restored:$_bl_unpack"
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'deferred:1:-1', 'send:0:client', 'restored:0'], result.stdout.splitlines())
def test_scan_keeps_the_running_game_and_ignores_steams_own_reaper(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
@@ -53,10 +96,12 @@ tick 60 0 0
self.write_cmd(root, 10, ['/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=769', '--'])
self.write_cmd(root, 20, ['/usr/bin/FEX', '/usr/lib/steam/reaper', 'SteamLaunch', 'AppId=1245620', '--'])
self.write_cmd(root, 30, ['/home/deck/.local/share/Steam/steamrtarm64/steam'])
self.write_cmd(root, 40, ['/usr/bin/wine', 'game.exe'])
self.write_cmd(root, 50, ['/usr/bin/FEXInterpreter', '/usr/bin/steamwebhelper'])
scan = function_source('bl_zram_scan').replace('for _d in /proc/[0-9]*', 'for _d in "$FAKE"/[0-9]*')
result = run_bash('FAKE=%s\n%s\nbl_zram_scan\necho "game=$_bl_game"\necho "apps=${_bl_apps# }"\necho "pids=${_bl_pids[*]}"' % (root, scan))
result = run_bash('FAKE=%s\n%s\nbl_zram_scan\necho "game=$_bl_game"\necho "apps=${_bl_apps# }"\necho "pids=${_bl_pids[*]}"\necho "others=${_bl_others[*]}"' % (root, scan))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(['game=1', 'apps=1245620', 'pids=30'], result.stdout.splitlines())
self.assertEqual(['game=1', 'apps=1245620', 'pids=30 50', 'others=40'], result.stdout.splitlines())
def test_focus_must_be_the_running_game(self):
focus = function_source('bl_game_focused')
+102
View File
@@ -0,0 +1,102 @@
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
CHAIN = ROOT / "app/src/main/cpp/framegen/ddfg"
class DdfgFlowLevelsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
compiler = shutil.which(os.environ.get("CXX", "c++"))
if compiler is None:
raise unittest.SkipTest("A host C++ compiler is required")
candidates = [Path("/usr/include/vulkan"), Path("/opt/homebrew/include/vulkan")]
for key in ("ANDROID_NDK_HOME", "ANDROID_NDK_ROOT", "NDK_HOME"):
if os.environ.get(key):
candidates.extend(Path(os.environ[key]).glob("toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan"))
for sdk in {Path(os.environ.get("ANDROID_HOME", "/nonexistent")),
Path(os.environ.get("ANDROID_SDK_ROOT", "/nonexistent")),
Path.home() / "Library/Android/sdk", Path.home() / "Android/Sdk"}:
candidates.extend(sdk.glob("ndk/*/toolchains/llvm/prebuilt/*/sysroot/usr/include/vulkan"))
headers = next((p for p in candidates if (p / "vulkan.h").is_file()), None)
if headers is None:
raise unittest.SkipTest("Vulkan headers from the Android NDK or system SDK are required")
cls.temp = tempfile.TemporaryDirectory(prefix="droiddeck-ddfg-levels-")
cls.addClassCleanup(cls.temp.cleanup)
work = Path(cls.temp.name)
shutil.copytree(headers, work / "include/vulkan", ignore=shutil.ignore_patterns("*.hpp"))
if (headers.parent / "vk_video").is_dir():
shutil.copytree(headers.parent / "vk_video", work / "include/vk_video")
cls.binary = work / "ddfg-flow-levels"
build = subprocess.run([
compiler, "-std=c++17", "-O2", "-Wall", "-Wextra",
"-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"),
"-o", str(cls.binary),
], capture_output=True, text=True, timeout=120)
if build.returncode:
raise RuntimeError(build.stdout + build.stderr)
def run_case(self, mode="resources", model=4, preset=2, width=1280, height=720, generations=1, repeats=1):
result = subprocess.run([
str(self.binary), mode, str(model), str(preset), str(width), str(height),
str(generations), str(repeats),
], capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertTrue(result.stdout.startswith("PASS "), result.stdout)
return dict(re.findall(r"(\w+)=(\w+)", result.stdout))
def test_each_model_and_preset_allocates_only_solved_flow_levels(self):
for model in (3, 4):
for preset, finest in enumerate((1, 2, 3)):
with self.subTest(model=model, preset=preset):
values = self.run_case(model=model, preset=preset)
self.assertEqual(int(values["images"]), 32 - 2 * finest)
self.assertEqual(int(values["buffers"]), 18 - finest)
self.assertEqual(int(values["sets"]), 54 - 4 * finest)
def test_default_preset_saves_the_exact_high_resolution_flow_payload(self):
for width, height in ((1280, 720), (1920, 1080), (2560, 1440)):
with self.subTest(width=width, height=height):
values = self.run_case(width=width, height=height)
pixels = lambda level: max(width >> level, 1) * max(height >> level, 1)
luma_bytes = 4 * (2 * sum(pixels(l) for l in range(7)) +
sum(pixels(l) for l in range(3, 7)))
flow_bytes = 8 * (sum(pixels(l) for l in range(3, 7)) +
2 * width * height + 2 * pixels(3))
self.assertEqual(int(values["bytes"]), luma_bytes + flow_bytes)
def test_small_and_odd_extents_keep_valid_bindings_and_dispatch_sizes(self):
for width, height in ((1, 1), (17, 9), (135, 73)):
for preset in range(3):
with self.subTest(width=width, height=height, preset=preset):
self.run_case(width=width, height=height, preset=preset)
def test_two_three_and_four_times_generation_keep_the_same_dispatch_schedule(self):
for model in (3, 4):
for preset in range(3):
for generations in (1, 2, 3):
with self.subTest(model=model, preset=preset, generations=generations):
self.run_case("record", model=model, preset=preset, generations=generations, repeats=3)
def test_resize_rebuilds_every_solved_level(self):
for preset in range(3):
with self.subTest(preset=preset):
self.run_case("resize", preset=preset, generations=3, repeats=3)
def test_live_preset_changes_rebuild_the_level_range(self):
for model in (3, 4):
with self.subTest(model=model):
self.run_case("preset", model=model, generations=3, repeats=4)
if __name__ == "__main__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
GPU = TOOLS / "linuxfs/desktop/droiddeck-gpu"
WINDOW = TOOLS / "linuxfs/overlay/usr/local/bin/droiddeck-gpu-window"
KEYS = ("MESA_VK_WSI_DEBUG", "SDL_VIDEODRIVER", "WAYLAND_DISPLAY", "BL_GPU_CHILD_WSI", "BL_DESKTOP_GPU_CHILD")
class DesktopGpuWindowTest(unittest.TestCase):
def setUp(self):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
self.out = self.tmp / "gamescope.json"
fake = self.tmp / "gamescope"
fake.write_text("#!%s\nimport json, os, sys\njson.dump({'args': sys.argv[1:], 'env': {k: os.environ.get(k) for k in %r}}, open(%r, 'w'))\n"
% (sys.executable, KEYS, str(self.out)))
fake.chmod(0o755)
def run_gpu(self, **env):
base = {k: v for k, v in os.environ.items() if k not in KEYS + ("BL_DEBUG_DIR", "BL_DESKTOP_GPU_WINDOW")}
base.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), BL_WIDTH="1280", BL_HEIGHT="720", **env)
subprocess.run(["bash", str(GPU), "game.exe"], env=base, check=True, capture_output=True)
return json.loads(self.out.read_text())
def test_on_the_desktop_the_game_gets_a_window_of_its_own(self):
run = self.run_gpu(WAYLAND_DISPLAY="wayland-1", MESA_VK_WSI_DEBUG="sw,linear")
self.assertEqual(run["args"][:2], ["--backend", "sdl"])
self.assertNotIn("-f", run["args"])
self.assertEqual(run["args"][-2:], ["/usr/local/bin/droiddeck-gpu-window", "game.exe"])
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-1")
self.assertEqual(run["env"]["SDL_VIDEODRIVER"], "wayland")
self.assertEqual(run["env"]["MESA_VK_WSI_DEBUG"], "sw")
self.assertEqual(run["env"]["BL_GPU_CHILD_WSI"], "linear")
self.assertEqual(run["env"]["BL_DESKTOP_GPU_CHILD"], "1")
def test_full_screen_stays_available(self):
for env in ({"WAYLAND_DISPLAY": "wayland-1", "BL_DESKTOP_GPU_WINDOW": "0"}, {"WAYLAND_DISPLAY": "wayland-0"}, {}):
run = self.run_gpu(**env)
self.assertEqual(run["args"][:2], ["--backend", "wayland"])
self.assertIn("-f", run["args"])
self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-0")
self.assertIsNone(run["env"]["MESA_VK_WSI_DEBUG"])
self.assertIsNone(run["env"]["BL_GPU_CHILD_WSI"])
def test_the_game_inside_the_window_gets_its_own_settings_back(self):
script = "import json, os; print(json.dumps({k: os.environ.get(k) for k in %r}))" % (KEYS,)
for saved, expected in (("linear", "linear"), ("", None)):
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)}
env.update(BL_GPU_CHILD_WSI=saved, MESA_VK_WSI_DEBUG="sw", SDL_VIDEODRIVER="wayland")
out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env,
check=True, capture_output=True, text=True).stdout
child = json.loads(out)
self.assertEqual(child["MESA_VK_WSI_DEBUG"], expected)
self.assertEqual(child["SDL_VIDEODRIVER"], "x11")
self.assertIsNone(child["BL_GPU_CHILD_WSI"])
def test_outside_a_window_the_game_keeps_its_settings(self):
script = "import os; print(os.environ.get('MESA_VK_WSI_DEBUG'), os.environ.get('SDL_VIDEODRIVER'))"
env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)}
env.update(MESA_VK_WSI_DEBUG="linear", SDL_VIDEODRIVER="x11")
out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env,
check=True, capture_output=True, text=True).stdout.split()
self.assertEqual(out, ["linear", "x11"])
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -456,6 +456,15 @@ class ProtonRunTest(Temp):
("0", "0", str(appid << 32 | 0x02000000), "1"))
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(self.root / ("steamapps/compatdata/%d" % appid)))
def test_a_window_draws_with_the_desktops_software_gl(self):
target = RUN["Target"]("2596113170", "/c", "/i", str(self.root), "fixed")
session = {"MESA_LOADER_DRIVER_OVERRIDE": "zink", "GALLIUM_DRIVER": "zink", "LIBGL_KOPPER_DRI2": "true"}
env = RUN["environment"](session, target, "/tool", str(self.root), window=True)
self.assertEqual((env["LIBGL_ALWAYS_SOFTWARE"], env["GALLIUM_DRIVER"]), ("1", "llvmpipe"))
self.assertNotIn("MESA_LOADER_DRIVER_OVERRIDE", env)
self.assertNotIn("LIBGL_KOPPER_DRI2", env)
self.assertEqual(RUN["environment"](session, target, "/tool", str(self.root))["GALLIUM_DRIVER"], "zink")
def test_a_steam_game_keeps_its_own_id(self):
target = RUN["Target"]("413150", "/c", "/i", str(self.root), "steam")
env = RUN["environment"]({"PROTON_USE_WINED3D": "0"}, target, "/tool", str(self.root), window=True)
@@ -465,6 +474,13 @@ class ProtonRunTest(Temp):
self.assertEqual(RUN["arguments"]("/root/x/setup.msi", ["/qn"]), ["msiexec", "/i", "Z:\\root\\x\\setup.msi", "/qn"])
self.assertEqual(RUN["arguments"]("/root/x/a.exe", ["-w"]), ["/root/x/a.exe", "-w"])
def test_a_virtual_desktop_runs_the_program_by_its_windows_path(self):
pfx = "/root/Steam/steamapps/compatdata/2596113170"
self.assertEqual(RUN["arguments"](pfx + "/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe", [], "1280x720", pfx),
["explorer.exe", "/desktop=droiddeck,1280x720", "C:\\Program Files (x86)\\Battle.net\\Battle.net Launcher.exe"])
self.assertEqual(RUN["arguments"]("/root/.cache/setup.exe", ["--lang=enUS"], "1920x1080", pfx),
["explorer.exe", "/desktop=droiddeck,1920x1080", "Z:\\root\\.cache\\setup.exe", "--lang=enUS"])
def test_a_games_own_program_is_left_to_steam(self):
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW}))
self.assertEqual(RUN["compat"]()["launch_programs"](STARDEW["config"]),
@@ -554,6 +570,50 @@ class ProtonRunTest(Temp):
self.game("70", "Linux Game", "run.sh")
self.assertEqual(self.run_main(["--app", "70"])[0], 2)
def test_without_steam_a_shortcut_reuses_a_signed_prefix_folder(self):
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
start = self.tmp / "Games/Epic/Game/Binaries"
start.mkdir()
signed = self.root / "steamapps/compatdata/-1561598272"
signed.mkdir(parents=True)
code, calls, dirs = self.run_main(["--app", "2733369024", "--dir", str(start), "--", str(bat)])
self.assertIsNone(code)
env = calls[0][2]
self.assertEqual(env["STEAM_COMPAT_DATA_PATH"], str(signed))
self.assertFalse((self.root / "steamapps/compatdata/2733369024").exists())
def test_prefix_folder_prefers_initialized_unsigned_over_empty_signed(self):
signed = self.root / "steamapps/compatdata/-1561598272"
signed.mkdir(parents=True)
initialized = self.root / "steamapps/compatdata/2733369024/pfx"
initialized.mkdir(parents=True)
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
def test_prefix_folder_prefers_initialized_signed_over_empty_unsigned(self):
unsigned = self.root / "steamapps/compatdata/2733369024"
unsigned.mkdir(parents=True)
initialized = self.root / "steamapps/compatdata/-1561598272/pfx"
initialized.mkdir(parents=True)
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(initialized.parent))
def test_prefix_folder_prefers_unsigned_when_initialization_ties(self):
unsigned = self.root / "steamapps/compatdata/2733369024/pfx"
unsigned.mkdir(parents=True)
signed = self.root / "steamapps/compatdata/-1561598272/pfx"
signed.mkdir(parents=True)
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024), str(unsigned.parent))
def test_prefix_folder_skips_numeric_names_too_long_to_convert(self):
from unittest.mock import patch
folder = self.root / "steamapps/compatdata"
folder.mkdir(parents=True)
with patch.object(RUN["os"], "listdir", return_value=["9" * 5000]):
self.assertEqual(RUN["prefix_folder"](str(self.root), 2733369024),
str(folder / "2733369024"))
def test_without_steam_a_shortcut_keeps_its_prefix_folder_and_launch_options(self):
bat = self.write("Games/Epic/Game/.droiddeck-launch.bat", b"@echo off")
start = self.tmp / "Games/Epic/Game/Binaries"
@@ -568,6 +628,43 @@ class ProtonRunTest(Temp):
self.assertTrue((self.root / "steamapps/compatdata/2733369024").is_dir())
self.assertEqual(dirs, [str(start)])
def write_account(self):
self.write("Steam/config/loginusers.vdf",
'"users"\n{\n\t"76561198352563669"\n\t{\n\t\t"MostRecent"\t\t"1"\n\t}\n}\n')
return "Steam/userdata/392297941/config/"
def test_without_steam_and_options_a_game_takes_its_steam_launch_options(self):
config = self.write_account()
self.write(config + "localconfig.vdf", '"UserLocalConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n'
'\t\t\t"Steam"\n\t\t\t{\n\t\t\t\t"apps"\n\t\t\t\t{\n\t\t\t\t\t"413150"\n\t\t\t\t\t{\n'
'\t\t\t\t\t\t"cloud"\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t"LaunchOptions"\t\t"-wrong"\n\t\t\t\t\t\t}\n'
'\t\t\t\t\t\t"LaunchOptions"\t\t"DXVK_HUD=1 %command% -d3d9 \\"-name=Two Words\\""\n'
'\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
shortcuts = runpy.run_path(str(BIN / "droiddeck-steam-shortcuts"))
self.write(config + "shortcuts.vdf", shortcuts["write"]({"shortcuts": {
"0": {"appid": -1561598272, "AppName": "Batman", "LaunchOptions": "-d3d9"},
"1": {"appid": -1, "AppName": "Other", "LaunchOptions": "-x"},
}}))
root = str(self.root)
self.assertEqual(RUN["steam_options"]("413150", root), 'DXVK_HUD=1 %command% -d3d9 "-name=Two Words"')
self.assertEqual(RUN["steam_options"]("2733369024", root), "-d3d9")
self.assertEqual(RUN["steam_options"]("70", root), "")
self.assertEqual(RUN["steam_options"]("2733369025", root), "")
info = {"common": {"type": "Game"}, "config": {"launch": {
"0": {"executable": "Game.exe", "type": "default", "config": {"oslist": "windows"}}}}}
self.write("Steam/appcache/appinfo.vdf", appinfo({413150: info}))
program = self.game("413150", "Some Game", "Game.exe")
code, calls, _ = self.run_main(["--app", "413150"])
self.assertIsNone(code)
_, argv, env = calls[0]
self.assertEqual(argv[1:], ["waitforexitandrun", str(program), "-d3d9", "-name=Two Words"])
self.assertEqual(env["DXVK_HUD"], "1")
bat = self.write("Games/GOG/Batman/Batman.exe", b"MZ")
code, calls, _ = self.run_main(["--app", "2733369024", "--", str(bat)])
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat), "-d3d9"])
code, calls, _ = self.run_main(["--app", "2733369024", "--options", "", "--", str(bat)])
self.assertEqual(calls[0][1][1:], ["waitforexitandrun", str(bat)])
def test_launch_options_split_like_steam_does(self):
split = RUN["split_options"]
self.assertEqual(split(""), ({}, []))
+12
View File
@@ -47,6 +47,8 @@ elif a[:1] == ["shell"]:
s.setdefault("log_commands", []).append(a)
p.write_text(json.dumps(s))
if "ls" in a: print(s["session"])
elif a[-1].endswith("/device.txt"): print(s.get("report", ""))
elif a[-1].endswith("/app.log"): print(s.get("app_log", ""))
else: print("package not debuggable")
'''
@@ -112,6 +114,16 @@ class DeviceSmokeTest(unittest.TestCase):
self.assertEqual(1, result.returncode, result.stdout)
self.assertIn("could not launch", result.stdout)
def test_fast_path_requires_a_session_activation_log(self):
for active in (False, True):
with self.subTest(active=active):
result, _ = self.run_smoke(
session="session", report="proot fast path (eligible) true",
app_log="proot: fast path on (66 binds)" if active else "proot: fast path off - too many binds",
)
self.assertEqual(0, result.returncode, result.stdout + result.stderr)
self.assertEqual(active, "PASS proot fast path was on" in result.stdout)
def test_session_name_remains_one_remote_argument(self):
session = "x';id;#"
result, state = self.run_smoke(session=session)
@@ -0,0 +1,95 @@
import json
import runpy
import tempfile
import unittest
from pathlib import Path
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"))
TOOL = COMPAT["TOOL"]
OLD = {"name": "DroidDeck-Proton-11-11.2", "display": "DroidDeck-Proton 11-11.2", "dir": "DroidDeck-Proton 11-11.2", "valve": False}
NEW = {"name": "DroidDeck-Proton-11-11.4", "display": "DroidDeck-Proton 11-11.4", "dir": "DroidDeck-Proton 11-11.4", "valve": False}
VALVE = {"name": TOOL, "display": "Proton Experimental ARM64", "dir": "Proton - Experimental (ARM64)", "valve": True}
GE = {"name": "GE-Proton11-7", "display": "GE-Proton11-7", "dir": "GE-Proton11-7", "valve": False}
def config_text(entries):
mapping = "".join('"%s" { "name" "%s" "config" "" "priority" "%s" }' % (app, name, "75" if app == "0" else "250") for app, name in entries)
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
class DroidDeckProtonDefaultTest(unittest.TestCase):
def run_default(self, state, mapping, catalog, apps=(), request=None, settle=True):
with tempfile.TemporaryDirectory() as tmp:
directory = Path(tmp)
(directory / "state.json").write_text(json.dumps(state))
if request is not None:
(directory / "request.json").write_text(json.dumps(request))
config = directory / "config.vdf"
config.write_text(config_text(mapping))
default = COMPAT["register_default"](str(config), list(apps), catalog=catalog, directory=str(directory), settle=settle)
return default, COMPAT["read_config_mapping"](str(config)), json.loads((directory / "state.json").read_text())
def test_a_replacement_seen_while_steam_runs_still_moves_the_default_later(self):
_, mapping, state = self.run_default(
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", OLD["name"])], [VALVE, NEW], settle=False)
self.assertEqual(state["tools"], [VALVE, NEW])
self.assertIn(OLD["name"], state["own_builds"])
default, mapping, state = self.run_default(state, [("0", OLD["name"])], [VALVE, NEW])
self.assertEqual(default, NEW["name"])
self.assertEqual(mapping, {"0": NEW["name"]})
def test_a_valve_default_picked_in_steam_after_a_replacement_is_kept(self):
default, mapping, _ = self.run_default(
{"default": OLD["name"], "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL)], [VALVE, NEW])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
def test_the_first_start_with_droiddeck_proton_makes_it_the_default_for_following_titles(self):
default, mapping, state = self.run_default(
{"default": TOOL, "auto": {"42": TOOL}}, [("0", TOOL), ("42", TOOL), ("43", TOOL)], [VALVE, NEW], ["42", "43"])
self.assertEqual(default, NEW["name"])
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": TOOL})
self.assertEqual(state["default"], NEW["name"])
self.assertTrue(state["own_proton"])
def test_a_default_picked_after_the_switch_is_kept(self):
default, mapping, state = self.run_default(
{"default": NEW["name"], "own_proton": True, "applied": 1, "tools": [VALVE, NEW]},
[("0", NEW["name"])], [VALVE, NEW], request={"seq": 2, "valve": True, "dir": VALVE["dir"]})
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
default, mapping, state = self.run_default(
{"default": TOOL, "own_proton": True, "tools": [VALVE, NEW]}, [("0", TOOL)], [VALVE, NEW])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
def test_a_replaced_build_moves_its_default_and_titles_to_the_newest(self):
default, mapping, state = self.run_default(
{"default": OLD["name"], "own_proton": True, "auto": {"42": OLD["name"]}, "tools": [VALVE, OLD, GE]},
[("0", OLD["name"]), ("42", OLD["name"]), ("43", OLD["name"]), ("44", GE["name"]), ("45", TOOL)],
[VALVE, NEW, GE], ["42", "43", "44", "45"])
self.assertEqual(default, NEW["name"])
self.assertEqual(mapping, {"0": NEW["name"], "42": NEW["name"], "43": NEW["name"], "44": GE["name"], "45": TOOL})
self.assertEqual(state["auto"], {"42": NEW["name"]})
def test_a_replaced_build_does_not_override_a_valve_default(self):
default, mapping, _ = self.run_default(
{"default": TOOL, "own_proton": True, "tools": [VALVE, OLD]}, [("0", TOOL), ("43", OLD["name"])], [VALVE, NEW], ["43"])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL, "43": NEW["name"]})
def test_nothing_changes_without_droiddeck_proton(self):
default, mapping, state = self.run_default({"default": TOOL}, [("0", TOOL)], [VALVE, GE])
self.assertEqual(default, TOOL)
self.assertEqual(mapping, {"0": TOOL})
self.assertNotIn("own_proton", state)
def test_the_newest_build_is_found_by_version(self):
newest, gone = COMPAT["own_proton_moves"]({"tools": [OLD]}, [dict(NEW, name="a", dir="DroidDeck-Proton 11-9.10"), dict(NEW, name="b", dir="DroidDeck-Proton 11-11.1")])
self.assertEqual(newest, "b")
self.assertEqual(gone, {OLD["name"]})
if __name__ == "__main__":
unittest.main()
+15
View File
@@ -413,6 +413,21 @@ class DroiddeckctlTest(FakeAdbTest):
self.assertEqual("Awake", out["wakefulness"])
self.assertIn(["shell", "input", "keyevent", "KEYCODE_WAKEUP"], [c["args"] for c in self.calls()])
def test_proot_profile_queues_only_the_next_session(self):
self.configure({"env": {"ok": True}})
code, out = self.run_ctl("proot-profile", "enable", "--slow-us", "250")
self.assertEqual(0, code, out)
self.assertEqual({"op": "set", "lines": ["PROOT_PROFILE=1", "PROOT_PROFILE_SLOW_US=250"], "persistent": False},
self.calls("env")[0]["request"])
def test_proot_profile_report_needs_no_adb_or_device(self):
path = self.dir / "session.log"
path.write_text('ordinary log')
with unittest.mock.patch.object(ctl, "adb_path", side_effect=AssertionError("must stay offline")):
code, out = self.run_ctl("proot-profile", "report", str(path))
self.assertEqual(0, code, out)
self.assertFalse(out["hasCounters"])
def test_override_pushes_to_the_inbox_first(self):
self.configure({
"access": {"ok": True, "commands": True, "inbox": "/sdcard/Android/data/x/files/agent-inbox"},
+45
View File
@@ -0,0 +1,45 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-flatpak-setup"
class FlatpakSetupTest(unittest.TestCase):
def run_setup(self, uid, pacman):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
bin_dir = root / "bin"
bin_dir.mkdir()
stubs = {"id": "echo %d" % uid, "curl": "exit 7", "pacman": pacman, "pacman-key": "exit 0"}
for name, body in stubs.items():
(bin_dir / name).write_text("#!/bin/sh\n%s\n" % body)
(bin_dir / name).chmod(0o755)
script = root / "setup"
script.write_text(SCRIPT.read_text().replace("WORK=/var/cache/droiddeck-flatpak", "WORK=%s/work" % root)
.replace("/etc/pacman.d/gnupg/pubring.gpg", str(root / "pubring.gpg"))
.replace(" /etc/pacman.conf >", " %s >" % (root / "pacman.conf")))
(root / "pacman.conf").write_text("[options]\n[core]\nInclude = /etc/pacman.d/mirrorlist\n")
(root / "pubring.gpg").write_text("")
env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ["PATH"]))
result = subprocess.run(["bash", str(script)], env=env, capture_output=True, text=True, timeout=30)
return result.returncode, result.stdout
def test_a_manual_run_without_root_says_so(self):
code, out = self.run_setup(1000, "exit 0")
self.assertEqual(code, 1)
self.assertIn("== FAIL needs root", out)
self.assertNotIn("Reading the package lists", out)
def test_an_unreachable_mirror_reports_pacmans_error(self):
code, out = self.run_setup(0, "echo \"error: failed retrieving file 'core.db' : Could not resolve host\" >&2; exit 1")
self.assertEqual(code, 1)
self.assertIn("== FAIL could not reach the Arch Linux ARM mirrors (error: failed retrieving file 'core.db' : "
"Could not resolve host)", out)
if __name__ == "__main__":
unittest.main()
+70 -1
View File
@@ -8,6 +8,7 @@ import shlex
import subprocess
import sys
import tempfile
from unittest import mock
import unittest
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
@@ -76,6 +77,35 @@ class GameEnvironmentTest(unittest.TestCase):
env=env, text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.strip(), expected)
def test_desktop_games_restart_on_the_gpu_with_steams_preloads_handed_back(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
gpu = home / "gpu"
gpu.write_text("#!/bin/bash\necho \"gpu LD_PRELOAD=${LD_PRELOAD-unset}\"\nexport BL_DESKTOP_GPU_CHILD=1\nexec \"$@\"\n")
gpu.chmod(0o755)
launcher = home / "launcher"
setup = COMPAT["BL_DESKTOP_GPU_SETUP"].replace("/usr/local/bin/droiddeck-gpu", str(gpu))
launcher.write_text("#!/bin/bash\nverb=$1; shift\n" + setup + "echo \"game $verb $* LD_PRELOAD=${LD_PRELOAD-unset} saved=${BL_GPU_SAVED_LD_PRELOAD-unset}\"\n")
launcher.chmod(0o755)
base = {key: value for key, value in os.environ.items() if not key.startswith("BL_")}
base["LD_PRELOAD"] = "overlay.so"
for extra, args, expected in (
({"BL_DESKTOP": "1"}, ["waitforexitandrun", "game.exe"],
["gpu LD_PRELOAD=unset", "game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
({"BL_DESKTOP": "1", "BL_DESKTOP_GPU": "Off"}, ["waitforexitandrun", "game.exe"],
["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
({"BL_DESKTOP": "1"}, ["run", "setup.exe"],
["game run setup.exe LD_PRELOAD=overlay.so saved=unset"]),
({"BL_DESKTOP": "1"}, ["waitforexitandrun", "iscriptevaluator.exe"],
["game waitforexitandrun iscriptevaluator.exe LD_PRELOAD=overlay.so saved=unset"]),
({}, ["waitforexitandrun", "game.exe"],
["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]),
):
with self.subTest(extra=extra, args=args):
result = subprocess.run([str(launcher)] + args, env=dict(base, **extra),
text=True, capture_output=True, check=True)
self.assertEqual(result.stdout.splitlines(), expected)
def test_the_install_script_evaluator_gets_its_scripts_marked_first(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -180,6 +210,14 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self):
cap = MODULE["vram_cap"]
self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096")
self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"],
"dxgi.maxDeviceMemory = 2048; dxvk.maxFrameRate = 60")
for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}):
self.assertNotIn("DXVK_CONFIG", cap(off))
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
@@ -357,7 +395,33 @@ class GameEnvironmentTest(unittest.TestCase):
(asylum / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(asylum / "BmLauncher.exe"), []), ({}, [], []))
def test_caravan_sandwitch_and_cyberpunk_run_at_feature_level_12_1(self):
def test_black_ops_iii_and_dark_souls_remastered_skip_protonfixes(self):
for exe in ("/game/Call of Duty Black Ops III/BlackOps3.exe", "/game/DARK SOULS REMASTERED/DarkSoulsRemastered.exe"):
env, extra, notes = MODULE["engine_fixes"](exe, [])
self.assertEqual((env, extra), ({"PROTONFIXES_DISABLE": "1"}, []))
self.assertTrue(notes)
self.assertEqual(MODULE["engine_fixes"]("/game/Game/DarkSoulsII.exe", []), ({}, [], []))
def test_game_cores_are_parsed_from_lists_and_ranges(self):
parse = MODULE["parse_cores"]
self.assertEqual(parse("0-3,6"), {0, 1, 2, 3, 6})
self.assertEqual(parse(" 4, 5 "), {4, 5})
for bad in ("", "a", "3-1", "1,,2", "-1", "1-"):
self.assertIsNone(parse(bad), bad)
def test_a_profiles_game_cores_pin_the_game_within_the_online_cores(self):
calls = []
os_mod = MODULE["os"]
with mock.patch.dict(MODULE["game_cores"].__globals__, {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}), \
mock.patch.object(os_mod, "sched_setaffinity", side_effect=lambda pid, cores: calls.append(set(cores)), create=True):
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "0-2,9"})
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "junk"})
MODULE["game_cores"]({"DROIDDECK_GAME_CORES": "12-13"})
MODULE["game_cores"]({})
self.assertEqual(calls, [{0, 1, 2}])
self.assertEqual(MODULE["parse_cores"]("0,2-7"), {0, 2, 3, 4, 5, 6, 7})
def test_caravan_sandwitch_robocop_and_cyberpunk_run_at_feature_level_12_1(self):
with tempfile.TemporaryDirectory() as tmp:
caravan = Path(tmp) / "Caravan SandWitch"
shipping = caravan / "CaravanSandWitch/Binaries/Win64"
@@ -369,8 +433,13 @@ class GameEnvironmentTest(unittest.TestCase):
(cyberpunk / "bin/x64").mkdir(parents=True)
for name in ("REDprelauncher.exe", "bin/x64/Cyberpunk2077.exe"):
(cyberpunk / name).touch()
robocop = Path(tmp) / "RoboCop Rogue City"
(robocop / "RoboCop/Binaries/Win64").mkdir(parents=True)
for name in ("RoboCop.exe", "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe"):
(robocop / name).touch()
games = [caravan / "CaravanSandWitch.exe", caravan / ".droiddeck-launch.bat",
shipping / "CaravanSandWitch-Win64-Shipping.exe",
robocop / "RoboCop.exe", robocop / "RoboCop/Binaries/Win64/RoboCop-Win64-Shipping.exe",
cyberpunk / "REDprelauncher.exe", cyberpunk / "bin/x64/Cyberpunk2077.exe"]
for exe in games:
env, extra, notes = MODULE["engine_fixes"](str(exe), [])
+91
View File
@@ -0,0 +1,91 @@
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import unittest
TOOLS = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(TOOLS))
from proot_profile import report
PROGRAM = r'''
#define _POSIX_C_SOURCE 200809L
#define PR_NB_SYSNUM 2
#define PR_void 0
static const char *stringify_sysnum(unsigned nr) { return nr ? "openat" : "void"; }
#include "profile.h"
int main(void) {
errno = EBUSY;
if (!dd_profile_enabled()) return errno != EBUSY;
if (errno != EBUSY) return 1;
for (int i = 0; i < 40; i++) {
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
struct timespec wait = {0, 2000000};
nanosleep(&wait, 0);
errno = ENOENT;
dd_profile_record(1, 1, 123, wall, cpu);
if (errno != ENOENT) return 2;
if (i == 9) dd_profile_flush();
}
dd_profile_next = 0;
uint64_t wall = dd_profile_clock(CLOCK_MONOTONIC);
uint64_t cpu = dd_profile_clock(CLOCK_THREAD_CPUTIME_ID);
struct timespec wait = {0, 2000000};
nanosleep(&wait, 0);
dd_profile_record(1, 0, 123, wall, cpu);
return 0;
}
'''
class ProotProfileTest(unittest.TestCase):
def test_snapshots_replace_instead_of_adding_and_tracers_remain_separate(self):
with tempfile.TemporaryDirectory() as work:
path = Path(work) / 'session.log'
records = [dict(type='total', tracer=1, id=2, syscall='statx', stage='enter',
calls=n, wall_ns=n * 100, cpu_ns=n * 10, max_ns=100) for n in (3, 8)]
records.append(dict(records[-1], tracer=2, calls=2))
records += [dict(type='total', tracer=1, id=3, syscall='openat', stage='enter',
calls=1, wall_ns=1000, cpu_ns=1000, max_ns=1000)]
path.write_text('unrelated log\n' + ''.join('prefix proot-profile ' + json.dumps(r) + '\n' for r in records)
+ 'proot-profile {truncated\n' + 'proot-profile []\n')
result = report(path)
self.assertEqual(11, result['handlerCalls'])
self.assertEqual(3, result['tracers'])
self.assertEqual(2, result['malformedRecords'])
self.assertEqual('statx', result['totals'][0]['syscall'])
self.assertEqual('openat', report(path, 'cpu')['totals'][0]['syscall'])
def test_empty_logs_do_not_claim_profiling_ran(self):
with tempfile.TemporaryDirectory() as work:
path = Path(work) / 'session.log'
path.write_text('ordinary log\n')
self.assertFalse(report(path)['hasCounters'])
@unittest.skipUnless(shutil.which('cc'), 'C compiler required')
def test_real_clocks_bounded_samples_errno_and_periodic_counters(self):
with tempfile.TemporaryDirectory() as work:
source = Path(work) / 'profile.c'
binary = Path(work) / 'profile'
source.write_text(PROGRAM)
subprocess.run(['cc', '-Wall', '-Wextra', '-Werror', '-std=c99', '-I', str(TOOLS / 'proot'),
str(source), '-o', str(binary)], check=True)
for setting in ('0', ''):
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE=setting), capture_output=True, check=True)
self.assertEqual(b'', result.stderr)
result = subprocess.run([binary], env=dict(os.environ, PROOT_PROFILE='1', PROOT_PROFILE_SLOW_US='1'),
capture_output=True, check=True)
rows = [json.loads(line.split(b'proot-profile ', 1)[1]) for line in result.stderr.splitlines()]
self.assertEqual(33, sum(row['type'] == 'slow' for row in rows))
self.assertEqual(32, sum(row['type'] == 'slow' and row['stage'] == 'enter' for row in rows))
self.assertGreater(sum(row['type'] == 'total' for row in rows), 2)
log = Path(work) / 'session.log'
log.write_bytes(result.stderr)
counters = report(log)
self.assertEqual(41, counters['handlerCalls'])
self.assertGreater(counters['handlerWallNs'], counters['handlerCpuNs'])
self.assertEqual(40, counters['totals'][0]['calls'])
+1 -1
View File
@@ -22,7 +22,7 @@ PACKAGES = [line.split()[1] for line in VARIANTS.read_text().splitlines()
def guest_prefix(package):
source = SERVICE.read_text()
before_environment = source.split("val guest = ArrayList<String>()", 1)[1].split(
"addClientEnvironment(guest, steamHere)", 1)[0]
"addClientEnvironment(guest,", 1)[0]
environment = source.split("private fun addClientEnvironment(", 1)[1].split(
'guest.add("HOME=/root")', 1)[0]
prefix = []
+55
View File
@@ -0,0 +1,55 @@
"""Steam owns game caps; the nested compositor follows the output refresh rate."""
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
class SessionPacingTest(unittest.TestCase):
def launch(self, refresh, **overrides):
source = SESSION.read_text()
start = source.index(' width=${BL_WIDTH:-1280}')
end = source.index('\nfi\n\nbl_displays()', start)
block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub')
with tempfile.TemporaryDirectory() as directory:
env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH=str(refresh),
BL_MANGOAPP='0', BL_FPS='0', DROIDDECK_GAME_FRAME_LIMIT='0')
env.update(overrides)
script = '''
set -u
mode=steam
pipewire_stub() { return 1; }
run_gamescope() { printf 'ARG:%s\\n' "$@"; }
''' + block
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True,
text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
return [line.removeprefix('ARG:') for line in result.stdout.splitlines()
if line.startswith('ARG:')]
def test_display_refresh_sets_the_nested_compositor_rate(self):
for refresh in (60, 90, 120):
with self.subTest(refresh=refresh):
args = self.launch(refresh)
self.assertEqual(str(refresh), args[args.index('-r') + 1])
self.assertIn('-e', args)
def test_retired_cap_variables_do_not_override_the_display_rate(self):
for performance in ('0', '1'):
with self.subTest(performance=performance):
args = self.launch(120, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT=performance)
self.assertEqual('120', args[args.index('-r') + 1])
self.assertNotIn('--framerate-limit', args)
def test_retired_cap_cannot_set_the_rate_when_the_display_rate_is_unknown(self):
args = self.launch(0, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT='1')
self.assertNotIn('-r', args)
self.assertNotIn('--framerate-limit', args)
if __name__ == '__main__':
unittest.main()
@@ -69,6 +69,44 @@ class SteamCompatEnvironmentTest(unittest.TestCase):
os.kill(helper_pid, 9)
self.fail('droiddeck-steam-compat outlived the session')
def test_the_x86_64_client_gets_only_the_file_dialog_bridge(self):
source = (BIN / 'droiddeck-session').read_text()
start = source.index(' if [ "$steam_x64" = 1 ]; then\n { droiddeck-steam-compat --files-only')
block = source[start:source.index(' fi\n', start) + len(' fi\n')]
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
helper = root / 'droiddeck-steam-compat'
helper.write_text('#!/bin/sh\necho "$@" >> "$ARGS_FILE"\n')
helper.chmod(0o755)
for x64, expected in (('1', '--files-only /steam'), ('0', '/steam')):
with self.subTest(x64=x64):
args = root / ('args-' + x64)
env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'],
ARGS_FILE=str(args), steam_root='/steam', steam_x64=x64)
subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + block + 'wait\n'], env=env, timeout=10, check=True)
self.assertEqual(args.read_text().split('\n')[0], expected)
def test_files_only_mode_installs_only_the_file_dialog_hook(self):
import runpy
compat = runpy.run_path(str(BIN / 'droiddeck-steam-compat'))
calls = []
class Page:
def __init__(self, port, path):
self.ws = None
def evaluate(self, expression):
calls.append(('evaluate', expression[:40]))
return True
def call(self, method, params):
calls.append((method, params['name']))
helper = compat['Helper']('/steam', 1234, files_only=True)
helper.attach.__globals__.update(shared_context=lambda port: '/devtools/page/1', Page=Page)
self.assertTrue(helper.attach())
bindings = [name for method, name in calls if method == 'Runtime.addBinding']
self.assertEqual(bindings, [compat['FILE_BINDING']])
self.assertIn(('evaluate', compat['FILE_JS'][:40]), calls)
if __name__ == '__main__':
unittest.main()
+30 -1
View File
@@ -277,11 +277,40 @@ class CloudHooks(unittest.TestCase):
for sh in (compat.LAUNCHER_SH, compat.EXTRA_WRAPPER_SH):
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
self.assertNotIn('exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh)
self.assertIn('[ $? -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
self.assertIn('[ $rc -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP)
self.assertIn('droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP)
self.assertIn('exec "$@"', compat.BL_STORE_SETUP)
BNET_EXE = '/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe'
class BattleNet(unittest.TestCase):
def test_a_games_shortcut_is_handed_to_droiddeck_battlenet(self):
self.assertEqual([store.BATTLENET, 'launch', 'Fen'], store.battlenet(['waitforexitandrun', BNET_EXE, '--exec=launch Fen'], env={}))
self.assertEqual([store.BATTLENET, 'launch', 'OSI'], store.battlenet(['"%s"' % BNET_EXE, '--exec="launch OSI"'], env={}))
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE], env={}))
def test_anything_else_and_its_own_starts_are_left_alone(self):
other = BNET_EXE.replace('2596113170', '123')
self.assertIsNone(store.battlenet([other, '--exec=launch Fen'], env={}))
self.assertIsNone(store.battlenet(['/x/Diablo IV/Diablo IV.exe'], env={}))
self.assertIsNone(store.battlenet([BNET_EXE, '--exec=launch Fen'], env={'BL_BATTLENET': '1'}))
self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE, '--exec=launch Fen;rm'], env={}))
def test_the_launch_runs_there_and_the_wrapper_ends_with_it(self):
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=0) as call:
os.environ.pop('BL_BATTLENET', None)
self.assertEqual(store.RAN, store.main([BNET_EXE, '--exec=launch Pro']))
call.assert_called_once_with([store.BATTLENET, 'launch', 'Pro'])
with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=1):
os.environ.pop('BL_BATTLENET', None)
self.assertEqual(store.RAN_FAILED, store.main([BNET_EXE, '--exec=launch Pro']))
self.assertIn('[ $rc -eq 11 ] && exit 0', compat.BL_STORE_SETUP)
self.assertIn('[ $rc -eq 12 ] && exit 1', compat.BL_STORE_SETUP)
self.assertLess(compat.BL_STORE_SETUP.index('droiddeck-store-launch "$@"'), compat.BL_STORE_SETUP.index('[ $rc -eq 11 ] && exit 0'))
class Launchers(unittest.TestCase):
def test_both_proton_launchers_ask_before_proton_starts(self):
sh = compat.LAUNCHER_SH