Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

fix(ps4): resolve VBLANK wait, Onion memory decoding, direct memory leaks, native affinity/priority, and EDS image CDN sizing

Rafael Abud Ferreiraa2ced7e1b5bd
diff --git a/src/display/display_ps4.cpp b/src/display/display_ps4.cpp
index 15c9d27..89bce3f 100644
--- a/src/display/display_ps4.cpp
+++ b/src/display/display_ps4.cpp
@@ -289,13 +289,18 @@ bool acquireBuffer(bool wait = true) {
for (int attempt = 0; attempt < 4; ++attempt) {
OrbisVideoOutFlipStatus status{};
int64_t shown = g_flipMarker; // no status: assume everything shown
- if (g_flipMarker && sceVideoOutGetFlipStatus(g_videoHandle, &status) == 0 && status.flipArg > 0)
+ bool gotStatus = (g_flipMarker && sceVideoOutGetFlipStatus(g_videoHandle, &status) == 0);
+ if (gotStatus && status.flipArg > 0)
shown = status.flipArg;
int onScreen = -1;
- for (int i = 0; i < kBuffers; ++i)
- if (g_bufferMarker[i] >= 0 && g_bufferMarker[i] <= shown &&
- (onScreen < 0 || g_bufferMarker[i] > g_bufferMarker[onScreen]))
- onScreen = i;
+ if (gotStatus && status.currentBuffer >= 0 && status.currentBuffer < kBuffers) {
+ onScreen = status.currentBuffer;
+ } else {
+ for (int i = 0; i < kBuffers; ++i)
+ if (g_bufferMarker[i] >= 0 && g_bufferMarker[i] <= shown &&
+ (onScreen < 0 || g_bufferMarker[i] > g_bufferMarker[onScreen]))
+ onScreen = i;
+ }
int best = -1;
for (int i = 0; i < kBuffers; ++i) {
if (i == onScreen || (g_bufferMarker[i] >= 0 && g_bufferMarker[i] > shown)) continue;
@@ -306,7 +311,7 @@ bool acquireBuffer(bool wait = true) {
return true;
}
if (!wait) return false;
- sceVideoOutWaitVblank();
+ sceVideoOutWaitVblank(g_videoHandle);
}
// Flip status not moving: fall back to round robin.
g_currentBuffer = static_cast<int>(g_flipMarker % kBuffers);
diff --git a/src/media/hw_decoder_ps4.cpp b/src/media/hw_decoder_ps4.cpp
index 5d6180b..5207b9a 100644
--- a/src/media/hw_decoder_ps4.cpp
+++ b/src/media/hw_decoder_ps4.cpp
@@ -8,7 +8,9 @@
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
+#include <mutex>
#include <unistd.h>
+#include <unordered_map>
extern "C" {
int sceSysmoduleLoadModule(uint32_t id);
@@ -17,9 +19,11 @@ int sceKernelLoadStartModule(const char* path, size_t argc, const void* argv, ui
size_t sceKernelGetDirectMemorySize();
int sceKernelAllocateDirectMemory(int64_t searchStart, int64_t searchEnd, size_t length, size_t alignment,
int memoryType, int64_t* physicalAddress);
+int sceKernelReleaseDirectMemory(int64_t physicalAddress, size_t length);
int sceKernelMapDirectMemory(void** address, size_t length, int protection, int flags, int64_t physicalAddress,
size_t alignment);
int sceKernelMapNamedFlexibleMemory(void** address, size_t length, int protection, int flags, const char* name);
+int sceKernelMunmap(void* address, size_t length);
// PS4 libSceVideodec2 structures
struct Vdec2DecoderConfig {
@@ -101,25 +105,71 @@ inline size_t align16k(size_t n) {
return (n + 0x3FFF) & ~static_cast<size_t>(0x3FFF);
}
-void* allocDirect(size_t size, int memoryType, const char* label) {
- if (size == 0) return nullptr;
- size = align16k(size);
+struct DirectMem {
+ void* addr = nullptr;
int64_t phys = 0;
+ size_t size = 0;
+};
+
+struct FlexibleMem {
+ void* addr = nullptr;
+ size_t size = 0;
+};
+
+DirectMem allocDirect(size_t size, int memoryType, const char* label) {
+ DirectMem mem{};
+ if (size == 0) return mem;
+ mem.size = align16k(size);
int rc = sceKernelAllocateDirectMemory(0, static_cast<int64_t>(sceKernelGetDirectMemorySize()),
- size, 0x4000, memoryType, &phys);
+ mem.size, 0x4000, memoryType, &mem.phys);
if (rc != 0) {
- XC_LOGW("hwdec: %s: allocate %zu bytes failed: 0x%08x", label, size, static_cast<unsigned>(rc));
- return nullptr;
+ XC_LOGW("hwdec: %s: allocate %zu bytes failed: 0x%08x", label, mem.size, static_cast<unsigned>(rc));
+ mem.size = 0;
+ return mem;
}
- void* addr = nullptr;
- rc = sceKernelMapDirectMemory(&addr, size, kProtectionRw, 0, phys, 0x4000);
- if (rc != 0 || !addr) {
- XC_LOGW("hwdec: %s: map %zu bytes failed: 0x%08x", label, size, static_cast<unsigned>(rc));
- return nullptr;
+ rc = sceKernelMapDirectMemory(&mem.addr, mem.size, kProtectionRw, 0, mem.phys, 0x4000);
+ if (rc != 0 || !mem.addr) {
+ XC_LOGW("hwdec: %s: map %zu bytes failed: 0x%08x", label, mem.size, static_cast<unsigned>(rc));
+ sceKernelReleaseDirectMemory(mem.phys, mem.size);
+ mem.addr = nullptr;
+ mem.phys = 0;
+ mem.size = 0;
+ return mem;
}
- return addr;
+ return mem;
}
+void freeDirect(DirectMem& mem) {
+ if (mem.addr && mem.size > 0) {
+ sceKernelMunmap(mem.addr, mem.size);
+ }
+ if (mem.size > 0) {
+ sceKernelReleaseDirectMemory(mem.phys, mem.size);
+ }
+ mem.addr = nullptr;
+ mem.phys = 0;
+ mem.size = 0;
+}
+
+void freeFlexible(FlexibleMem& mem) {
+ if (mem.addr && mem.size > 0) {
+ sceKernelMunmap(mem.addr, mem.size);
+ }
+ mem.addr = nullptr;
+ mem.size = 0;
+}
+
+struct DecoderAllocations {
+ DirectMem computeBuf;
+ FlexibleMem decCpu;
+ DirectMem decGpu;
+ DirectMem decCpuGpu;
+ DirectMem frameBuf;
+};
+
+static std::mutex s_allocMutex;
+static std::unordered_map<const HwDecoder*, DecoderAllocations> s_allocations;
+
} // namespace
HwDecoder::~HwDecoder() {
@@ -136,11 +186,25 @@ HwDecoder::~HwDecoder() {
sceVideodec2ReleaseComputeQueue(computeQueue_);
computeQueue_ = nullptr;
}
+ {
+ std::lock_guard<std::mutex> lock(s_allocMutex);
+ auto it = s_allocations.find(this);
+ if (it != s_allocations.end()) {
+ freeDirect(it->second.frameBuf);
+ freeDirect(it->second.decCpuGpu);
+ freeDirect(it->second.decGpu);
+ freeFlexible(it->second.decCpu);
+ freeDirect(it->second.computeBuf);
+ s_allocations.erase(it);
+ }
+ }
frameBuffer_ = nullptr;
frameBufferSize_ = 0;
}
bool HwDecoder::init(int maxWidth, int maxHeight) {
+ if (decoder_) return true;
+
int rc = sceSysmoduleLoadModule(kVideodecModule);
XC_LOGI("hwdec: sceSysmoduleLoadModule(VIDEODEC2) -> 0x%08x", static_cast<unsigned>(rc));
if (rc < 0 && rc != static_cast<int>(0x80020002) && rc != static_cast<int>(0x8002000e)) {
@@ -160,6 +224,30 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
}
sceSysmoduleLoadModuleInternal(0x80000015);
+ DecoderAllocations allocs{};
+ auto rollback = [&]() {
+ if (decoder_) {
+ Vdec2Frame frm{};
+ frm.size = sizeof(frm);
+ Vdec2Output out{};
+ out.size = sizeof(out);
+ sceVideodec2Flush(decoder_, &frm, &out);
+ sceVideodec2DeleteDecoder(decoder_);
+ decoder_ = nullptr;
+ }
+ if (computeQueue_) {
+ sceVideodec2ReleaseComputeQueue(computeQueue_);
+ computeQueue_ = nullptr;
+ }
+ freeDirect(allocs.frameBuf);
+ frameBuffer_ = nullptr;
+ frameBufferSize_ = 0;
+ freeDirect(allocs.decCpuGpu);
+ freeDirect(allocs.decGpu);
+ freeFlexible(allocs.decCpu);
+ freeDirect(allocs.computeBuf);
+ };
+
// Query and allocate compute queue memory
Vdec2ComputeMemory computeMem{};
computeMem.size = sizeof(computeMem);
@@ -171,11 +259,11 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
}
size_t computeBytes = align16k(computeMem.cpuGpuSize);
- void* computeBuf = allocDirect(computeBytes, kMemoryTypeOnion, "compute queue");
- if (!computeBuf) {
+ allocs.computeBuf = allocDirect(computeBytes, kMemoryTypeOnion, "compute queue");
+ if (!allocs.computeBuf.addr) {
return false;
}
- computeMem.cpuGpu = computeBuf;
+ computeMem.cpuGpu = allocs.computeBuf.addr;
// Allocate compute queue across pipes 0..4
void* queue = nullptr;
@@ -192,6 +280,7 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
}
if (!queue) {
XC_LOGW("hwdec: failed to allocate compute queue on all pipes");
+ rollback();
return false;
}
computeQueue_ = queue;
@@ -216,6 +305,7 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
rc = sceVideodec2QueryDecoderMemoryInfo(&decCfg, &decMem);
if (rc != 0) {
XC_LOGW("hwdec: sceVideodec2QueryDecoderMemoryInfo failed: 0x%08x", static_cast<unsigned>(rc));
+ rollback();
return false;
}
@@ -225,35 +315,53 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
rc = sceKernelMapNamedFlexibleMemory(&cpuMem, cpuBytes, kProtectionRw, 0, "PSBoxVdecCpu");
if (rc != 0 || !cpuMem) {
XC_LOGW("hwdec: allocate flexible memory %zu failed: 0x%08x", cpuBytes, static_cast<unsigned>(rc));
+ rollback();
return false;
}
decMem.cpu = cpuMem;
decMem.cpuSize = cpuBytes;
+ allocs.decCpu = {cpuMem, cpuBytes};
}
if (decMem.gpuSize > 0) {
- decMem.gpu = allocDirect(decMem.gpuSize, kMemoryTypeGarlic, "decoder gpu");
- if (!decMem.gpu) return false;
+ allocs.decGpu = allocDirect(decMem.gpuSize, kMemoryTypeGarlic, "decoder gpu");
+ if (!allocs.decGpu.addr) {
+ rollback();
+ return false;
+ }
+ decMem.gpu = allocs.decGpu.addr;
}
if (decMem.cpuGpuSize > 0) {
- decMem.cpuGpu = allocDirect(decMem.cpuGpuSize, kMemoryTypeOnion, "decoder cpu+gpu");
- if (!decMem.cpuGpu) return false;
+ allocs.decCpuGpu = allocDirect(decMem.cpuGpuSize, kMemoryTypeOnion, "decoder cpu+gpu");
+ if (!allocs.decCpuGpu.addr) {
+ rollback();
+ return false;
+ }
+ decMem.cpuGpu = allocs.decCpuGpu.addr;
}
frameBufferSize_ = align16k(decMem.maxFrameSize > 0 ? decMem.maxFrameSize : (static_cast<size_t>(maxWidth) * maxHeight * 3 / 2 + 64));
- frameBuffer_ = static_cast<uint8_t*>(allocDirect(frameBufferSize_, kMemoryTypeGarlic, "frame buffer"));
- if (!frameBuffer_) {
+ allocs.frameBuf = allocDirect(frameBufferSize_, kMemoryTypeOnion, "frame buffer");
+ if (!allocs.frameBuf.addr) {
+ rollback();
return false;
}
+ frameBuffer_ = static_cast<uint8_t*>(allocs.frameBuf.addr);
rc = sceVideodec2CreateDecoder(&decCfg, &decMem, &decoder_);
XC_LOGI("hwdec: sceVideodec2CreateDecoder -> 0x%08x", static_cast<unsigned>(rc));
if (rc != 0 || !decoder_) {
decoder_ = nullptr;
+ rollback();
return false;
}
+ {
+ std::lock_guard<std::mutex> lock(s_allocMutex);
+ s_allocations[this] = allocs;
+ }
+
XC_LOGI("hwdec: PS4 decoder running, frame buffer %zu bytes", frameBufferSize_);
return true;
}
diff --git a/src/platform/ps4/platform_ps4.cpp b/src/platform/ps4/platform_ps4.cpp
index 61dcc3e..de334fc 100644
--- a/src/platform/ps4/platform_ps4.cpp
+++ b/src/platform/ps4/platform_ps4.cpp
@@ -53,6 +53,9 @@ int sceSysmoduleLoadModule(uint32_t id);
int sceSysmoduleLoadModuleInternal(uint32_t id);
int sceRandomGetRandomNumber(void* buf, size_t size);
int scePthreadCreate(pthread_t* thread, const pthread_attr_t* attr, void* (*entry)(void*), void* arg, const char* name);
+pthread_t scePthreadSelf(void);
+int scePthreadSetaffinity(pthread_t thread, uint64_t mask);
+int scePthreadSetprio(pthread_t thread, int prio);
static inline int getNetErrno(int ret) {
int* err = sceNetErrnoLoc();
@@ -922,18 +925,17 @@ void setThreadAffinity(ThreadRole role, const char* name) {
if (name && *name) {
pthread_set_name_np(pthread_self(), name);
}
- static cpu_set_t s_procMask;
- static bool s_procMaskQueried = false;
+ static std::once_flag s_maskOnce;
static int s_allowedCpus[32];
static int s_numAllowedCpus = 0;
- if (!s_procMaskQueried) {
- s_procMaskQueried = true;
- CPU_ZERO(&s_procMask);
- int grc = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &s_procMask);
+ std::call_once(s_maskOnce, [&]() {
+ cpu_set_t procMask;
+ CPU_ZERO(&procMask);
+ int grc = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &procMask);
if (grc == 0) {
for (int i = 0; i < 32; ++i) {
- if (CPU_ISSET(i, &s_procMask)) {
+ if (CPU_ISSET(i, &procMask)) {
s_allowedCpus[s_numAllowedCpus++] = i;
}
}
@@ -949,17 +951,18 @@ void setThreadAffinity(ThreadRole role, const char* name) {
for (int i = 0; i < s_numAllowedCpus; ++i) {
XC_LOGI(" cpu slot %d: logical core %d", i, s_allowedCpus[i]);
}
- }
+ });
if (s_numAllowedCpus <= 1) {
return;
}
- cpu_set_t mask;
- CPU_ZERO(&mask);
+ uint64_t orbisMask = 0;
auto setSlot = [&](int slotIndex) {
int idx = s_allowedCpus[slotIndex % s_numAllowedCpus];
- CPU_SET(idx, &mask);
+ if (idx >= 0 && idx < 64) {
+ orbisMask |= (UINT64_C(1) << idx);
+ }
};
switch (role) {
@@ -984,22 +987,22 @@ void setThreadAffinity(ThreadRole role, const char* name) {
}
break;
}
- int rc = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &mask);
+ int rc = scePthreadSetaffinity(scePthreadSelf(), orbisMask);
if (rc != 0) {
- XC_LOGW("pthread_setaffinity_np(%s): %d", name ? name : "thread", rc);
+ XC_LOGW("scePthreadSetaffinity(%s, 0x%llx): 0x%08x", name ? name : "thread",
+ static_cast<unsigned long long>(orbisMask), static_cast<unsigned>(rc));
} else {
- XC_LOGI("thread %s pinned to role %d", name ? name : "unknown", static_cast<int>(role));
+ XC_LOGI("thread %s pinned to role %d (mask 0x%llx)", name ? name : "unknown",
+ static_cast<int>(role), static_cast<unsigned long long>(orbisMask));
}
}
void setThreadRealtimePriority() {
- struct sched_param param{};
- param.sched_priority = 64; // Orbis audio realtime priority
- int rc = pthread_setschedparam(pthread_self(), SCHED_RR, &param);
+ int rc = scePthreadSetprio(scePthreadSelf(), 256);
if (rc != 0) {
- XC_LOGW("pthread_setschedparam(SCHED_RR, 64): %d (the audio thread keeps the default)", rc);
+ XC_LOGW("scePthreadSetprio(256): 0x%08x (the audio thread keeps the default)", static_cast<unsigned>(rc));
} else {
- XC_LOGI("thread elevated to SCHED_RR (prio=64)");
+ XC_LOGI("thread elevated to realtime priority (scePthreadSetprio 256)");
}
}
diff --git a/src/ui/image_cache.cpp b/src/ui/image_cache.cpp
index 9f4d3f5..9f984ef 100644
--- a/src/ui/image_cache.cpp
+++ b/src/ui/image_cache.cpp
@@ -73,21 +73,21 @@ Image coverResize(const Image& src, int w, int h) {
return out;
}
-namespace {
-
-// store-images.s-microsoft.com resizes on request: fetch close to the size
-// we draw instead of the multi-megapixel original.
+// store-images.s-microsoft.com and images-eds-ssl.xboxlive.com resize on request:
+// fetch close to the size we draw instead of the multi-megapixel original.
std::string sizedUrl(std::string url, int w, int h) {
+ if (url.empty() || w <= 0 || h <= 0) return url;
if (url.rfind("//", 0) == 0) url = "https:" + url;
if (url.find("store-images.s-microsoft.com") != std::string::npos) {
url += url.find('?') == std::string::npos ? "?" : "&";
- url += "w=" + std::to_string(w) + "&h=" + std::to_string(h) + "&mode=scale&q=90&format=jpg";
+ url += "w=" + std::to_string(w) + "&h=" + std::to_string(h) + "&mode=scale&q=75&format=jpg";
+ } else if (url.find("images-eds-ssl.xboxlive.com") != std::string::npos) {
+ url += url.find('?') == std::string::npos ? "?" : "&";
+ url += "w=" + std::to_string(w) + "&h=" + std::to_string(h) + "&format=jpg";
}
return url;
}
-} // namespace
-
ImageCache::ImageCache(std::function<void()> onReady, size_t budgetBytes, std::string diskDir,
size_t diskBudgetBytes)
: onReady_(std::move(onReady)), budget_(budgetBytes), diskDir_(std::move(diskDir)), diskBudget_(diskBudgetBytes) {
diff --git a/src/ui/image_cache.h b/src/ui/image_cache.h
index d96fd9e..33f90f5 100644
--- a/src/ui/image_cache.h
+++ b/src/ui/image_cache.h
@@ -27,6 +27,8 @@ namespace xc::ui {
bool decodeImage(const std::string& bytes, Image& out);
// Scales `src` to fill w x h, cropping the excess around the centre.
Image coverResize(const Image& src, int w, int h);
+// Sized URL rewrite for store-images and images-eds-ssl.
+std::string sizedUrl(std::string url, int w, int h);
class ImageCache {
public:
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index e2f8972..1334864 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -6552,7 +6552,32 @@ void testPhase1BugFixesAndPhase2Optimizations() {
}
}
+static void testSizedUrl() {
+ // Protocol-relative URLs
+ CHECK(ui::sizedUrl("//store-images.s-microsoft.com/image.png", 300, 450) ==
+ "https://store-images.s-microsoft.com/image.png?w=300&h=450&mode=scale&q=75&format=jpg");
+ // store-images q=75
+ CHECK(ui::sizedUrl("https://store-images.s-microsoft.com/image.png", 1920, 1080) ==
+ "https://store-images.s-microsoft.com/image.png?w=1920&h=1080&mode=scale&q=75&format=jpg");
+ CHECK(ui::sizedUrl("https://store-images.s-microsoft.com/image.png?param=1", 100, 100) ==
+ "https://store-images.s-microsoft.com/image.png?param=1&w=100&h=100&mode=scale&q=75&format=jpg");
+ // images-eds-ssl.xboxlive.com format=jpg without quality
+ CHECK(ui::sizedUrl("https://images-eds-ssl.xboxlive.com/image.png", 400, 600) ==
+ "https://images-eds-ssl.xboxlive.com/image.png?w=400&h=600&format=jpg");
+ CHECK(ui::sizedUrl("https://images-eds-ssl.xboxlive.com/image.png?foo=bar", 200, 300) ==
+ "https://images-eds-ssl.xboxlive.com/image.png?foo=bar&w=200&h=300&format=jpg");
+ // other URLs untouched
+ CHECK(ui::sizedUrl("https://assets.xbox.com/img.png", 100, 100) == "https://assets.xbox.com/img.png");
+ // invalid dimensions or empty string untouched
+ CHECK(ui::sizedUrl("", 100, 100).empty());
+ CHECK(ui::sizedUrl("https://store-images.s-microsoft.com/image.png", 0, 100) ==
+ "https://store-images.s-microsoft.com/image.png");
+ CHECK(ui::sizedUrl("https://images-eds-ssl.xboxlive.com/image.png", 100, -1) ==
+ "https://images-eds-ssl.xboxlive.com/image.png");
+}
+
int main() {
+ testSizedUrl();
testPhase1BugFixesAndPhase2Optimizations();
testBlock4OwnershipAndRecents();
testBloco3Corrections();
diff --git a/tools/ps4/fetch-toolchain.sh b/tools/ps4/fetch-toolchain.sh
index b7310bc..cb0e113 100755
--- a/tools/ps4/fetch-toolchain.sh
+++ b/tools/ps4/fetch-toolchain.sh
@@ -35,4 +35,12 @@ if [ -f "$DEST/include/bits/alltypes.h" ]; then
sed -i 's/typedef struct { unsigned __attr\[2\]; } pthread_rwlockattr_t;/typedef struct { void *__attr; } pthread_rwlockattr_t;/' "$DEST/include/bits/alltypes.h"
fi
+if [ -f "$DEST/include/orbis/VideoOut.h" ]; then
+ sed -i 's/void sceVideoOutWaitVblank();/int32_t sceVideoOutWaitVblank(int32_t handle);/' "$DEST/include/orbis/VideoOut.h"
+fi
+
+if [ -f "$DEST/include/orbis/libkernel.h" ]; then
+ sed -i 's/void scePthreadSetaffinity();/int32_t scePthreadSetaffinity(OrbisPthread, uint64_t);/' "$DEST/include/orbis/libkernel.h"
+fi
+
echo "OpenOrbis toolchain installed at $DEST."