Merge org main 0f839bef into the non-Adreno test branch

Conflicts resolved:
- build.yml: main's proot pack pin check and the Venus component fetch both kept.
- compositor.c: main's unpaced release goes through send_buffer_release (DMA-BUF quarantine).
- PulseAudioComponent: the AAudio retry loop stays; both sinks get main's control_dir.
- SessionService: main's add-on pack and proot checks, then the PowerVR driver setup and staging.
- droiddeck-session: main's stretch and refresh arguments with the selectable backend.
- droiddeck-gpu: main's desktop window mode on the wayland backend; PowerVR's sdl backend stays full screen.
- gamescope/release.env: the non-Adreno build stays pinned until the next one is published.
- FrontEndActivity/FrontEndScreen/SessionActivity/SessionFiles/SessionPrefs/LinuxRuntime/strings: both sides kept.
- test_gamescope_backend: the desktop backend test turns window mode off.
This commit is contained in:
The412Banner committed 2026-10-27 12:25:25 +00:00
commit 941cde30f2
394 files changed
+28009 -3092

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());
}
+101
View File
@@ -0,0 +1,101 @@
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
@unittest.skipUnless(shutil.which("cc"), "C compiler required")
class AndroidVolumeTest(unittest.TestCase):
def test_missing_or_invalid_initial_state_recovers_without_restarting_the_sink(self):
header = Path(__file__).resolve().parents[1] / "aaudio-sink/android-volume.h"
harness = r'''
#define _GNU_SOURCE
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#define PA_VOLUME_NORM 65536U
#define PA_USEC_PER_MSEC 1000
#define PA_SINK_INIT 0
#define PA_SUBSCRIPTION_EVENT_SINK 1
#define PA_SUBSCRIPTION_EVENT_CHANGE 2
#define PA_MIN(a,b) ((a)<(b)?(a):(b))
#define pa_xnew0(type,n) ((type*)calloc(n,sizeof(type)))
#define pa_xstrdup strdup
#define pa_xfree free
#define pa_log_warn(...) ((void)0)
typedef struct { unsigned value; } pa_cvolume;
typedef struct pa_time_event { int value; } pa_time_event;
typedef struct pa_mainloop_api { void (*time_free)(pa_time_event*); } pa_mainloop_api;
typedef struct { pa_mainloop_api *mainloop; } pa_core;
typedef struct pa_sink {
void *userdata; int state; bool muted; unsigned n_volume_steps, index;
struct { unsigned channels; } sample_spec;
pa_cvolume real_volume, reference_volume, soft_volume;
pa_core *core;
void (*set_volume)(struct pa_sink*), (*set_mute)(struct pa_sink*);
} pa_sink;
struct android_volume;
struct userdata { struct android_volume *android_volume; };
static int restarts, frees;
static char *pa_sprintf_malloc(const char *format, ...) {
va_list ap; va_start(ap,format); char *result; assert(vasprintf(&result,format,ap)>=0); va_end(ap); return result;
}
static void pa_cvolume_set(pa_cvolume *volume, unsigned channels, unsigned value) { volume->value=value; }
static unsigned pa_cvolume_max(const pa_cvolume *volume) { return volume->value; }
static void pa_cvolume_reset(pa_cvolume *volume, unsigned channels) { volume->value=PA_VOLUME_NORM; }
static bool pa_cvolume_equal(const pa_cvolume *a, const pa_cvolume *b) { return a->value==b->value; }
static void pa_sink_volume_changed(pa_sink *sink, const pa_cvolume *volume) { sink->real_volume=*volume; }
static void pa_sink_mute_changed(pa_sink *sink, bool muted) { sink->muted=muted; }
static void pa_sink_set_set_volume_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_volume=callback; }
static void pa_sink_set_set_mute_callback(pa_sink *sink, void (*callback)(pa_sink*)) { sink->set_mute=callback; }
static void pa_subscription_post(pa_core *core, int event, unsigned index) {}
static uint64_t pa_rtclock_now(void) { return 0; }
static void pa_core_rttime_restart(pa_core *core, pa_time_event *event, uint64_t time) { restarts++; }
static pa_time_event *pa_core_rttime_new(pa_core *core, uint64_t time,
void (*callback)(pa_mainloop_api*,pa_time_event*,const struct timeval*,void*), void *userdata) {
return calloc(1,sizeof(pa_time_event));
}
static void free_timer(pa_time_event *event) { frees++; free(event); }
#include "android-volume.h"
static void state(const char *directory, const char *text) {
char *path=pa_sprintf_malloc("%s/volume.state",directory);
FILE *f=fopen(path,"w"); assert(f); fputs(text,f); fclose(f); free(path);
}
int main(int argc, char **argv) {
pa_mainloop_api api={.time_free=free_timer}; pa_core core={.mainloop=&api};
struct userdata userdata={0};
pa_sink sink={.userdata=&userdata,.core=&core,.state=1,.sample_spec={.channels=2},.real_volume={PA_VOLUME_NORM}};
userdata.android_volume=android_volume_new(&sink,argv[1]);
assert(userdata.android_volume && userdata.android_volume->timer && sink.set_volume && sink.set_mute);
state(argv[1],"invalid\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==PA_VOLUME_NORM && restarts==1);
state(argv[1],"3 15 1\n");
android_volume_refresh(&api,userdata.android_volume->timer,NULL,userdata.android_volume);
assert(sink.real_volume.value==3*PA_VOLUME_NORM/15 && sink.muted && sink.n_volume_steps==16);
assert(sink.soft_volume.value==PA_VOLUME_NORM && restarts==2);
sink.real_volume.value=2*PA_VOLUME_NORM/3; sink.set_volume(&sink);
char *request=pa_sprintf_malloc("%s/volume.request",argv[1]);
FILE *f=fopen(request,"r"); unsigned level; assert(f && fscanf(f,"%u",&level)==1 && level==10); fclose(f); free(request);
android_volume_free(userdata.android_volume); assert(frees==1);
return 0;
}
'''
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "pulsecore").mkdir()
for name in ("core-rtclock.h", "core-subscribe.h"):
(root / "pulsecore" / name).touch()
source = root / "test.c"
source.write_text(harness)
binary = root / "test"
subprocess.run(["cc", "-std=c11", "-I", str(root), "-I", str(header.parent),
str(source), "-o", str(binary)], check=True, capture_output=True)
subprocess.run([str(binary), str(root)], check=True, capture_output=True)
File diff suppressed because it is too large. Load diff
+169
View File
@@ -0,0 +1,169 @@
from pathlib import Path
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
def function_source(name):
source = SCRIPT.read_text()
start = source.index('%s() {' % name)
end = source.index('\n }', start)
return source[start:end + len('\n }')]
def run_bash(script, env=None):
return subprocess.run(['bash', '-c', script], capture_output=True, text=True, timeout=10, env=env)
class ClientZramFocusTest(unittest.TestCase):
def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self):
source = SCRIPT.read_text()
start = source.index(' if [ "$_bl_game" = 1 ] && bl_game_focused; then')
stop = source.index(' nap 5', start)
body = source[start:stop]
harness = '''
_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_apps=" 413150"
_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
''' + body + '''
}
tick 0 1 1
tick 5 1 0
tick 30 1 1
echo "refocus:$_bl_packed"
tick 49 1 1
tick 50 1 1
tick 55 1 0
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_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30
_bl_apps=" 413150"
_bl_pids=(123)
step() { :; }
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_a_new_game_restarts_the_compression_delay(self):
result = run_bash(self.monitor_harness() + '''
tick 0 1 1 0 0
_bl_apps=" 413150 1245620"
tick 15 1 1 0 0
tick 20 1 1 0 0
echo "starting:$_bl_packed"
tick 34 1 1 0 0
tick 35 1 1 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['starting:-1', 'send:1:client'], result.stdout.splitlines())
def test_ram_cap_can_still_compress_an_unfocused_client(self):
result = run_bash(self.monitor_harness() + '''
BL_ZRAM_CLIENT=0 BL_RAM_CAP_MB=1024
bl_zram_usage() { _bl_rss=$((768 * 1024)); }
tick 0 1 0 1 1
echo "cap:$_bl_packed:$_bl_since:$_bl_backoff"
tick 5 0 0 0 0
''')
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual('', result.stderr)
self.assertEqual(['send:1:client', 'send:1:session', 'cap:0:-1:60', 'send:0:client'], result.stdout.splitlines())
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)
root = Path(temp.name)
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[*]}"\necho "others=${_bl_others[*]}"' % (root, scan))
self.assertEqual(0, result.returncode, result.stderr)
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')
script = '''
%s
check() {
BL_DESKTOP=$1 BL_LAUNCH_DIR=$2 _bl_apps=$3
if bl_game_focused; then echo yes; else echo no; fi
}
check "" "$dir" " 413150"
check "" "$dir" " 1245620"
printf '%%s\\n' '{"focusedApp": 999}' > "$dir/agent/focus.json"
check "" "$dir" " 413150"
printf '%%s\\n' '{"focusedApp": 769}' > "$dir/agent/focus.json"
check "" "$dir" " 413150"
rm -f "$dir/agent/focus.json"
check 1 "$dir" " 413150"
check "" "" " 413150"
''' % focus
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
launch = Path(temp.name)
(launch / 'agent').mkdir()
(launch / 'agent' / 'focus.json').write_text('{"t": 1, "focusedApp": 413150}\n')
result = run_bash('dir=%s\n%s' % (launch, script))
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual(['yes', 'no', 'no', 'no', 'yes', 'yes'], result.stdout.splitlines())
@staticmethod
def write_cmd(root, pid, args):
proc = root / str(pid)
proc.mkdir()
(proc / 'cmdline').write_bytes(b'\0'.join(arg.encode() for arg in args) + b'\0')
if __name__ == '__main__':
unittest.main()
+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(""), ({}, []))
+172
View File
@@ -0,0 +1,172 @@
import json
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
class DeviceControlsTest(unittest.TestCase):
def test_sync_controls_queued_notifications_are_processed_without_another_frame(self):
with tempfile.TemporaryDirectory() as directory:
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1}))
helper = LIVE["Helper"]("/steam", 0)
helper.controls_installed = True
page = mock.Mock(events=[])
page.ws.pending.return_value = False
helper.page = page
payload = json.dumps({"id": 1, "options": {"strTitle": "Pick a file"}})
def evaluate(expression):
for name, value in [(LIVE["BRIGHTNESS_BINDING"], "0.4"), (LIVE["FILE_BINDING"], payload)]:
page.events.append({"method": "Runtime.bindingCalled", "params": {"name": name, "payload": value}})
return True
def drain():
events, page.events = page.events, []
return events
page.evaluate.side_effect = evaluate
page.drain.side_effect = drain
helper.reconcile = mock.Mock()
helper.sync_frame_limit = mock.Mock()
helper.ensure_tools = mock.Mock(side_effect=[None, StopIteration])
helper.open_chooser = mock.Mock()
watcher = mock.Mock()
watcher.fileno.return_value = -1
watcher.changed.return_value = False
globals_ = LIVE["Helper"].serve.__globals__
with mock.patch.dict(globals_, {"CONTROLS_DIR": directory,
"brightness_request": lambda value: LIVE["brightness_request"](value, directory)}), \
mock.patch.dict(globals_["COMPAT"], {"state_path": lambda name: str(Path(directory, name))}), \
mock.patch.object(globals_["select"], "select", return_value=([], [], [])) as select_:
with self.assertRaises(StopIteration):
helper.serve(watcher)
self.assertEqual(float(Path(directory, "brightness.request").read_text()), 0.4)
helper.open_chooser.assert_called_once_with(payload)
self.assertEqual(page.events, [])
select_.assert_not_called()
def test_native_brightness_notifications_do_not_echo_android_readback(self):
harness = r"""
const assert = require('assert');
globalThis.window = globalThis;
const requests = [], callbacks = [];
const timers = [];
globalThis.setTimeout = callback => timers.push(callback);
let current = 1;
window.droiddeckBrightnessChanged = value => requests.push(Number(value));
globalThis.SteamClient = { System: { Display: {
RegisterForBrightnessChanges(cb) { callbacks.push(cb); cb({ flBrightness: 1 }); return {}; },
SetBrightness(value) {
if (current === value) return;
current = value;
callbacks.forEach(cb => cb({ flBrightness: value }));
}
} } };
const script = require('fs').readFileSync(process.argv[2], 'utf8');
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
const bridge = window.__droiddeckBrightness;
bridge.set(0.5);
bridge.set(0.5);
assert.deepStrictEqual(requests, []);
callbacks.forEach(cb => cb({ flBrightness: 0.8 }));
assert.deepStrictEqual(requests, [0.8]);
bridge.set(0.7992126);
assert.deepStrictEqual(requests, [0.8]);
for (const value of [NaN, Infinity, -1, 2, '0.5']) callbacks.forEach(cb => cb({ flBrightness: value }));
assert.deepStrictEqual(requests, [0.8]);
assert.strictEqual(callbacks.length, 1);
SteamClient.System.Display.SetBrightness = value => callbacks.forEach(cb => cb({ flBrightness: value + 0.1 }));
bridge.set(0.3);
assert.deepStrictEqual(requests, [0.8]);
callbacks.forEach(cb => cb({ flBrightness: 0.6 }));
assert.deepStrictEqual(requests, [0.8, 0.6]);
SteamClient.System.Display.SetBrightness = () => {};
bridge.set(0.65);
timers.forEach(callback => callback());
callbacks.forEach(cb => cb({ flBrightness: 0.7 }));
assert.deepStrictEqual(requests, [0.8, 0.6, 0.7]);
"""
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "bridge.js"
script.write_text(LIVE["BRIGHTNESS_JS"])
test = Path(directory) / "test.js"
test.write_text(harness)
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_requests_reject_nonfinite_and_out_of_range_values(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "brightness.request"
for value in ["NaN", "Infinity", "-0.1", "1.1", "invalid", None]:
LIVE["brightness_request"](value, directory)
self.assertFalse(path.exists())
LIVE["brightness_request"]("0.4", directory)
self.assertEqual(float(path.read_text()), 0.4)
def test_failed_request_revision_republishes_the_actual_brightness(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
helper = LIVE["Helper"]("/steam", 0)
calls = []
helper.controls_installed = True
helper.page = type("Page", (), {"evaluate": lambda self, expression: calls.append(expression) or True})()
path = Path(directory) / "state.json"
path.write_text(json.dumps({"brightness": 0.5, "revision": 1}))
helper.sync_controls()
helper.sync_controls()
self.assertEqual(len(calls), 1)
path.write_text(json.dumps({"brightness": 0.5, "revision": 2}))
helper.sync_controls()
self.assertEqual(len(calls), 2)
finally:
globals_["CONTROLS_DIR"] = previous
def test_display_bridge_retries_binding_and_install_before_caching_state(self):
with tempfile.TemporaryDirectory() as directory:
globals_ = LIVE["Helper"].sync_controls.__globals__
previous = globals_["CONTROLS_DIR"]
try:
globals_["CONTROLS_DIR"] = directory
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.5, "revision": 1}))
calls, installs, writes = [], ["unavailable", "installed", "present"], []
class Page:
present = True
def call(self, method, params):
calls.append((method, params))
def evaluate(self, expression):
if expression == LIVE["BRIGHTNESS_JS"]:
return installs.pop(0)
writes.append(expression)
return self.present
helper = LIVE["Helper"]("/steam", 0)
helper.page = Page()
helper.sync_controls()
self.assertIsNone(helper.controls_state)
self.assertFalse(writes)
helper.sync_controls()
helper.sync_controls()
self.assertEqual(len(calls), 2)
self.assertEqual(len(writes), 1)
self.assertEqual(calls[1], ("Runtime.addBinding", {"name": LIVE["BRIGHTNESS_BINDING"]}))
helper.page.present = False
Path(directory, "state.json").write_text(json.dumps({"brightness": 0.7, "revision": 2}))
helper.sync_controls()
self.assertIsNone(helper.controls_state)
self.assertFalse(helper.controls_installed)
helper.page.present = True
helper.sync_controls()
self.assertEqual(len(calls), 3)
self.assertEqual(helper.controls_state["brightness"], 0.7)
finally:
globals_["CONTROLS_DIR"] = previous
if __name__ == "__main__":
unittest.main()
+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)
+71
View File
@@ -48,6 +48,8 @@ class FexTestCase(unittest.TestCase):
"HOST_PRELOAD": str(self.tmp / "ld.so.preload"),
"DEVICE_FONTS": str(self.tmp / "android-fonts"),
"FONT_RULES": str(self.tmp / "66-droiddeck-device-fonts.conf"),
"OWN_FEX": str(self.tmp / "own"),
"OWN_FEX_TAG": str(self.tmp / "own/share/fex-emu/.droiddeck-tag"),
}
patcher = mock.patch.dict(G, patches)
patcher.start()
@@ -202,6 +204,75 @@ class LocateTest(FexTestCase):
self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(tool / "usr/bin/FEX"), str(tool / "usr/bin/FEXServer"), True))
self.assertTrue(fex["host_thunks"].endswith("HostThunks") and fex["guest_thunks"].endswith("GuestThunks") and fex["thunks_db"])
def own_fex(self, tag, loads=True):
own = self.tmp / "own"
self.write(own / "bin/FEX", mode=0o755)
self.write(own / "bin/FEXServer", mode=0o755)
self.write(own / "share/fex-emu/.droiddeck-tag", tag + "\n")
listing = b"libc.so.6 => /usr/lib/libc.so.6\n" if loads else b"libxxhash.so.0 => not found\n"
patcher = mock.patch.object(G["subprocess"], "run", lambda args, **kw: subprocess.CompletedProcess(args, 0, listing))
patcher.start()
self.addCleanup(patcher.stop)
return own
def test_an_own_build_that_no_longer_loads_is_installed_again_and_skipped(self):
tool = self.fex_tool(self.steam)
self.own_fex("fex-2610-r7", loads=False)
calls = []
with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 1):
FEX["update_own_fex"]()
self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls)
self.assertEqual(FEX["fex_install"]()["bin"], str(tool / "usr/bin/FEX"))
def test_droiddeck_s_own_build_comes_before_the_steam_tool(self):
self.fex_tool(self.steam)
own = self.own_fex("fex-2610-r7")
fex = FEX["fex_install"]()
self.assertEqual((fex["bin"], fex["server"], fex["portable"]), (str(own / "bin/FEX"), str(own / "bin/FEXServer"), False))
def test_the_build_the_session_names_is_installed_once(self):
self.own_fex("fex-2610-r6")
calls = []
with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0):
FEX["update_own_fex"]()
self.write(self.tmp / "own/share/fex-emu/.droiddeck-tag", "fex-2610-r7\n")
FEX["update_own_fex"]()
self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls)
def test_a_failed_build_waits_an_hour_unless_the_session_names_another(self):
self.own_fex("fex-2610-r6")
Path(G["STATE"]).mkdir(parents=True, exist_ok=True)
calls = []
tag = {"BL_FEX_TAG": "fex-2610-r7"}
with mock.patch.dict(os.environ, tag), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(os.environ["BL_FEX_TAG"]) or 1):
FEX["update_own_fex"]()
FEX["update_own_fex"]()
failed = Path(G["STATE"]) / "update-failed"
os.utime(failed, (failed.stat().st_atime, failed.stat().st_mtime - 3601))
FEX["update_own_fex"]()
os.environ["BL_FEX_TAG"] = "fex-2610-r8"
FEX["update_own_fex"]()
self.assertEqual(["fex-2610-r7", "fex-2610-r7", "fex-2610-r8"], calls)
def test_a_missing_updater_falls_back_to_the_fex_already_here(self):
self.fex_tool(self.steam)
Path(G["STATE"]).mkdir(parents=True, exist_ok=True)
with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \
mock.patch.object(G["subprocess"], "call", mock.Mock(side_effect=FileNotFoundError)):
FEX["update_own_fex"]()
self.assertEqual(FEX["fex_install"]()["bin"], str(self.steam / "steamapps/common/FEX-Emu/usr/bin/FEX"))
def test_no_build_is_installed_without_one_from_the_session(self):
calls = []
with mock.patch.dict(os.environ, {}, clear=False), \
mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0):
os.environ.pop("BL_FEX_TAG", None)
FEX["update_own_fex"]()
self.assertEqual([], calls)
def test_library_folders_are_read(self):
other = self.tmp / "other"
(other / "steamapps/common").mkdir(parents=True)
@@ -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"},
+1 -1
View File
@@ -6,7 +6,7 @@ import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-fex-update"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("fex_install() {")
END = SOURCE.index("\n}\n", START) + 3
+3 -3
View File
@@ -5,9 +5,9 @@ import tempfile
import textwrap
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-steam-x64"
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-fex-update"
SOURCE = SCRIPT.read_text()
START = SOURCE.index("x64_fex() {")
START = SOURCE.index("fex_ready() {")
END = SOURCE.index("\n}\n", START) + 3
X64_FEX = SOURCE[START:END]
@@ -35,7 +35,7 @@ class FexSelectTest(unittest.TestCase):
fex.chmod(0o755)
body = (X64_FEX.replace("/usr/local/share/fex-emu/.droiddeck-tag", "$ROOT/tag")
.replace("/usr/local/bin/FEX", "$ROOT/FEX"))
script = HARNESS + body + 'if x64_fex; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n'
script = HARNESS + body + 'if fex_ready; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n'
env = dict(os.environ, ROOT=root, LOADS="1" if loads else "0", INSTALLABLE=" ".join(installable))
env.pop("BL_FEX_TAG", None)
if catalog:
+67
View File
@@ -0,0 +1,67 @@
import contextlib
import fcntl
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, locked=False, busy=False):
with tempfile.TemporaryDirectory() as directory, contextlib.ExitStack() as held:
root = Path(directory)
if locked:
(root / "work/db").mkdir(parents=True)
(root / "work/db/db.lck").write_text("")
if busy:
holder = held.enter_context(open(root / "work/setup.lock", "w"))
fcntl.flock(holder, fcntl.LOCK_EX | fcntl.LOCK_NB)
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)
SYNC = ("db=; while [ $# -gt 0 ]; do [ \"$1\" = --dbpath ] && db=$2; shift; done\n"
"[ -e \"$db/db.lck\" ] && { echo 'error: failed to synchronize all databases (unable to lock database)' >&2; exit 1; }\n"
"mkdir -p \"$db/sync\" && touch \"$db/sync/extra.db\"")
def test_a_lock_left_by_an_interrupted_run_is_cleared(self):
code, out = self.run_setup(0, self.SYNC, locked=True)
self.assertNotIn("unable to lock database", out)
self.assertIn("== STEP Downloading Flatpak", out)
def test_a_setup_that_is_still_running_keeps_its_lock(self):
code, out = self.run_setup(0, self.SYNC, locked=True, busy=True)
self.assertEqual(code, 1)
self.assertIn("== FAIL another Flatpak setup is still running", out)
self.assertNotIn("Reading the package lists", out)
if __name__ == "__main__":
unittest.main()
+139
View File
@@ -0,0 +1,139 @@
"""The Quick Access Frame Limit follows the panel when its refresh rate changes."""
from pathlib import Path
import runpy
import subprocess
import tempfile
import unittest
from unittest import mock
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
LIVE = runpy.run_path(str(BIN / "droiddeck-steam-compat"))
HARNESS = r"""
const assert = require('assert');
globalThis.window = globalThis;
globalThis.btoa = text => Buffer.from(text, 'binary').toString('base64');
let timers = new Map(), nextTimer = 0;
globalThis.setTimeout = (callback, ms) => { timers.set(++nextTimer, callback); return nextTimer; };
globalThis.clearTimeout = id => timers.delete(id);
globalThis.setInterval = () => 0;
const fire = async () => {
const pending = [...timers.values()]; timers = new Map();
for (const callback of pending) await callback();
};
let rates = [36, 48, 72, 144];
const notify = [];
const service = {
GetState: async () => ({ BSuccess: () => true,
Body: () => ({ toObject: () => ({ state: { active_display_info: { supported_frame_rates: rates } } }) }) }),
RegisterForNotifyStateChanged(callback) { notify.push(callback); return {}; },
SetBlurParams() {},
};
const writes = [];
globalThis.settingsStore = { clientSettings: {
gamescope_enable_app_target_framerate: true, gamescope_app_target_framerate: 120, gamescope_disable_framelimit: false } };
const varints = bytes => { const out = []; let value = 0, shift = 0;
for (const b of bytes) { value += (b & 127) * 2 ** shift; shift += 7; if (b < 128) { out.push(value); value = 0; shift = 0; } }
return out; };
globalThis.SteamClient = { Settings: { SetSetting(encoded) {
const [key, value] = varints([...Buffer.from(encoded, 'base64')]);
assert.strictEqual(key, 21002 * 8);
writes.push(value);
settingsStore.clientSettings.gamescope_app_target_framerate = value;
} } };
const modules = {
1: { source: () => 'RegisterForNotifyStateChanged only', exports: { other: { GetState() {} } } },
2: { source: () => 'n.MX.SetBlurParams(); n.MX.RegisterForNotifyStateChanged()', exports: { hooks: () => {} } },
3: { source: () => 'SetBlurParams RegisterForNotifyStateChanged GetState', exports: { MX: service } },
};
const webpack = modules => { const require = id => modules[id].exports;
require.m = Object.fromEntries(Object.entries(modules).map(([id, m]) => [id, { toString: m.source }]));
return require; };
globalThis.webpackChunksteamui = { push([, , callback]) { callback(webpack(modules)); } };
const script = require('fs').readFileSync(process.argv[2], 'utf8');
const change = async next => { rates = next; notify.forEach(callback => callback()); };
(async () => {
assert.strictEqual(eval(script), 'installed');
assert.strictEqual(eval(script), 'present');
await fire();
assert.deepStrictEqual(writes, [144], 'a remembered limit the panel does not offer moves to the highest value');
await fire();
assert.deepStrictEqual(writes, [144], 'unchanged choices are not written again');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
await change([24, 30, 40, 60, 120]);
await fire();
assert.deepStrictEqual(writes, [144, 120], '72 is not offered at 120 Hz');
settingsStore.clientSettings.gamescope_app_target_framerate = 60;
await change([12, 15, 20, 30, 60]);
await fire();
assert.deepStrictEqual(writes, [144, 120], '60 is still offered at 60 Hz and is kept');
await change([18, 24, 36, 72]);
await change([24, 30, 40, 60, 120]);
await fire();
assert.deepStrictEqual(writes, [144, 120], 'a passing rate during a mode switch is not acted on');
settingsStore.clientSettings.gamescope_enable_app_target_framerate = false;
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
await change([36, 48, 144]);
await fire();
assert.deepStrictEqual(writes, [144, 120], 'nothing changes while Steam has the frame limit turned off');
settingsStore.clientSettings.gamescope_enable_app_target_framerate = true;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144], 'turning the limit on after a rate change moves an unoffered value');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
const setSetting = SteamClient.Settings.SetSetting;
SteamClient.Settings.SetSetting = () => { throw new Error('busy'); };
window.__droiddeckFrameLimit.schedule();
await fire();
SteamClient.Settings.SetSetting = setSetting;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144, 144], 'a failed write is tried again on the next check');
settingsStore.clientSettings.gamescope_app_target_framerate = 72;
SteamClient.Settings.SetSetting = () => Promise.reject(new Error('busy'));
window.__droiddeckFrameLimit.schedule();
await fire();
SteamClient.Settings.SetSetting = setSetting;
window.__droiddeckFrameLimit.schedule();
await fire();
assert.deepStrictEqual(writes, [144, 120, 144, 144, 144], 'a rejected write is caught and tried again');
delete window.__droiddeckFrameLimit;
webpackChunksteamui.push = ([, , callback]) => callback(webpack({ 1: modules[1], 2: modules[2] }));
assert.strictEqual(eval(script), 'unavailable');
})().catch(error => { console.error(error); process.exit(1); });
"""
class FrameLimitSyncTest(unittest.TestCase):
def test_limit_is_kept_when_offered_and_moved_to_the_highest_value_otherwise(self):
with tempfile.TemporaryDirectory() as directory:
script = Path(directory) / "frame_limit.js"
script.write_text(LIVE["FRAME_LIMIT_JS"])
test = Path(directory) / "test.js"
test.write_text(HARNESS)
result = subprocess.run(["node", str(test), str(script)], capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
def test_install_is_retried_until_steam_is_ready_and_reported_once_per_state(self):
helper = LIVE["Helper"]("/steam", 0)
page = mock.Mock()
page.evaluate.side_effect = ["unavailable", "unavailable", "installed"]
helper.page = page
said = []
clock = [100.0]
globals_ = LIVE["Helper"].sync_frame_limit.__globals__
with mock.patch.dict(globals_, {"say": said.append}), mock.patch.object(globals_["time"], "monotonic", lambda: clock[0]):
helper.sync_frame_limit()
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
clock[0] += 10
helper.sync_frame_limit()
self.assertEqual(page.evaluate.call_count, 3)
self.assertEqual(said, ["frame limit sync: unavailable", "frame limit sync: installed"])
if __name__ == "__main__":
unittest.main()
+139 -1
View File
@@ -8,6 +8,7 @@ import shlex
import subprocess
import sys
import tempfile
from unittest import mock
import unittest
from unittest.mock import patch
@@ -206,6 +207,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)
@@ -310,6 +340,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"}}}
@@ -443,6 +481,13 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d")
self.assertEqual(extra, ["--rendering-driver", "vulkan"])
self.assertEqual(MODULE["engine_fixes"](str(game / "Game.exe"), ["--rendering-driver", "opengl3"])[1], [])
script = Path(tmp) / "GDScript Game"
script.mkdir()
for name in ("Game.exe", "Game.pck", "libsentry.windows.release.x86_64.dll"):
(script / name).touch()
env, extra, notes = MODULE["engine_fixes"](str(script / "Game.exe"), [])
self.assertNotIn("WINEDLLOVERRIDES", env)
self.assertEqual(extra, ["--rendering-driver", "vulkan"])
other = Path(tmp) / "Other"
other.mkdir()
(other / "Other.exe").touch()
@@ -536,7 +581,95 @@ 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_d3dgear_capture_hook_beside_the_game_is_turned_off(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "The Crew 2"
game.mkdir()
for name in ("TheCrew2.exe", "TheCrew2_BE.exe", "d3dgear64.dll"):
(game / name).touch()
env, extra, notes = MODULE["engine_fixes"](str(game / "TheCrew2.exe"), [])
self.assertEqual((env, extra), ({"WINEDLLOVERRIDES": "d3dgear64=d"}, []))
self.assertTrue(notes)
(game / "d3dgear64.dll").rename(game / "D3DGear64.DLL")
self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), [])[0], {"WINEDLLOVERRIDES": "d3dgear64=d"})
(game / "D3DGear64.DLL").unlink()
self.assertEqual(MODULE["engine_fixes"](str(game / "TheCrew2.exe"), []), ({}, [], []))
def test_dll_overrides_from_several_fixes_are_all_kept(self):
with tempfile.TemporaryDirectory() as tmp:
for name in ("Game.exe", "Game.pck", "GodotSharp.dll", "libsentry.windows.release.x86_64.dll", "d3dgear64.dll"):
(Path(tmp) / name).touch()
env = MODULE["engine_fixes"](str(Path(tmp) / "Game.exe"), [])[0]
self.assertEqual(env["WINEDLLOVERRIDES"], "libsentry.windows.release.x86_64=d;d3dgear64=d")
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_windows_games_see_only_the_cores_they_are_pinned_to(self):
os_mod = MODULE["os"]
online = {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}}
cases = [
({"BL_GAME_CPUS": "6,7"}, {6, 7}, "2:6,7", "2:6,7"),
({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, "3:0,1,2", "3:0,1,2"),
({"BL_GAME_CPUS": "0-7"}, set(range(8)), None, None),
({}, {6, 7}, None, None),
({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": "4:0,1,2,3"}, {6, 7}, "4:0,1,2,3", "4:0,1,2,3"),
({"WINE_CPU_TOPOLOGY": "2:0,1"}, set(range(8)), "2:0,1", "2:0,1"),
({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": ""}, {6, 7}, "", None),
({"BL_GAME_CPUS": "6,7", "PROTON_CPU_TOPOLOGY": "1:7"}, {6, 7}, None, "1:7"),
({"BL_GAME_CPUS": "9"}, {9}, None, None),
]
for env, affinity, expected, proton in cases:
with mock.patch.dict(MODULE["cpu_topology"].__globals__, online), \
mock.patch.object(os_mod, "sched_getaffinity", return_value=affinity, create=True):
MODULE["cpu_topology"](env)
self.assertEqual(env.get("WINE_CPU_TOPOLOGY"), expected, env)
self.assertEqual(env.get("PROTON_CPU_TOPOLOGY"), proton, env)
def test_reskate_runs_at_feature_level_12_1(self):
with tempfile.TemporaryDirectory() as tmp:
reskate = Path(tmp) / "ReSkate"
reskate.mkdir()
for name in ("Skate.exe", "ReSkate.dll", "ReSkateLauncher.exe", "EAAntiCheat.GameServiceLauncher.exe"):
(reskate / name).touch()
for exe in ("ReSkateLauncher.exe", "Skate.exe"):
env, extra, notes = MODULE["engine_fixes"](str(reskate / exe), [])
self.assertEqual((env, extra), ({"VKD3D_FEATURE_LEVEL": "12_1"}, []), exe)
self.assertTrue(notes)
config = {"version": 1, "shared": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_1")
config["games"] = {"3354750": {"VKD3D_FEATURE_LEVEL": "12_2"}}
self.assertEqual(MODULE["apply_config"]({}, config, "3354750", env)["VKD3D_FEATURE_LEVEL"], "12_2")
skate = Path(tmp) / "Skate"
skate.mkdir()
for name in ("Skate.exe", "EAAntiCheat.GameServiceLauncher.exe"):
(skate / name).touch()
self.assertEqual(MODULE["engine_fixes"](str(skate / "EAAntiCheat.GameServiceLauncher.exe"), [])[:2], ({}, []))
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"
@@ -548,8 +681,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), [])
+1 -1
View File
@@ -65,7 +65,7 @@ class DesktopGamescopeBackendTest(unittest.TestCase):
for name in ("BL_GAMESCOPE_BACKEND", "BL_DEBUG_DIR", "BL_FPS", "BL_REFRESH", "BL_HDR"):
env.pop(name, None)
env.update(PATH=f"{root}{os.pathsep}{env.get('PATH', '')}",
GAMESCOPE_CAPTURE=str(capture), WAYLAND_DISPLAY="desktop-0",
GAMESCOPE_CAPTURE=str(capture), WAYLAND_DISPLAY="desktop-0", BL_DESKTOP_GPU_WINDOW="0",
SDL_VIDEODRIVER="dummy", GDK_BACKEND="wayland", QT_QPA_PLATFORM="wayland")
if backend is not None:
env["BL_GAMESCOPE_BACKEND"] = backend
+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 = []
+64
View File
@@ -0,0 +1,64 @@
"""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.pop('GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST', None)
env.update(overrides)
script = '''
set -u
mode=steam
pipewire_stub() { return 1; }
run_gamescope() { printf 'ARG:%s\\n' "$@"; printf 'FOLLOW:%s\\n' "${GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST:-}"; }
''' + block
result = subprocess.run(['bash', '-c', script], env=env, capture_output=True,
text=True, timeout=5)
self.assertEqual(0, result.returncode, result.stderr)
self.follow = [line.removeprefix('FOLLOW:') for line in result.stdout.splitlines()
if line.startswith('FOLLOW:')]
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_gamescope_follows_the_panel_after_the_starting_rate(self):
self.launch(144)
self.assertEqual(['1'], self.follow)
self.launch(0)
self.assertEqual([''], self.follow)
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
+17 -1
View File
@@ -28,7 +28,8 @@ class ValidateApkTest(unittest.TestCase):
def git(self, *args):
return subprocess.check_output(["git", "-C", self.root, *args], text=True).strip()
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt"):
def validate(self, message="Source change", body="", result="success", stale=False, completed=False, filename="source.kt", permission="write", role_name="write"):
(self.root / filename).parent.mkdir(parents=True, exist_ok=True)
(self.root / filename).write_text(message)
self.git("add", filename)
self.git("commit", "--allow-empty", "-qm", message)
@@ -42,6 +43,8 @@ class ValidateApkTest(unittest.TestCase):
path.write_text(json.dumps(event))
def api(path, *args):
if path.endswith("/collaborators/human/permission"):
return {"permission": permission, "role_name": role_name}
if "/statuses/" in path:
self.statuses.append(dict(value.split("=", 1) for value in args if "=" in value))
return {}
@@ -96,6 +99,19 @@ class ValidateApkTest(unittest.TestCase):
self.validate(filename="README.md", result="pending")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_trusted_list_requires_maintainer_pr_opener(self):
with self.assertRaisesRegex(RuntimeError, "Only a maintainer"):
self.validate(filename=".github/trusted-test-builds.txt")
self.assertEqual(self.statuses[-1]["state"], "failure")
def test_maintainer_can_change_trusted_list(self):
self.validate(filename=".github/trusted-test-builds.txt", permission="write", role_name="maintain")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_admin_can_change_trusted_list(self):
self.validate(filename=".github/trusted-test-builds.txt", permission="admin", role_name="admin")
self.assertEqual(self.statuses[-1]["state"], "success")
def test_renaming_code_to_documentation_still_requires_compilation(self):
(self.root / "source.kt").write_text("source")
self.git("add", "source.kt")
+282
View File
@@ -0,0 +1,282 @@
import array
import mmap
import os
import socket
import struct
import subprocess
import tempfile
import threading
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
VDEC = ROOT / 'tools/linuxfs/preload/vdec.c'
VENC = ROOT / 'tools/linuxfs/preload/venc.c'
DRIVER = r'''
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <poll.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
int bl_vdec_open(const char *path, int flags);
int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc);
void bl_vdec_closed(int fd);
void *SDL_LoadObject(const char *name);
void *SDL_LoadFunction(void *handle, const char *name);
struct heap_alloc { uint64_t len; uint32_t fd, fd_flags; uint64_t heap_flags; };
struct create_dumb { uint32_t height, width, bpp, flags, handle, pitch; uint64_t size; };
struct prime_handle { uint32_t handle, flags; int32_t fd; };
struct destroy_dumb { uint32_t handle; };
struct drm_device { char **nodes; int available_nodes; };
static int heap = -1;
int open(const char *path, int flags, ...) {
static int (*real)(const char *, int, ...);
va_list ap;
va_start(ap, flags);
int mode = va_arg(ap, int);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "open");
if (strcmp(path, "/dev/dma_heap/system") == 0) return heap = memfd_create("heap", 0);
return real(path, flags, mode);
}
int ioctl(int fd, unsigned long req, ...) {
static int (*real)(int, unsigned long, ...);
va_list ap;
va_start(ap, req);
void *arg = va_arg(ap, void *);
va_end(ap);
if (!real) real = dlsym(RTLD_NEXT, "ioctl");
if (fd == heap && req == _IOWR('H', 0, struct heap_alloc)) {
struct heap_alloc *a = arg;
int buf = memfd_create("dmabuf", 0);
if (ftruncate(buf, (off_t)a->len) != 0) return -1;
a->fd = (uint32_t)buf;
return 0;
}
if (req == _IOW('b', 0, uint64_t)) return 0;
return real(fd, req, arg);
}
static int vfd;
static int call(unsigned long req, void *arg) {
int rc;
if (!bl_vdec_ioctl(vfd, req, arg, &rc)) return -100;
return rc < 0 ? -errno : 0;
}
int main(void) {
if (bl_vdec_open("/dev/video0", O_RDWR) != -2) return 2;
void *drm = SDL_LoadObject("libdrm.so.2");
if (!drm) return 3;
int (*devices)(uint32_t, struct drm_device **, int) = SDL_LoadFunction(drm, "drmGetDevices2");
int (*drm_ioctl)(int, unsigned long, void *) = SDL_LoadFunction(drm, "drmIoctl");
if (!devices || !drm_ioctl || !SDL_LoadFunction(drm, "drmModeAtomicCommit")) return 4;
struct drm_device *dev[1];
if (devices(0, NULL, 0) != 1 || devices(0, dev, 1) != 1 || !(dev[0]->available_nodes & 1)) return 5;
int card = open(dev[0]->nodes[0], O_RDWR | O_CLOEXEC);
if (card < 0) return 6;
vfd = bl_vdec_open("/dev/video-dec0", O_RDWR);
if (vfd < 0) return 7;
struct v4l2_capability cap;
if (call(VIDIOC_QUERYCAP, &cap) || (cap.capabilities & 0x04004000) != 0x04004000) return 8;
struct v4l2_fmtdesc d = { .index = 1, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
if (call(VIDIOC_ENUM_FMT, &d) || d.pixelformat != V4L2_PIX_FMT_HEVC) return 9;
struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 720; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_HEVC;
if (call(VIDIOC_S_FMT, &f)) return 10;
struct v4l2_requestbuffers r = { .count = 4, .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, .memory = V4L2_MEMORY_MMAP };
if (call(VIDIOC_REQBUFS, &r) || r.count != 4) return 11;
unsigned char *in[4];
for (int i = 0; i < 4; i++) {
struct v4l2_plane p = { 0 };
struct v4l2_buffer b = { .index = i, .type = r.type, .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
if (call(VIDIOC_QUERYBUF, &b)) return 12;
in[i] = mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, vfd, p.m.mem_offset);
if (in[i] == MAP_FAILED) return 13;
}
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
f.fmt.pix_mp.width = 1280; f.fmt.pix_mp.height = 736; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.num_planes != 1) return 14;
uint32_t bpl = f.fmt.pix_mp.plane_fmt[0].bytesperline, size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
if (bpl != 1280 || size != 1280 * 736 * 3 / 2) return 15;
r = (struct v4l2_requestbuffers){ .count = 3, .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE, .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r) || r.count != 3) return 16;
int out[3];
for (int i = 0; i < 3; i++) {
struct create_dumb c = { .height = 736, .width = 1280, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &c) || !c.handle || c.size < size) return 17;
struct prime_handle h = { .handle = c.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &h)) return 18;
struct destroy_dumb x = { .handle = c.handle };
if (drm_ioctl(card, 0xc00464b4, &x)) return 19;
out[i] = h.fd;
}
unsigned types[2] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
if (call(VIDIOC_STREAMON, &types[0]) || call(VIDIOC_STREAMON, &types[1])) return 20;
for (int i = 0; i < 3; i++) {
struct v4l2_plane p = { .m.fd = out[i] };
struct v4l2_buffer b = { .index = i, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &p };
if (call(VIDIOC_QBUF, &b)) return 21;
}
struct pollfd pf = { .fd = vfd, .events = 0xc9 };
if (poll(&pf, 1, 0) != 0) return 22;
for (int frame = 1; frame <= 5; frame++) {
int slot = frame % 4;
memset(in[slot], 'a' + frame, 100 + frame);
struct v4l2_plane p = { .bytesused = 100 + frame };
struct v4l2_buffer b = { .index = slot, .type = types[0], .memory = V4L2_MEMORY_MMAP, .flags = 0x4008, .length = 1, .m.planes = &p };
b.timestamp.tv_usec = frame;
if (call(VIDIOC_QBUF, &b)) return 23;
pf = (struct pollfd){ .fd = vfd, .events = 0xc9 };
if (poll(&pf, 1, 30) != 1 || !(pf.revents & POLLIN)) return 24;
struct v4l2_plane cp = { 0 };
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &cp };
if (call(VIDIOC_DQBUF, &cb)) return 25;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, out[cb.index], 0);
printf("%ld %u %c%c %u\n", (long)cb.timestamp.tv_usec, cb.index, m[0], m[(size_t)bpl * 736], cp.bytesused == size);
munmap(m, size);
pf = (struct pollfd){ .fd = vfd, .events = 0x306 };
if (poll(&pf, 1, 0) != 1) return 26;
struct v4l2_plane op = { 0 };
struct v4l2_buffer ob = { .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &op };
if (call(VIDIOC_DQBUF, &ob) || ob.index != (unsigned)slot) return 27;
struct v4l2_plane rp = { .m.fd = out[cb.index] };
struct v4l2_buffer rb = { .index = cb.index, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &rp };
if (call(VIDIOC_QBUF, &rb)) return 28;
}
if (call(VIDIOC_STREAMOFF, &types[1])) return 29;
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
f.fmt.pix_mp.width = 1920; f.fmt.pix_mp.height = 1088; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f)) return 30;
size = f.fmt.pix_mp.plane_fmt[0].sizeimage;
r = (struct v4l2_requestbuffers){ .count = 1, .type = types[1], .memory = V4L2_MEMORY_DMABUF };
if (call(VIDIOC_REQBUFS, &r)) return 31;
struct create_dumb big = { .height = 1088, .width = 1920, .bpp = 16 };
if (drm_ioctl(card, 0xc02064b2, &big)) return 32;
struct prime_handle bh = { .handle = big.handle, .flags = O_CLOEXEC };
if (drm_ioctl(card, 0xc00c642d, &bh)) return 33;
if (call(VIDIOC_STREAMON, &types[1])) return 34;
struct v4l2_plane bp = { .m.fd = bh.fd };
struct v4l2_buffer bb = { .index = 0, .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &bp };
if (call(VIDIOC_QBUF, &bb)) return 35;
memset(in[2], 'z', 50);
struct v4l2_plane zp = { .bytesused = 50 };
struct v4l2_buffer zb = { .index = 2, .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &zp };
zb.timestamp.tv_usec = 6;
if (call(VIDIOC_QBUF, &zb)) return 36;
struct v4l2_plane dp = { 0 };
struct v4l2_buffer db = { .type = types[1], .memory = V4L2_MEMORY_DMABUF, .length = 1, .m.planes = &dp };
if (call(VIDIOC_DQBUF, &db)) return 37;
unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0);
printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]);
bl_vdec_closed(vfd);
return 0;
}
'''
CONFIG = struct.Struct('<IIIIIIII')
CAPTURE = struct.Struct('<III')
PACKET = struct.Struct('<IIII q')
RESULT = struct.Struct('<IiI')
class FakeDecoder(threading.Thread):
def __init__(self, path):
super().__init__(daemon=True)
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
self.listener.bind(path)
self.listener.listen(1)
self.configs, self.packets = [], []
def run(self):
while True:
try:
conn, _ = self.listener.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
def serve(self, conn):
bitstream, captures, config = None, {}, None
while True:
fds = array.array('i')
msg, ancdata, _, _ = conn.recvmsg(256, socket.CMSG_LEN(4 * fds.itemsize))
if not msg:
return
for level, kind, data in ancdata:
if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
fds.frombytes(data[:len(data) - len(data) % fds.itemsize])
kind = struct.unpack_from('<I', msg)[0]
if kind == 6:
config = CONFIG.unpack(msg)
self.configs.append(config)
bitstream = mmap.mmap(fds[0], config[6] * config[7], prot=mmap.PROT_READ)
os.close(fds[0])
conn.send(RESULT.pack(9, 0, 0))
elif kind == 7:
_, index, size = CAPTURE.unpack(msg)
captures[index] = mmap.mmap(fds[0], size)
os.close(fds[0])
elif kind == 8:
_, source, nbytes, target, pts = PACKET.unpack(msg)
self.packets.append((source, nbytes, target, pts))
first = bitstream[source * config[7]]
frame = captures[target]
frame[0] = first
frame[config[4] * config[5]] = ord('u')
conn.send(RESULT.pack(9, 0, 1))
class VdecEmulatorTest(unittest.TestCase):
def test_remote_play_client_decodes_through_the_app_socket(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'streaming_client'
subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC),
str(VENC), '-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeDecoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
self.assertEqual(done.stdout.split('\n')[:6],
['1 0 bu 1', '2 1 cu 1', '3 2 du 1', '4 0 eu 1', '5 1 fu 1', '6 0 zu'])
self.assertEqual([c[1:6] for c in server.configs],
[(1, 1280, 720, 1280, 736), (1, 1280, 720, 1920, 1088)])
self.assertEqual([p[:3] for p in server.packets],
[(1, 101, 0), (2, 102, 1), (3, 103, 2), (0, 104, 0), (1, 105, 1), (2, 50, 0)])
def test_other_programs_keep_the_real_libdrm(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
(tmp / 'main.c').write_text(
'void *SDL_LoadObject(const char *);\n'
'int main(void) { return SDL_LoadObject("libdrm.so.2") != 0; }\n')
binary = tmp / 'steam'
subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(tmp / 'main.c'),
str(VDEC), str(VENC), '-ldl'], check=True)
done = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stderr)
if __name__ == '__main__':
unittest.main()
+40
View File
@@ -136,6 +136,46 @@ class XboxLaunchTest(unittest.TestCase):
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
def test_launch_view_runs_from_a_short_drive_letter(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
prefix = root / 'compat/pfx'
prefix.mkdir(parents=True)
runtime = root / 'runtime/windows'; runtime.mkdir(parents=True)
for name in xbox['DLLS']:
(runtime / name).write_bytes(b'MZ-synthetic')
view = root / 'files/xbox-runtime/views/launch-4093691424/droiddeck-xbox-1ZpM3D'
(view / 'Bin').mkdir(parents=True)
command = root / 'command.json'
command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe']))
env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command)}
seen = []
def call(argv, **kwargs):
seen.append((argv, os.readlink(prefix / 'dosdevices/x:')))
return 0
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', side_effect=call):
initialize.return_value.returncode = 0
self.assertEqual(xbox['wine']([str(view / 'Bin/Game.exe')]), 0)
self.assertEqual(seen, [(['/selected/proton', 'waitforexitandrun', 'X:\\Bin\\Game.exe'], str(view))])
self.assertFalse(os.path.lexists(prefix / 'dosdevices/x:'))
def test_view_drive_keeps_drives_in_use_and_reuses_a_stale_view(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
devices = root / 'pfx/dosdevices'; devices.mkdir(parents=True)
views = root / 'views'
live = views / 'launch-1/droiddeck-xbox-live'; live.mkdir(parents=True)
view = views / 'launch-2/droiddeck-xbox-new'; view.mkdir(parents=True)
(devices / 'x:').symlink_to(live)
(devices / 'w:').symlink_to(root / 'games')
(devices / 'v:').symlink_to(views / 'launch-0/droiddeck-xbox-gone')
exe, link = xbox['view_drive'](root / 'pfx', str(view / 'Game.exe'))
self.assertEqual((exe, link), ('V:\\Game.exe', devices / 'v:'))
self.assertEqual(os.readlink(devices / 'v:'), str(view))
self.assertEqual(os.readlink(devices / 'x:'), str(live))
self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:'])
self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None))
def test_missing_runtime_classes_are_registered_once(self):
with tempfile.TemporaryDirectory() as root:
prefix = Path(root)