Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

build(ps4): optimised by default, WebRTC patches kept in the repo

Rafael Abud Ferreiraa9c46c69cc68
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5c0652f..3132082 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -13,6 +13,12 @@ option(XCLOUD_PS5 "Build for the PS5 (payload SDK)" OFF)
option(XC_TARGET_PS4 "Build for the PS4 (OpenOrbis)" OFF)
include(cmake/platform.cmake)
+# Without a build type clang compiles at -O0, and the PS4's CPU cannot keep up: v1.5.5
+# for PS4 shipped that way and drew 2-7 fps. The PS4 build is optimised by default.
+if(XC_TARGET_PS4 AND NOT CMAKE_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE Release CACHE STRING "Build type" FORCE)
+endif()
+
# --- Portable core: auth, HTTPS, xCloud protocol -----------------------------
# The CA bundle inside the binary too: used when assets/cacert.pem can't be read.
set(XC_BUILTIN_CA "${CMAKE_CURRENT_BINARY_DIR}/generated/builtin_ca.cpp")
diff --git a/cmake/apply_patch.cmake b/cmake/apply_patch.cmake
new file mode 100644
index 0000000..0deb251
--- /dev/null
+++ b/cmake/apply_patch.cmake
@@ -0,0 +1,24 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+# Copyright (C) 2026 RafaelNGP
+# xc_apply_patch(<checkout dir> <patch file>): applies a patch kept in this repo to a
+# submodule checkout, once. Already applied: nothing to do. Neither applied nor
+# applicable (the submodule moved, or holds other edits): configure stops, so a
+# release can never be built without the patch.
+find_package(Git REQUIRED)
+
+function(xc_apply_patch dir patch)
+ execute_process(COMMAND "${GIT_EXECUTABLE}" apply --reverse --check "${patch}"
+ WORKING_DIRECTORY "${dir}" RESULT_VARIABLE applied
+ OUTPUT_QUIET ERROR_QUIET)
+ if(applied EQUAL 0)
+ return()
+ endif()
+ execute_process(COMMAND "${GIT_EXECUTABLE}" apply --whitespace=nowarn "${patch}"
+ WORKING_DIRECTORY "${dir}" RESULT_VARIABLE rc
+ ERROR_VARIABLE err)
+ if(NOT rc EQUAL 0)
+ message(FATAL_ERROR "cannot apply ${patch} to ${dir}:\n${err}\n"
+ "Reset that submodule (git -C ${dir} checkout .) and configure again.")
+ endif()
+ message(STATUS "Applied ${patch}")
+endfunction()
diff --git a/cmake/deps/libdatachannel.cmake b/cmake/deps/libdatachannel.cmake
index 6c8b538..f142256 100644
--- a/cmake/deps/libdatachannel.cmake
+++ b/cmake/deps/libdatachannel.cmake
@@ -14,4 +14,14 @@ set(BUILD_WITH_WARNINGS OFF CACHE BOOL "" FORCE)
list(PREPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/modules")
find_package(MbedTLS REQUIRED)
+# PS4 needs a few edits to libdatachannel and libjuice (ps4/patches/README.md). They
+# are kept in this repo and applied here, so a clean checkout builds the same thing.
+if(XC_TARGET_PS4)
+ include(${CMAKE_SOURCE_DIR}/cmake/apply_patch.cmake)
+ xc_apply_patch(${CMAKE_SOURCE_DIR}/deps/libdatachannel/deps/libjuice
+ ${CMAKE_SOURCE_DIR}/ps4/patches/libjuice.patch)
+ xc_apply_patch(${CMAKE_SOURCE_DIR}/deps/libdatachannel
+ ${CMAKE_SOURCE_DIR}/ps4/patches/libdatachannel.patch)
+endif()
+
add_subdirectory(deps/libdatachannel ${CMAKE_BINARY_DIR}/libdatachannel EXCLUDE_FROM_ALL)
diff --git a/ps4/patches/README.md b/ps4/patches/README.md
new file mode 100644
index 0000000..1333e6f
--- /dev/null
+++ b/ps4/patches/README.md
@@ -0,0 +1,18 @@
+# PS4 patches to the WebRTC submodules
+
+CMake applies these when it configures a PS4 build (`cmake/deps/libdatachannel.cmake`).
+The submodules stay on their upstream commits, and their checkouts show as modified
+afterwards. That is expected.
+
+- `libjuice.patch` (deps/libdatachannel/deps/libjuice):
+ - `timestamp.c`: on PS4, time comes from `sceKernelGetProcessTime`.
+ - `conn_poll.c`: the poll loop gets woken by a UDP socket, as on Windows, because PS4 has no
+ pipe. When the system refuses the loopback bind, it falls back to waking every 50 ms.
+- `libdatachannel.patch` (deps/libdatachannel):
+ - `sctptransport`: sets `sconn_len`, as on FreeBSD, and moves the 64 KB receive buffer off
+ the thread stack, which is small on PS4.
+ - `dtlstransport`: a DTLS send that cannot complete returns instead of spinning.
+ - `init` and `peerconnection`: extra debug log lines.
+
+To change a patch, edit the submodule checkout, then run
+`git -C <submodule> diff > ps4/patches/<name>.patch`.
diff --git a/ps4/patches/libdatachannel.patch b/ps4/patches/libdatachannel.patch
new file mode 100644
index 0000000..47a3444
--- /dev/null
+++ b/ps4/patches/libdatachannel.patch
@@ -0,0 +1,161 @@
+diff --git a/src/impl/dtlstransport.cpp b/src/impl/dtlstransport.cpp
+index 6a289ef..b44dfcf 100644
+--- a/src/impl/dtlstransport.cpp
++++ b/src/impl/dtlstransport.cpp
+@@ -479,7 +479,7 @@ bool DtlsTransport::send(message_ptr message) {
+ PLOG_VERBOSE << "Send size=" << message->size();
+
+ int ret;
+- do {
++ {
+ std::lock_guard lock(mSslMutex);
+ if (message->size() > size_t(mbedtls_ssl_get_max_out_record_payload(&mSsl)))
+ return false;
+@@ -487,7 +487,10 @@ bool DtlsTransport::send(message_ptr message) {
+ mCurrentDscp = message->dscp;
+ ret = mbedtls_ssl_write(&mSsl, reinterpret_cast<const unsigned char *>(message->data()),
+ message->size());
+- } while (!mbedtls::check(ret));
++ }
++
++ if (!mbedtls::check(ret))
++ return false;
+
+ return mOutgoingResult;
+ }
+diff --git a/src/impl/init.cpp b/src/impl/init.cpp
+index aad72dd..f016bc4 100644
+--- a/src/impl/init.cpp
++++ b/src/impl/init.cpp
+@@ -122,6 +122,7 @@ void Init::doInit() {
+ int count = std::max(concurrency, MIN_THREADPOOL_SIZE);
+ PLOG_DEBUG << "Spawning " << count << " threads";
+ ThreadPool::Instance().spawn(count);
++ PLOG_DEBUG << "Spawned threads done";
+
+ #if RTC_ENABLE_WEBSOCKET
+ PollService::Instance().start();
+@@ -135,9 +136,13 @@ void Init::doInit() {
+ openssl::init();
+ #endif
+
++ PLOG_DEBUG << "Calling SctpTransport::Init()";
+ SctpTransport::Init();
++ PLOG_DEBUG << "SctpTransport::Init() returned";
+ SctpTransport::SetSettings(mCurrentSctpSettings);
++ PLOG_DEBUG << "SctpTransport::SetSettings() returned";
+ DtlsTransport::Init();
++ PLOG_DEBUG << "DtlsTransport::Init() returned";
+ #if RTC_ENABLE_WEBSOCKET
+ TlsTransport::Init();
+ #endif
+@@ -145,6 +150,7 @@ void Init::doInit() {
+ DtlsSrtpTransport::Init();
+ #endif
+ IceTransport::Init();
++ PLOG_DEBUG << "Init::doInit() completed";
+ }
+
+ void Init::doCleanup() {
+diff --git a/src/impl/peerconnection.cpp b/src/impl/peerconnection.cpp
+index c9eefca..8ec2294 100644
+--- a/src/impl/peerconnection.cpp
++++ b/src/impl/peerconnection.cpp
+@@ -47,7 +47,7 @@ static LogCounter
+ const string PemBeginCertificateTag = "-----BEGIN CERTIFICATE-----";
+
+ PeerConnection::PeerConnection(Configuration config_) : config(std::move(config_)) {
+- PLOG_VERBOSE << "Creating PeerConnection";
++ PLOG_DEBUG << "Creating PeerConnection (impl)";
+
+ if (config.certificatePemFile && config.keyPemFile) {
+ std::promise<certificate_ptr> cert;
+@@ -58,7 +58,9 @@ PeerConnection::PeerConnection(Configuration config_) : config(std::move(config_
+ config.keyPemPass.value_or(""))));
+ mCertificate = cert.get_future();
+ } else if (!config.certificatePemFile && !config.keyPemFile) {
++ PLOG_DEBUG << "calling make_certificate";
+ mCertificate = make_certificate(config.certificateType);
++ PLOG_DEBUG << "make_certificate returned";
+ } else {
+ throw std::invalid_argument(
+ "Either none or both certificate and key PEM files must be specified");
+@@ -77,6 +79,7 @@ PeerConnection::PeerConnection(Configuration config_) : config(std::move(config_
+ PLOG_VERBOSE << "MTU set to " << *config.mtu;
+ }
+ }
++ PLOG_DEBUG << "Creating PeerConnection (impl) completed";
+ }
+
+ PeerConnection::~PeerConnection() {
+diff --git a/src/impl/sctptransport.cpp b/src/impl/sctptransport.cpp
+index 6afe772..b803f33 100644
+--- a/src/impl/sctptransport.cpp
++++ b/src/impl/sctptransport.cpp
+@@ -339,12 +339,12 @@ void SctpTransport::stop() { close(); }
+
+ struct sockaddr_conn SctpTransport::getSockAddrConn(uint16_t port) {
+ struct sockaddr_conn sconn = {};
++#if defined(HAVE_SCONN_LEN) || defined(__FreeBSD__) || defined(__APPLE__) || defined(__DragonFly__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__ORBIS__)
++ sconn.sconn_len = sizeof(sconn);
++#endif
+ sconn.sconn_family = AF_CONN;
+ sconn.sconn_port = htons(port);
+ sconn.sconn_addr = this;
+-#ifdef HAVE_SCONN_LEN
+- sconn.sconn_len = sizeof(sconn);
+-#endif
+ return sconn;
+ }
+
+@@ -473,15 +473,15 @@ void SctpTransport::doRecv() {
+ std::lock_guard lock(mRecvMutex);
+ --mPendingRecvCount;
+ try {
++ const size_t bufferSize = 65536;
++ auto buffer = std::make_unique<byte[]>(bufferSize);
+ while (state() != State::Disconnected && state() != State::Failed) {
+- const size_t bufferSize = 65536;
+- byte buffer[bufferSize];
+ socklen_t fromlen = 0;
+ struct sctp_rcvinfo info = {};
+ socklen_t infolen = sizeof(info);
+ unsigned int infotype = 0;
+ int flags = 0;
+- ssize_t len = usrsctp_recvv(mSock, buffer, bufferSize, nullptr, &fromlen, &info,
++ ssize_t len = usrsctp_recvv(mSock, buffer.get(), bufferSize, nullptr, &fromlen, &info,
+ &infolen, &infotype, &flags);
+ if (len < 0) {
+ if (errno == EWOULDBLOCK || errno == EAGAIN || errno == ECONNRESET)
+@@ -498,7 +498,7 @@ void SctpTransport::doRecv() {
+ // therefore partial notifications and messages need to be handled separately.
+ if (flags & MSG_NOTIFICATION) {
+ // SCTP event notification
+- mPartialNotification.insert(mPartialNotification.end(), buffer, buffer + len);
++ mPartialNotification.insert(mPartialNotification.end(), buffer.get(), buffer.get() + len);
+
+ if (flags & MSG_EOR) {
+ // Notification is complete, process it
+@@ -510,7 +510,7 @@ void SctpTransport::doRecv() {
+
+ } else {
+ // SCTP message
+- mPartialMessage.insert(mPartialMessage.end(), buffer, buffer + len);
++ mPartialMessage.insert(mPartialMessage.end(), buffer.get(), buffer.get() + len);
+ if (mPartialMessage.size() > mMaxMessageSize) {
+ PLOG_WARNING << "SCTP message is too large, truncating it";
+ mPartialMessage.resize(mMaxMessageSize);
+diff --git a/src/impl/sctptransport.hpp b/src/impl/sctptransport.hpp
+index 4e1a9a0..f4d3363 100644
+--- a/src/impl/sctptransport.hpp
++++ b/src/impl/sctptransport.hpp
+@@ -21,6 +21,9 @@
+ #include <map>
+ #include <mutex>
+
++#if defined(__ORBIS__) && !defined(__FreeBSD__)
++#define __FreeBSD__ 1
++#endif
+ #include "usrsctp.h"
+
+ namespace rtc::impl {
diff --git a/ps4/patches/libjuice.patch b/ps4/patches/libjuice.patch
new file mode 100644
index 0000000..094661e
--- /dev/null
+++ b/ps4/patches/libjuice.patch
@@ -0,0 +1,121 @@
+diff --git a/src/conn_poll.c b/src/conn_poll.c
+index a8462c0..8be0130 100644
+--- a/src/conn_poll.c
++++ b/src/conn_poll.c
+@@ -20,7 +20,7 @@
+
+ typedef struct registry_impl {
+ thread_t thread;
+-#ifdef _WIN32
++#if defined(_WIN32) || defined(__ORBIS__)
+ socket_t interrupt_sock;
+ #else
+ int interrupt_pipe_out;
+@@ -64,9 +64,17 @@ int conn_poll_registry_init(conn_registry_t *registry, udp_socket_config_t *conf
+ return -1;
+ }
+
+-#ifdef _WIN32
++#if defined(_WIN32) || defined(__ORBIS__)
+ udp_socket_config_t interrupt_config;
+ memset(&interrupt_config, 0, sizeof(interrupt_config));
++#ifdef __ORBIS__
++ // PS4: loopback bind may be rejected. The interrupt socket is optional
++ // here because conn_poll_run caps the poll timeout at 50ms.
++ interrupt_config.bind_address = NULL;
++ registry_impl->interrupt_sock = udp_create_socket(&interrupt_config);
++ if (registry_impl->interrupt_sock == INVALID_SOCKET)
++ JLOG_WARN("Interrupt socket unavailable, relying on poll timeout");
++#else
+ interrupt_config.bind_address = "localhost";
+ registry_impl->interrupt_sock = udp_create_socket(&interrupt_config);
+ if (registry_impl->interrupt_sock == INVALID_SOCKET) {
+@@ -74,6 +82,7 @@ int conn_poll_registry_init(conn_registry_t *registry, udp_socket_config_t *conf
+ free(registry_impl);
+ return -1;
+ }
++#endif
+ #else
+ int pipefds[2];
+ if (pipe(pipefds)) {
+@@ -100,7 +109,7 @@ int conn_poll_registry_init(conn_registry_t *registry, udp_socket_config_t *conf
+ return 0;
+
+ error:
+-#ifndef _WIN32
++#if !defined(_WIN32) && !defined(__ORBIS__)
+ close(registry_impl->interrupt_pipe_out);
+ close(registry_impl->interrupt_pipe_in);
+ #endif
+@@ -115,8 +124,9 @@ void conn_poll_registry_cleanup(conn_registry_t *registry) {
+ JLOG_VERBOSE("Waiting for connections thread");
+ thread_join(registry_impl->thread, NULL);
+
+-#ifdef _WIN32
+- closesocket(registry_impl->interrupt_sock);
++#if defined(_WIN32) || defined(__ORBIS__)
++ if (registry_impl->interrupt_sock != INVALID_SOCKET)
++ closesocket(registry_impl->interrupt_sock);
+ #else
+ close(registry_impl->interrupt_pipe_out);
+ close(registry_impl->interrupt_pipe_in);
+@@ -144,12 +154,12 @@ int conn_poll_prepare(conn_registry_t *registry, pfds_record_t *pfds, timestamp_
+ registry_impl_t *registry_impl = registry->impl;
+ struct pollfd *interrupt_pfd = pfds->pfds;
+ assert(interrupt_pfd);
+-#ifdef _WIN32
++#if defined(_WIN32) || defined(__ORBIS__)
+ interrupt_pfd->fd = registry_impl->interrupt_sock;
+ #else
+ interrupt_pfd->fd = registry_impl->interrupt_pipe_in;
+ #endif
+- interrupt_pfd->events = POLLIN;
++ interrupt_pfd->events = interrupt_pfd->fd == INVALID_SOCKET ? 0 : POLLIN;
+
+ for (nfds_t i = 1; i < pfds->size; ++i) {
+ struct pollfd *pfd = pfds->pfds + i;
+@@ -210,7 +220,7 @@ int conn_poll_recv(socket_t sock, char *buffer, size_t size, addr_record_t *src)
+ int conn_poll_process(conn_registry_t *registry, pfds_record_t *pfds) {
+ struct pollfd *interrupt_pfd = pfds->pfds;
+ if (interrupt_pfd->revents & POLLIN) {
+-#ifdef _WIN32
++#if defined(_WIN32) || defined(__ORBIS__)
+ char dummy;
+ addr_record_t src;
+ while (udp_recvfrom(interrupt_pfd->fd, &dummy, 1, &src) >= 0) {
+@@ -295,6 +305,10 @@ int conn_poll_run(conn_registry_t *registry) {
+ timediff_t timediff = next_timestamp - current_timestamp();
+ if (timediff < 0)
+ timediff = 0;
++#if defined(__ORBIS__)
++ if (timediff > 50)
++ timediff = 50;
++#endif
+
+ JLOG_VERBOSE("Entering poll on %d sockets for %d ms", count, (int)timediff);
+ int ret = poll(pfds.pfds, pfds.size, (int)timediff);
+@@ -378,7 +392,9 @@ int conn_poll_interrupt(juice_agent_t *agent) {
+ JLOG_VERBOSE("Interrupting connections thread");
+
+ char dummy = 0;
+-#ifdef _WIN32
++#if defined(_WIN32) || defined(__ORBIS__)
++ if (registry_impl->interrupt_sock == INVALID_SOCKET)
++ return 0; // PS4 fallback: the poll loop wakes every 50ms
+ if (udp_sendto_self(registry_impl->interrupt_sock, &dummy, 0) < 0) {
+ if (sockerrno != SEAGAIN && sockerrno != SEWOULDBLOCK) {
+ JLOG_WARN("Failed to interrupt poll by triggering socket, errno=%d", sockerrno);
+diff --git a/src/timestamp.c b/src/timestamp.c
+index 2a7cc98..c50141a 100644
+--- a/src/timestamp.c
++++ b/src/timestamp.c
+@@ -36,6 +36,9 @@ int clock_gettime(int clk_id, struct timespec *t) {
+ timestamp_t current_timestamp() {
+ #ifdef _WIN32
+ return (timestamp_t)GetTickCount();
++#elif defined(__ORBIS__)
++ extern uint64_t sceKernelGetProcessTime(void);
++ return (timestamp_t)(sceKernelGetProcessTime() / 1000);
+ #else // POSIX
+ struct timespec ts;
+ if (clock_gettime(CLOCK_MONOTONIC, &ts))
diff --git a/tools/ps4/package.sh b/tools/ps4/package.sh
index d744ce4..f8c901a 100755
--- a/tools/ps4/package.sh
+++ b/tools/ps4/package.sh
@@ -82,6 +82,27 @@ FSELF_PAID="${XC_PS4_FSELF_PAID:-0x3800000000000011}"
ELF="$BUILD_DIR/xcloud_ps4.elf"
[ -f "$ELF" ] || { echo "error: $ELF not found (build with cmake/ps4.toolchain.cmake first)" >&2; exit 1; }
+# An unoptimised build runs at a few fps on a PS4 (v1.5.5 for PS4 shipped like that),
+# and a build without ps4/patches has no working WebRTC: refuse to package either.
+# XC_PS4_ALLOW_DEBUG=1 packages a debug build anyway, for local tests only.
+BUILD_TYPE="$(sed -n 's/^CMAKE_BUILD_TYPE:[A-Z]*=//p' "$BUILD_DIR/CMakeCache.txt" 2>/dev/null)"
+case "$BUILD_TYPE" in
+ Release|RelWithDebInfo|MinSizeRel) ;;
+ *)
+ if [ "${XC_PS4_ALLOW_DEBUG:-0}" != 1 ]; then
+ echo "error: $BUILD_DIR is a '${BUILD_TYPE:-no build type}' build (-O0)." >&2
+ echo " Reconfigure with -DCMAKE_BUILD_TYPE=Release, or set XC_PS4_ALLOW_DEBUG=1 for a local test." >&2
+ exit 1
+ fi
+ echo "warning: packaging an unoptimised '${BUILD_TYPE:-no build type}' build" >&2 ;;
+esac
+for _p in "deps/libdatachannel/deps/libjuice:libjuice" "deps/libdatachannel:libdatachannel"; do
+ if ! git -C "$REPO_DIR/${_p%%:*}" apply --reverse --check "$REPO_DIR/ps4/patches/${_p##*:}.patch" 2>/dev/null; then
+ echo "error: ps4/patches/${_p##*:}.patch is not applied to ${_p%%:*} (configure the PS4 build again)" >&2
+ exit 1
+ fi
+done
+
STAGE_DIR="$BUILD_DIR/pkg_stage"
rm -rf -- "$STAGE_DIR" "$OUT_DIR"
mkdir -p "$STAGE_DIR/sce_sys" "$STAGE_DIR/sce_module" "$STAGE_DIR/assets" "$OUT_DIR"