Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

feat(diag): log build commit ID, PS4 memory/thread snapshots, WebRTC ICE stages, and hwdec allocations

Rafael Abud Ferreirad3180ccdabc1
diff --git a/CMakeLists.txt b/CMakeLists.txt
index dc8b86f..5a51dc2 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -141,6 +141,16 @@ if(NOT MSVC)
target_compile_options(xcloud_appcore PRIVATE -Wall -Wextra -Wno-unused-parameter)
endif()
+# The commit each build came from, written to the log at start-up: a tester's log
+# then says which package produced it.
+set(XC_BUILD_ID_HEADER "${CMAKE_BINARY_DIR}/generated/build_id.h")
+set(XC_BUILD_ID_ARGS -DSRC=${CMAKE_SOURCE_DIR} -DOUT=${XC_BUILD_ID_HEADER} -P ${CMAKE_SOURCE_DIR}/cmake/build_id.cmake)
+execute_process(COMMAND ${CMAKE_COMMAND} ${XC_BUILD_ID_ARGS})
+add_custom_target(xcloud_build_id COMMAND ${CMAKE_COMMAND} ${XC_BUILD_ID_ARGS}
+ BYPRODUCTS ${XC_BUILD_ID_HEADER} VERBATIM)
+add_dependencies(xcloud_appcore xcloud_build_id)
+target_include_directories(xcloud_appcore PRIVATE ${CMAKE_BINARY_DIR}/generated)
+
if(XCLOUD_PS5)
target_sources(xcloud_core PRIVATE src/platform/ps5/platform_ps5.cpp src/platform/ps5/libc_compat.c src/platform/ps5/net_probe.cpp src/platform/ps5/keyboard_ps5.cpp)
diff --git a/cmake/build_id.cmake b/cmake/build_id.cmake
new file mode 100644
index 0000000..4156c85
--- /dev/null
+++ b/cmake/build_id.cmake
@@ -0,0 +1,29 @@
+# Writes OUT (a header) with XC_BUILD_ID: the commit the build came from, plus
+# "-dirty" when tracked files differ from it. Run in script mode on every build;
+# the header is only rewritten when the id changes, so nothing else recompiles.
+# cmake -DSRC=<source dir> -DOUT=<header> -P build_id.cmake
+set(id "")
+set(dirty "")
+find_package(Git QUIET)
+if(GIT_FOUND)
+ execute_process(COMMAND "${GIT_EXECUTABLE}" rev-parse --short=7 HEAD
+ WORKING_DIRECTORY "${SRC}" OUTPUT_VARIABLE id
+ OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
+ execute_process(COMMAND "${GIT_EXECUTABLE}" status --porcelain --untracked-files=no --ignore-submodules=dirty
+ WORKING_DIRECTORY "${SRC}" OUTPUT_VARIABLE dirty
+ OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
+endif()
+if(id STREQUAL "")
+ set(id "unknown")
+elseif(NOT dirty STREQUAL "")
+ string(APPEND id "-dirty")
+endif()
+
+set(content "// Generated by cmake/build_id.cmake: do not edit.\n#pragma once\n#define XC_BUILD_ID \"${id}\"\n")
+set(old "")
+if(EXISTS "${OUT}")
+ file(READ "${OUT}" old)
+endif()
+if(NOT old STREQUAL content)
+ file(WRITE "${OUT}" "${content}")
+endif()
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index fe1949c..933f701 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -8,6 +8,7 @@
// and autoplay.cpp (the unattended tests). What only some platforms do is
// behind app/shell.h.
#include "app/app_core.h"
+#include "build_id.h" // generated: XC_BUILD_ID (cmake/build_id.cmake)
#include "app/app_state.h"
#include "app/autoplay.h"
@@ -254,7 +255,9 @@ bool coreStartup() {
if (!logOk)
XC_LOGW("could not open xcloud.log in %s: log kept in memory", platform::dataDir().c_str());
XC_LOGI("=== PSBox Cloud Gaming starting ===");
- XC_LOGI("firmware %s, PSBox %s", platform::firmwareVersion().c_str(), XC_APP_VERSION);
+ XC_LOGI("firmware %s, PSBox %s (build %s, %s)", platform::firmwareVersion().c_str(), XC_APP_VERSION, XC_BUILD_ID,
+ platform::platformName().c_str());
+ if (std::string res = platform::diagnostics(); !res.empty()) XC_LOGI("resources at start: %s", res.c_str());
// Did the last session go down? (A crash leaves a marker; being closed
// from the system's menu doesn't.) Offered as a report once signed in.
g_lastCrash = crash::takePrevious(crashMarkerPath());
diff --git a/src/app/stream_player.cpp b/src/app/stream_player.cpp
index 387d7f4..2c1d7c6 100644
--- a/src/app/stream_player.cpp
+++ b/src/app/stream_player.cpp
@@ -578,6 +578,8 @@ struct StreamPlayer::Impl {
platform::notify(ui::trf(ui::Str::IdleWarning, std::to_string(seconds)));
};
cb.closed = [this](const std::string& reason, bool recoverable) {
+ if (std::string res = platform::diagnostics(); !res.empty())
+ XC_LOGI("resources at stream close: %s", res.c_str());
// A lost connection: the worker's tick() reconnects. The server
// ending the session (or no game left) ends the stream.
if (recoverable && running) {
diff --git a/src/app/worker_stream.cpp b/src/app/worker_stream.cpp
index 7107e63..799277e 100644
--- a/src/app/worker_stream.cpp
+++ b/src/app/worker_stream.cpp
@@ -436,6 +436,7 @@ std::string play(auth::AuthManager& am, xcloud::GssvClient& gssv, const ui::Game
g_stageTitle = game.titleId;
g_stageProduct = game.productId;
crash::setStage(gssv.isHome() ? "starting own Xbox" : ("starting " + game.titleId).c_str());
+ if (std::string res = platform::diagnostics(); !res.empty()) XC_LOGI("resources before the stream: %s", res.c_str());
int status = 0;
bool started = gssv.startSession(game.titleId, streamLocale, err, &status);
if (!started && status == 401 && !g_cancel) {
diff --git a/src/media/hw_decoder_ps4.cpp b/src/media/hw_decoder_ps4.cpp
index f2d8be6..fb47f3e 100644
--- a/src/media/hw_decoder_ps4.cpp
+++ b/src/media/hw_decoder_ps4.cpp
@@ -315,6 +315,9 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
rollback();
return false;
}
+ XC_LOGI("hwdec: decoder memory query: cpu=%llu gpu=%llu cpuGpu=%llu maxFrame=%llu bytes",
+ static_cast<unsigned long long>(decMem.cpuSize), static_cast<unsigned long long>(decMem.gpuSize),
+ static_cast<unsigned long long>(decMem.cpuGpuSize), static_cast<unsigned long long>(decMem.maxFrameSize));
if (decMem.cpuSize > 0) {
size_t cpuBytes = align16k(decMem.cpuSize);
@@ -322,6 +325,7 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
if (allocs.decCpuDirect.addr) {
decMem.cpu = allocs.decCpuDirect.addr;
decMem.cpuSize = allocs.decCpuDirect.size;
+ XC_LOGI("hwdec: decoder cpu %zu bytes allocated in direct Onion memory", cpuBytes);
} else {
XC_LOGW("hwdec: direct onion memory for cpu failed, falling back to flexible memory");
void* cpuMem = nullptr;
@@ -334,6 +338,7 @@ bool HwDecoder::init(int maxWidth, int maxHeight) {
decMem.cpu = cpuMem;
decMem.cpuSize = cpuBytes;
allocs.decCpuFlex = {cpuMem, cpuBytes};
+ XC_LOGI("hwdec: decoder cpu %zu bytes allocated in flexible memory", cpuBytes);
}
}
diff --git a/src/platform/android/platform_android.cpp b/src/platform/android/platform_android.cpp
index ab70a4a..93b27cb 100644
--- a/src/platform/android/platform_android.cpp
+++ b/src/platform/android/platform_android.cpp
@@ -116,6 +116,7 @@ KeyboardStatus pollSystemKeyboard(std::string&) { return KeyboardStatus::Closed;
bool restartApp() { return false; }
std::string firmwareVersion() { return {}; }
+std::string diagnostics() { return {}; }
std::string platformName() { return "Android"; }
void setThreadAffinity(ThreadRole, const char*) {}
diff --git a/src/platform/linux/platform_linux.cpp b/src/platform/linux/platform_linux.cpp
index 855cbe1..ea91578 100644
--- a/src/platform/linux/platform_linux.cpp
+++ b/src/platform/linux/platform_linux.cpp
@@ -168,6 +168,7 @@ KeyboardStatus pollSystemKeyboard(std::string&) { return KeyboardStatus::Closed;
bool restartApp() { return false; }
std::string firmwareVersion() { return {}; }
+std::string diagnostics() { return {}; }
std::string platformName() { return "Linux"; }
void setThreadAffinity(ThreadRole role, const char* name) {
diff --git a/src/platform/platform.h b/src/platform/platform.h
index 1f0827f..f39147b 100644
--- a/src/platform/platform.h
+++ b/src/platform/platform.h
@@ -95,6 +95,10 @@ bool restartApp();
// The console's system software ("13.00"); empty where unknown.
std::string firmwareVersion();
+// One line for the log about the resources left (free memory, threads...), to
+// tell what ran out when something fails; empty where there is nothing to report.
+std::string diagnostics();
+
// Platform description ("PlayStation 4", "PlayStation 5", "Linux", etc.).
std::string platformName();
diff --git a/src/platform/ps4/platform_ps4.cpp b/src/platform/ps4/platform_ps4.cpp
index 48830f6..be52650 100644
--- a/src/platform/ps4/platform_ps4.cpp
+++ b/src/platform/ps4/platform_ps4.cpp
@@ -159,13 +159,40 @@ long sysconf(int name) {
}
static std::atomic<int> s_threadsCreated{0};
-static std::atomic<bool> s_threadFailLogged{false};
+static std::atomic<int> s_threadsLive{0};
+static std::atomic<int> s_threadFailures{0};
+
+// Counts the threads still running: the key's destructor runs when a thread ends,
+// whether it returns or calls pthread_exit.
+static pthread_key_t s_liveKey;
+static std::once_flag s_liveKeyOnce;
+static bool s_liveKeyOk = false;
+
+struct ThreadStart {
+ void* (*fn)(void*);
+ void* arg;
+};
+
+static void* threadTrampoline(void* p) {
+ ThreadStart start = *static_cast<ThreadStart*>(p);
+ delete static_cast<ThreadStart*>(p);
+ if (s_liveKeyOk) {
+ s_threadsLive.fetch_add(1, std::memory_order_relaxed);
+ pthread_setspecific(s_liveKey, reinterpret_cast<void*>(1));
+ }
+ return start.fn(start.arg);
+}
int pthread_create(pthread_t* thread, const pthread_attr_t* attr,
void* (*start_routine)(void*), void* arg) {
if (!thread || !start_routine) {
return EINVAL;
}
+ std::call_once(s_liveKeyOnce, [] {
+ s_liveKeyOk = pthread_key_create(&s_liveKey, [](void*) {
+ s_threadsLive.fetch_sub(1, std::memory_order_relaxed);
+ }) == 0;
+ });
pthread_attr_t customAttr;
bool createdAttr = false;
@@ -187,15 +214,23 @@ int pthread_create(pthread_t* thread, const pthread_attr_t* attr,
if (sym && sym != reinterpret_cast<void*>(&pthread_create)) {
real_pthread_create = reinterpret_cast<RealPthreadCreateFn>(sym);
}
+ XC_LOGI("threads: created with %s, %ld cores reported, default stack 1 MB",
+ real_pthread_create ? "libkernel pthread_create (dlsym)" : "scePthreadCreate",
+ sysconf(84 /*musl _SC_NPROCESSORS_ONLN*/));
}
+ size_t stackBytes = 0;
+ if (attr) pthread_attr_getstacksize(attr, &stackBytes);
+
+ auto* start = new ThreadStart{start_routine, arg};
int rc = -1;
if (real_pthread_create) {
- rc = real_pthread_create(thread, attr, start_routine, arg);
+ rc = real_pthread_create(thread, attr, threadTrampoline, start);
}
+ int realRc = rc;
int sceRc = 0;
if (rc != 0) {
- rc = scePthreadCreate(thread, attr, start_routine, arg, "xcloud_worker");
+ rc = scePthreadCreate(thread, attr, threadTrampoline, start, "xcloud_worker");
sceRc = rc;
if (rc < 0) {
uint32_t uret = static_cast<uint32_t>(rc);
@@ -208,11 +243,15 @@ int pthread_create(pthread_t* thread, const pthread_attr_t* attr,
}
if (rc == 0) {
s_threadsCreated.fetch_add(1, std::memory_order_relaxed);
- } else if (!s_threadFailLogged.exchange(true)) {
- size_t freeFlex = 0;
- sceKernelAvailableFlexibleMemorySize(&freeFlex);
- XC_LOGE("pthread_create failed: rc=%d (sce 0x%08x) after %d threads, %zu MB flexible memory free",
- rc, static_cast<unsigned>(sceRc), s_threadsCreated.load(), freeFlex >> 20);
+ } else {
+ delete start;
+ // The first few, then every 100th: a runaway loop must not flood the log.
+ int n = s_threadFailures.fetch_add(1) + 1;
+ if (n <= 3 || n % 100 == 0) {
+ XC_LOGE("pthread_create failed #%d: rc=%d %s (sce 0x%08x, pthread_create %d), stack %zu KB; %s", n, rc,
+ std::strerror(rc), static_cast<unsigned>(sceRc), realRc, stackBytes >> 10,
+ xc::platform::diagnostics().c_str());
+ }
}
return rc;
}
@@ -228,6 +267,8 @@ int socket(int domain, int type, int protocol) {
int s = sceNetSocket("", domain, baseType, protocol);
if (s < 0) {
errno = getNetErrno(s);
+ XC_LOGW("net: sceNetSocket(domain=%d, type=0x%x, proto=%d) failed: 0x%08x (errno=%d)",
+ domain, type, protocol, static_cast<unsigned>(s), errno);
return -1;
}
#ifndef SOCK_NONBLOCK
@@ -266,6 +307,8 @@ int bind(int fd, const struct sockaddr* addr, socklen_t len) {
int rc = sceNetBind(fd, &boundAddr, sizeof(boundAddr));
if (rc < 0) {
errno = getNetErrno(rc);
+ XC_LOGW("net: sceNetBind(fd=%d, port=%u) failed: 0x%08x (errno=%d)",
+ fd, static_cast<unsigned>(port), static_cast<unsigned>(rc), errno);
return -1;
}
if (port != 0) {
@@ -658,6 +701,7 @@ extern "C" int getifaddrs(struct ifaddrs** ifap) {
mask.sin_len = sizeof(struct sockaddr_in);
mask.sin_addr.s_addr = htonl(0xFFFFFF00);
+ const char* src = "none";
// 1. Query sceNetCtlGetInfo from libSceNetCtl
OrbisNetCtlInfo info{};
int ctlRc = sceNetCtlGetInfo(14 /*ORBIS_NET_CTL_INFO_IP_ADDRESS*/, &info);
@@ -671,6 +715,7 @@ extern "C" int getifaddrs(struct ifaddrs** ifap) {
if (ctlRc == 0 && info.ip_address[0] != '\0') {
info.ip_address[sizeof(info.ip_address) - 1] = '\0';
inet_pton(AF_INET, info.ip_address, &local.sin_addr);
+ src = "sceNetCtlGetInfo";
OrbisNetCtlInfo maskInfo{};
if (sceNetCtlGetInfo(15 /*ORBIS_NET_CTL_INFO_NETMASK*/, &maskInfo) == 0 && maskInfo.netmask[0] != '\0') {
@@ -691,6 +736,7 @@ extern "C" int getifaddrs(struct ifaddrs** ifap) {
if (connect(s, reinterpret_cast<struct sockaddr*>(&probe), sizeof(probe)) == 0) {
socklen_t localLen = sizeof(local);
getsockname(s, reinterpret_cast<struct sockaddr*>(&local), &localLen);
+ if (local.sin_addr.s_addr != 0) src = "udp-route-probe";
}
close(s);
}
@@ -705,6 +751,7 @@ extern "C" int getifaddrs(struct ifaddrs** ifap) {
char* nl = std::strpbrk(buf, "\r\n ");
if (nl) *nl = '\0';
inet_pton(AF_INET, buf, &local.sin_addr);
+ if (local.sin_addr.s_addr != 0) src = "local_ip.txt";
}
std::fclose(fp);
}
@@ -713,6 +760,12 @@ extern "C" int getifaddrs(struct ifaddrs** ifap) {
// 4. Default fallback: ensure libjuice never receives an empty interface list
if (local.sin_addr.s_addr == 0) {
inet_pton(AF_INET, "192.168.15.30", &local.sin_addr);
+ src = "fallback-default";
+ }
+ static const char* s_lastIfSrc = nullptr;
+ if (s_lastIfSrc != src) {
+ s_lastIfSrc = src;
+ XC_LOGI("net: getifaddrs resolved eth0 via %s (ctlRc=0x%08x)", src, static_cast<unsigned>(ctlRc));
}
local.sin_family = AF_INET;
local.sin_len = sizeof(struct sockaddr_in);
@@ -763,6 +816,9 @@ int sceNetPoolCreate(const char* name, int size, int flags);
int sceNetResolverCreate(const char* name, int memid, int flags);
int sceNetResolverStartNtoa(int rid, const char* hostname, uint32_t* addr, int timeout, int retry, int flags);
int sceNetResolverDestroy(int rid);
+int sceKernelAvailableDirectMemorySize(off_t start, off_t end, size_t align, off_t* startOut, size_t* sizeOut);
+size_t sceKernelGetDirectMemorySize(void);
+int sceKernelIsNeoMode(void);
}
namespace xc::platform {
@@ -939,6 +995,19 @@ std::string platformName() {
return "PlayStation 4";
}
+std::string diagnostics() {
+ size_t flex = 0;
+ sceKernelAvailableFlexibleMemorySize(&flex);
+ off_t start = 0;
+ size_t direct = 0;
+ sceKernelAvailableDirectMemorySize(0, static_cast<off_t>(sceKernelGetDirectMemorySize()), 16384, &start, &direct);
+ char text[192];
+ std::snprintf(text, sizeof text, "%s, flexible %zu MB free, direct %zu MB free (largest block), threads %d live / %d created",
+ sceKernelIsNeoMode() ? "PS4 Pro" : "PS4", flex >> 20, direct >> 20,
+ s_threadsLive.load(), s_threadsCreated.load());
+ return text;
+}
+
void makePrivate(const std::string&) {}
void notify(const std::string& text) { notify(text, text); }
diff --git a/src/platform/ps5/platform_ps5.cpp b/src/platform/ps5/platform_ps5.cpp
index 6fe500a..c18c3b6 100644
--- a/src/platform/ps5/platform_ps5.cpp
+++ b/src/platform/ps5/platform_ps5.cpp
@@ -222,6 +222,8 @@ bool restartApp() {
return false;
}
+std::string diagnostics() { return {}; }
+
std::string firmwareVersion() {
// The kernel's: 0x13600007 is 13.60 (the version the console's settings
// show). sceKernelGetSystemSwVersion said "13.590.001" on a 13.60 console.
diff --git a/src/platform/windows/platform_windows.cpp b/src/platform/windows/platform_windows.cpp
index ac6a961..0e2934c 100644
--- a/src/platform/windows/platform_windows.cpp
+++ b/src/platform/windows/platform_windows.cpp
@@ -331,6 +331,7 @@ KeyboardStatus pollSystemKeyboard(std::string&) { return KeyboardStatus::Closed;
bool restartApp() { return false; }
std::string firmwareVersion() { return {}; }
+std::string diagnostics() { return {}; }
std::string platformName() { return "Windows"; }
bool readFile(const std::string& path, std::string& out) {
diff --git a/src/stream/stream_session.cpp b/src/stream/stream_session.cpp
index e24ad57..f861851 100644
--- a/src/stream/stream_session.cpp
+++ b/src/stream/stream_session.cpp
@@ -20,6 +20,7 @@
#include <condition_variable>
#include <cstdio>
#include <mutex>
+#include <sstream>
#include <thread>
#include <vector>
@@ -34,6 +35,14 @@ constexpr const char* kClientAppInstallId = "c97d7ee0-73b2-4239-bf1d-9d805a33842
// SystemUiType of the system UIs this client draws itself.
constexpr int kShowVirtualKeyboard = 10;
+// libdatachannel's name for one of its states ("checking", "srflx"...), for the log.
+template <class T>
+std::string named(const T& value) {
+ std::ostringstream out;
+ out << value;
+ return out.str();
+}
+
std::string uuid4() {
uint8_t b[16];
platform::randomBytes(b, sizeof b);
@@ -421,22 +430,29 @@ struct StreamSession::Impl {
void createPeer() {
initRtcLogging();
XC_LOGI("webrtc: createPeer starting");
+ if (std::string res = platform::diagnostics(); !res.empty()) XC_LOGI("webrtc: resources before the peer: %s", res.c_str());
rtc::Configuration config;
config.disableAutoNegotiation = true;
try {
pc = std::make_shared<rtc::PeerConnection>(config);
} catch (const std::exception& e) {
XC_LOGE("webrtc: PeerConnection failed to create: %s", e.what());
+ if (std::string res = platform::diagnostics(); !res.empty()) XC_LOGE("webrtc: resources at the failure: %s", res.c_str());
fail(std::string("WebRTC peer creation failed: ") + e.what());
return;
}
XC_LOGI("webrtc: PeerConnection created");
+ if (std::string res = platform::diagnostics(); !res.empty()) XC_LOGI("webrtc: resources after the peer: %s", res.c_str());
pc->onLocalCandidate([this](rtc::Candidate c) {
+ // Its type and transport only: the address stays out of the log.
+ XC_LOGI("webrtc: local ICE candidate: %s %s", named(c.type()).c_str(),
+ c.transportType() == rtc::Candidate::TransportType::Udp ? "udp" : "tcp");
std::lock_guard<std::mutex> lock(mutex);
localCandidates.push_back(std::move(c));
});
pc->onGatheringStateChange([this](rtc::PeerConnection::GatheringState s) {
+ XC_LOGI("webrtc: ICE gathering %s", named(s).c_str());
if (s == rtc::PeerConnection::GatheringState::Complete) {
{
std::lock_guard<std::mutex> lock(mutex);
@@ -445,8 +461,9 @@ struct StreamSession::Impl {
cv.notify_all();
}
});
+ pc->onIceStateChange([](rtc::PeerConnection::IceState s) { XC_LOGI("webrtc: ICE state %s", named(s).c_str()); });
pc->onStateChange([this](rtc::PeerConnection::State s) {
- XC_LOGI("peer connection state: %d", static_cast<int>(s));
+ XC_LOGI("peer connection state: %d (%s)", static_cast<int>(s), named(s).c_str());
if (s == rtc::PeerConnection::State::Failed) fail("WebRTC connection failed");
if (s == rtc::PeerConnection::State::Disconnected) fail("WebRTC connection lost");
});