Skip to content

Xbox Cloud Gaming app for PS5 Homebrew

C

fix(ps4): resolve screen tearing (#366), udp packet loss (#368), and usb controller rumble/onefamily conflict (#369)

Rafael Abud Ferreira4dcdadd85d2f
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6ac89fe..cd9934b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 RafaelNGP
cmake_minimum_required(VERSION 3.20)
-project(xcloud_ps5 VERSION 1.6.1 LANGUAGES C CXX)
+project(xcloud_ps5 VERSION 1.6.2 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
diff --git a/notes.md b/notes.md
index 1d4fd78..6e7a930 100644
--- a/notes.md
+++ b/notes.md
@@ -1,70 +1,48 @@
<!-- LANG:EN -->
-# PSBox Cloud Gaming v1.6.1
+# PSBox Cloud Gaming v1.6.2 (Experimental PS4 Release)
-## 🏆 Xbox Achievements to Native PS5 Trophies Conversion
-- **Xbox to PS5 Trophy Synchronization**: Converts unlocked Xbox achievements directly into native PlayStation 5 Trophy 2 packages (`TRPTITLE.DAT` + `TROPHY.UCP` + database registration).
-- **Trophy Conversion Disclaimer Modal**: Explains local profile registration, warns about PSN ban/flag risk, and advises users to enable only on local/offline profiles or if they do not plan to connect to PSN again. Includes explicit "Estou ciente" (I understand) and "Cancelar" (Cancel) confirmation buttons.
-- **Remove Local PSBox Trophies Option**: New action in Settings allowing users to completely remove all trophies and metadata added by PSBox from their local PS5 account at any time, eliminating ban risks. Trophies can be safely re-synced from Xbox anytime.
+## 📺 PS4 Horizontal Screen Tearing Elimination (Issue #366)
+- **Strict V-Sync Flip Presentation**: Changed display presentation flip mode on PS4 from `ORBIS_VIDEO_OUT_FLIP_HSYNC` to `ORBIS_VIDEO_OUT_FLIP_VSYNC`.
+- **Smooth 60 FPS Pacing**: Eliminates horizontal tearing lines during fast camera rotation and lateral movement, synchronizing frame swaps strictly to the 60 Hz vertical blanking interval.
-## 🐧 Linux Desktop Improvements & Input Bug Fixes
-- **Keyboard Typing Isolation**: Fixed keyboard text input triggering gamepad buttons in UI navigation and Search screens.
-- **Delete Key Fix**: Fixed `Delete` key triggering touchpad hold (signout) on desktop.
-- **Eliminated Ghost Phone Icon**: Fixed virtual gamepad detection so inactive WebUI connections do not display a phantom phone controller icon on desktop slot 0.
-- **Low-Latency Presentation & Handheld Detection**: Vulkan NV12 decode pipeline and mailbox presentation for Linux desktop and handheld devices (Steam Deck / ROG Ally / Legion Go).
+## 🌐 PS4 High Bitrate UDP Socket Buffering (Issue #368)
+- **Kernel Socket Buffer Expansion**: UDP sockets now explicitly request a progressive receive buffer up to 2MB (`SO_RCVBUF = 0x1002`) with fallback down to 128KB, and send buffer up to 1MB (`SO_SNDBUF = 0x1001`), replacing the default ~48-64KB OS buffer.
+- **Socket Options Translation & Fallback**: Implemented comprehensive option translation for BSD/Orbis socket levels and constants (`SOL_SOCKET`, `SO_RCVBUF`, `SO_SNDBUF`, `SO_ERROR`, `SO_REUSEADDR`, `SO_RCVTIMEO`, `SO_SNDTIMEO`), with graceful step-down on kernel buffer limits, preventing packet drop during 15+ Mbps burst streams.
-## 🎮 PS4 Native USB Controller Support (OneFamily Integration)
-- **Universal USB Controller Drivers**: Direct in-app support on PS4 (using `libSceUsbd`) for PS3 (DualShock 3), PS4 (wired/third-party), PS5 (DualSense), Xbox 360, Xbox One / Series X|S (GIP), 8BitDo adapters/controllers, Nintendo Switch Pro & Input-Only, Google Stadia, and generic DirectInput/HID gamepads.
-- **Autonomous & Zero-Dependency**: Works out of the box directly in the application without requiring background daemons or external GoldHEN payloads.
+## 🎮 PS4 USB Controller & OneFamily Conflict Fix + Rumble Support (Issue #369)
+- **OneFamily Coexistence Setting**: Added a user toggle (`usbControllers` / `"Controles USB (Driver OneFamily integrado)"`) via WebUI and `settings.json`. Users using GoldHEN's OneFamily plugin can disable in-app USB claiming to prevent double input registration.
+- **Full USB Force-Feedback (Rumble)**: Implemented rumble output packets for XInput, GIP (Xbox One / Series X|S), DualShock 4, DualSense, DualShock 3, and Switch Pro controllers.
+- **Rumble Pipeline Routing**: Refactored pad polling so rumble timers and motor outputs dispatch correctly to USB devices even when native `scePad` ports are unoccupied.
### 📦 Attached Files (English)
| File Name | Description |
|---|---|
-| `PSBoxCloudGaming[PS5]-v1.6.1.zip` | Official standalone ZIP package for PlayStation 5 (manual install or homebrew manager). |
-| `PSBoxCloudGaming[PS5]-v1.6.1.zip.sig` | ECDSA cryptographic digital signature verifying package authenticity on PS5. |
-| `PSBoxCloudGaming[PS5]-v1.6.1.zip.sha256` | SHA256 checksum for the PS5 package. |
-| `PPSA99810.zip` | Canonical PS5 package required by the In-App Updater for consoles updating from previous versions. |
-| `PPSA99810.zip.sig` | Canonical cryptographic signature required by the In-App Updater. |
-| `PPSA99810.zip.sha256` | SHA256 checksum for the canonical PS5 package. |
-| `PSBoxCloudGaming[PS4]-v1.6.1.pkg` | Installable FPKG package for PlayStation 4 (GoldHEN Package Installer). |
-| `PSBoxCloudGaming[PS4]-v1.6.1.pkg.sha256` | SHA256 checksum for the PS4 package. |
-| `PSBoxCloudGaming[Linux]-v1.6.1.AppImage` | Universal portable binary for Linux distributions and Steam Deck (Desktop Mode & Game Mode). |
-| `PSBoxCloudGaming[Linux]-v1.6.1.AppImage.sha256` | SHA256 checksum for the Linux AppImage. |
+| `PSBoxCloudGaming[PS4]-v1.6.2.pkg` | Installable FPKG package for PlayStation 4 (GoldHEN Package Installer). |
+| `PSBoxCloudGaming[PS4]-v1.6.2.pkg.sha256` | SHA256 checksum for the PS4 package. |
---
### 🚀 How to Install (English)
-#### 🎮 PlayStation 5
-- **Automatic In-App Update**: Open the app's *Settings* menu and choose the built-in update option.
-- **Manual Installation**:
- 1. Download `PSBoxCloudGaming[PS5]-v1.6.1.zip` or `PPSA99810.zip`.
- 2. Extract its contents over FTP to `/data/homebrew/PPSA99810/` on your jailbroken PS5.
- 3. Ensure all files and folders have `0777` permissions.
-
#### 🎮 PlayStation 4
-- Download `PSBoxCloudGaming[PS4]-v1.6.1.pkg`, copy it to the root of a USB drive (exFAT/FAT32), and install via *Settings > GoldHEN > Package Installer*.
-
-#### 🐧 Linux Desktop & Steam Deck
-- Download `PSBoxCloudGaming[Linux]-v1.6.1.AppImage`, make it executable (`chmod +x`) and run it. Works directly in Desktop Mode and Steam Game Mode.
+- Download `PSBoxCloudGaming[PS4]-v1.6.2.pkg`, copy it to the root of a USB drive (exFAT/FAT32), and install via *Settings > GoldHEN > Package Installer*.
<!-- LANG:PT -->
-# PSBox Cloud Gaming v1.6.1 (Português)
+# PSBox Cloud Gaming v1.6.2 (Release Experimental PS4)
-## 🏆 Conversão de Conquistas Xbox em Troféus Nativos do PS5
-- **Sincronização de Conquistas para Troféus PS5**: Converte conquistas desbloqueadas do Xbox diretamente em pacotes nativos do sistema Trophy 2 do PlayStation 5 (`TRPTITLE.DAT` + `TROPHY.UCP` + registro no sistema).
-- **Modal de Aviso sobre Troféus**: Explica a modificação no perfil local, alerta sobre o risco de banimento/marcação na PSN e instrui o usuário a ativar a opção apenas em contas locais (offline) ou se não pretende conectar novamente à PSN. Inclui botões explícitos "Estou ciente" e "Cancelar".
-- **Opção de Remoção de Troféus Locais do PSBox**: Nova opção nas Configurações para remover com segurança todos os troféus e registros adicionados pelo PSBox da conta local a qualquer momento, eliminando riscos de banimento. Os troféus podem ser re-sincronizados da conta Xbox quando desejar.
+## 📺 Eliminação de Screen Tearing Horizontal no PS4 (Issue #366)
+- **Apresentação com V-Sync Estrito**: Alterado o modo de flip no PS4 de `ORBIS_VIDEO_OUT_FLIP_HSYNC` para `ORBIS_VIDEO_OUT_FLIP_VSYNC`.
+- **Taxa Suave de 60 FPS**: Elimina linhas de corte/rasgo horizontal durante giros rápidos de câmera e movimentação lateral rápida, sincronizando os quadros estritamente no intervalo de apagamento vertical de 60 Hz.
-## 🐧 Melhorias no Linux Desktop & Correções de Entrada
-- **Isolamento de Digitação no Teclado**: Corrigido problema onde a digitação em telas de busca e interface acionava botões do controle.
-- **Correção da Tecla Delete**: Evita que a tecla `Delete` acione o botão touchpad (desconexão da conta) no desktop.
-- **Eliminação do Ícone Fantasma de Celular**: Corrigida a detecção do controle virtual da WebUI para evitar a exibição indevida de ícone de celular no slot 0 do desktop.
-- **Apresentação de Baixa Latência & Detecção de Handhelds**: Pipeline Vulkan NV12 e modo de apresentação mailbox para desktop Linux e dispositivos portáteis (Steam Deck / ROG Ally / Legion Go).
+## 🌐 Otimização de Buffers UDP contra Perda de Pacotes no PS4 (Issue #368)
+- **Expansão Progressiva de Buffers no Kernel**: Sockets UDP agora alocam de forma progressiva até 2MB de buffer de recepção (`SO_RCVBUF = 0x1002`) com escalonamento gradual até 128KB e buffer de envio de 1MB (`SO_SNDBUF = 0x1001`), superando a limitação do buffer padrão de ~48-64KB do sistema operacional.
+- **Tradução e Fallback de Opções de Socket**: Adicionada camada de tradução completa para níveis e constantes de socket (`SOL_SOCKET`, `SO_RCVBUF`, `SO_SNDBUF`, `SO_ERROR`, `SO_REUSEADDR`, etc.) com redução automática em caso de limite do kernel, evitando estouro de buffer e perda de pacotes em bitrates altos de 15+ Mbps.
-## 🎮 Suporte Nativo a Controles USB no PS4 (Integração OneFamily)
-- **Drivers Universais de Controles USB**: Suporte nativo direto no app para PS4 (via `libSceUsbd`) para controles de PS3 (DualShock 3), PS4 (com fio/paralelos), PS5 (DualSense), Xbox 360, Xbox One / Series X|S (GIP), adaptadores/controles 8BitDo, Nintendo Switch Pro e Input-Only, Google Stadia e gamepads HID/DirectInput genéricos.
-- **Autônomo e Sem Dependências Externas**: Funciona imediatamente dentro do próprio aplicativo sem necessidade de daemons ou payloads externos do GoldHEN em segundo plano.
+## 🎮 Suporte e Ajuste a Controles USB no PS4 & Vibração (Issue #369)
+- **Opção de Coexistência com OneFamily**: Adicionada chave de configuração (`usbControllers` / `"Controles USB (Driver OneFamily integrado)"`) na WebUI e no `settings.json`. Permite desativar o driver USB interno quando o usuário preferir usar o plugin OneFamily do GoldHEN, eliminando a duplicação de comandos.
+- **Vibração Completa em Controles USB**: Implementado envio nativo de pacotes de vibração/rumble para controles XInput, GIP (Xbox One / Series X|S), DualShock 4, DualSense, DualShock 3 e Nintendo Switch Pro.
+- **Roteamento do Pipeline de Vibração**: Ajustado o laço de polling para despachar a vibração para controles USB mesmo quando a porta nativa do `scePad` não estiver aberta.
---
@@ -72,30 +50,12 @@
| Nome do Arquivo | Descrição |
|---|---|
-| `PSBoxCloudGaming[PS5]-v1.6.1.zip` | Pacote ZIP oficial para PlayStation 5 (instalação manual ou via gerenciadores homebrew). |
-| `PSBoxCloudGaming[PS5]-v1.6.1.zip.sig` | Assinatura digital ECDSA para verificação de integridade e autenticidade no PS5. |
-| `PSBoxCloudGaming[PS5]-v1.6.1.zip.sha256` | Checksum SHA256 do pacote de PS5. |
-| `PPSA99810.zip` | Pacote canônico de PS5 obrigatório para o atualizador automático in-app (consoles rodando v1.5.4 ou anterior). |
-| `PPSA99810.zip.sig` | Assinatura canônica obrigatória para validação do in-app updater. |
-| `PPSA99810.zip.sha256` | Checksum SHA256 do pacote canônico de PS5. |
-| `PSBoxCloudGaming[PS4]-v1.6.1.pkg` | Pacote FPKG instalável para PlayStation 4 (compatível com GoldHEN Package Installer). |
-| `PSBoxCloudGaming[PS4]-v1.6.1.pkg.sha256` | Checksum SHA256 do pacote de PS4. |
-| `PSBoxCloudGaming[Linux]-v1.6.1.AppImage` | Pacote executável universal para distribuições Linux e Steam Deck (Desktop Mode e Game Mode). |
-| `PSBoxCloudGaming[Linux]-v1.6.1.AppImage.sha256` | Checksum SHA256 do pacote AppImage Linux. |
+| `PSBoxCloudGaming[PS4]-v1.6.2.pkg` | Pacote FPKG instalável para PlayStation 4 (compatível com GoldHEN Package Installer). |
+| `PSBoxCloudGaming[PS4]-v1.6.2.pkg.sha256` | Checksum SHA256 do pacote de PS4. |
---
### 🚀 Como Instalar (Português)
-#### 🎮 PlayStation 5
-- **Atualização Automática**: Abra as *Configurações* no próprio app e utilize a opção de atualização automática integrada.
-- **Instalação Manual**:
- 1. Baixe `PSBoxCloudGaming[PS5]-v1.6.1.zip` ou `PPSA99810.zip`.
- 2. Extraia o conteúdo para `/data/homebrew/PPSA99810/` no seu PS5 via FTP.
- 3. Garanta permissões `0777` em todas as pastas e arquivos extraídos.
-
#### 🎮 PlayStation 4
-- Baixe `PSBoxCloudGaming[PS4]-v1.6.1.pkg`, copie para a raiz de um pendrive (exFAT/FAT32) e instale via *Configurações > GoldHEN > Instalador de Pacotes*.
-
-#### 🐧 Linux Desktop & Steam Deck
-- Baixe `PSBoxCloudGaming[Linux]-v1.6.1.AppImage`, dê permissão de execução (`chmod +x`) e execute. Compatível com Steam Deck em modo Desktop e Game Mode.
+- Baixe `PSBoxCloudGaming[PS4]-v1.6.2.pkg`, copie para a raiz de um pendrive (exFAT/FAT32) e instale via *Configurações > GoldHEN > Instalador de Pacotes*.
diff --git a/src/app/app_core.cpp b/src/app/app_core.cpp
index 71818c8..11d422a 100644
--- a/src/app/app_core.cpp
+++ b/src/app/app_core.cpp
@@ -106,6 +106,7 @@ void applyControllerSettings() {
input::setTriggerFeel(g_settings.triggerStrength, g_settings.triggerHz, g_settings.triggerResistance, g_settings.triggerPulses);
input::setCircleConfirms(g_settings.circleConfirms);
media::setAudioHapticsLevel(g_settings.audioHaptics);
+ input::setUsbPadsEnabled(g_settings.usbControllers);
if (g_ui) g_ui->setCircleConfirms(g_settings.circleConfirms);
}
@@ -356,6 +357,7 @@ bool coreStartup() {
root.set("audioHaptics", g_settings.audioHaptics);
root.set("queueReadyAlert", g_settings.queueReadyAlert);
root.set("previewFeatures", g_settings.previewFeatures);
+ root.set("usbControllers", g_settings.usbControllers);
root.set("videoDecoder", g_settings.videoDecoder);
root.set("voiceRouting", g_settings.voiceRouting);
root.set("padSpeakerVolume", g_settings.padSpeakerVolume);
@@ -430,6 +432,14 @@ bool coreStartup() {
g_settings.previewFeatures = root["previewFeatures"].asBool(g_settings.previewFeatures);
changed = true;
}
+ if (root.has("usbControllers") || root.has("usb_controllers") || root.has("enable_onefamily")) {
+ bool val = root.has("usbControllers") ? root["usbControllers"].asBool(g_settings.usbControllers)
+ : root.has("usb_controllers") ? root["usb_controllers"].asBool(g_settings.usbControllers)
+ : root["enable_onefamily"].asBool(g_settings.usbControllers);
+ g_settings.usbControllers = val;
+ input::setUsbPadsEnabled(val);
+ changed = true;
+ }
if (root.has("videoDecoder")) {
g_settings.videoDecoder = static_cast<int>(std::clamp<int64_t>(root["videoDecoder"].asInt(g_settings.videoDecoder), 0, 1));
changed = true;
diff --git a/src/app/settings.cpp b/src/app/settings.cpp
index 3d9ffbd..936bf6c 100644
--- a/src/app/settings.cpp
+++ b/src/app/settings.cpp
@@ -135,6 +135,7 @@ bool Settings::load(const std::string& path) {
queueReadyAlert = (*j)["queueReadyAlert"].asBool(queueReadyAlert);
previewFeatures = (*j)["previewFeatures"].asBool(previewFeatures);
syncTrophies = (*j)["syncTrophies"].asBool(syncTrophies);
+ usbControllers = (*j)["usbControllers"].asBool((*j)["usb_controllers"].asBool((*j)["enable_onefamily"].asBool(usbControllers)));
titlePlaytime.clear();
for (const auto& [id, sec] : (*j)["titlePlaytime"].members())
if (sec.asInt() > 0) titlePlaytime[id] = static_cast<uint64_t>(sec.asInt());
@@ -279,6 +280,7 @@ bool Settings::save(const std::string& path) const {
v.set("queueReadyAlert", queueReadyAlert);
v.set("previewFeatures", previewFeatures);
v.set("syncTrophies", syncTrophies);
+ v.set("usbControllers", usbControllers);
json::Value pt = json::Value::object();
for (const auto& [id, sec] : titlePlaytime)
if (sec > 0) pt.set(id, static_cast<int64_t>(sec));
diff --git a/src/app/settings.h b/src/app/settings.h
index 575e4dc..c96d1cc 100644
--- a/src/app/settings.h
+++ b/src/app/settings.h
@@ -122,6 +122,7 @@ struct Settings {
bool queueReadyAlert = true; // Queue-ready chime and rumble alert
bool previewFeatures = true; // xCloud preview client identification & ad-supported F2P streaming
bool syncTrophies = false; // Xbox achievement to PlayStation trophy conversion
+ bool usbControllers = true; // in-app USB controllers driver (OneFamily)
std::map<std::string, uint64_t> titlePlaytime; // accumulated playtime in seconds (productId or titleId -> seconds)
uint64_t playtimeForGame(const std::string& productId, const std::string& titleId) const {
diff --git a/src/app/web_server_html.cpp b/src/app/web_server_html.cpp
index 3744f2e..cfb074e 100644
--- a/src/app/web_server_html.cpp
+++ b/src/app/web_server_html.cpp
@@ -744,6 +744,14 @@ input:checked + .slider-sw:before { transform: translateX(20px); }
</label>
</div>
+ <div class="toggle-row">
+ <span class="toggle-label">Controles USB (Driver OneFamily integrado)</span>
+ <label class="switch">
+ <input type="checkbox" id="checkUsbControllers" onchange="markSettingsChanged()">
+ <span class="slider-sw"></span>
+ </label>
+ </div>
+
<div class="map-item" style="margin-top: 10px;">
<label>Decodificador de Vídeo</label>
<select id="selectVideoDecoder" onchange="markSettingsChanged()">
@@ -1635,6 +1643,7 @@ function saveGeneralSettings() {
lightBarMode: parseInt(document.getElementById('selectLightBarMode').value, 10),
lightBarColour: document.getElementById('inputLightBarColor').value,
queueReadyAlert: document.getElementById('checkQueueAlert').checked,
+ usbControllers: document.getElementById('checkUsbControllers') ? document.getElementById('checkUsbControllers').checked : true,
videoDecoder: parseInt(document.getElementById('selectVideoDecoder').value, 10),
voiceRouting: parseInt(document.getElementById('selectVoiceRouting').value, 10)
};
@@ -2002,6 +2011,10 @@ function applyLoadedSettings(s) {
const el = document.getElementById('checkQueueAlert');
if (el) el.checked = !!s.queueReadyAlert;
}
+ if (s.usbControllers !== undefined) {
+ const el = document.getElementById('checkUsbControllers');
+ if (el) el.checked = !!s.usbControllers;
+ }
if (s.videoDecoder !== undefined) {
const el = document.getElementById('selectVideoDecoder');
if (el) el.value = s.videoDecoder;
diff --git a/src/display/display_ps4.cpp b/src/display/display_ps4.cpp
index b77e873..1d457e3 100644
--- a/src/display/display_ps4.cpp
+++ b/src/display/display_ps4.cpp
@@ -658,7 +658,7 @@ void present() {
int64_t marker = ++g_flipMarker;
uint64_t subProcUs = sceKernelGetProcessTime();
uint64_t subUs = platform::nowUs();
- const int flipMode = g_videoFlip ? ORBIS_VIDEO_OUT_FLIP_HSYNC : ORBIS_VIDEO_OUT_FLIP_VSYNC;
+ const int flipMode = ORBIS_VIDEO_OUT_FLIP_VSYNC;
int rc = sceVideoOutSubmitFlip(g_videoHandle, g_currentBuffer, flipMode, marker);
if (rc != 0) {
XC_LOGW("display: submit flip: 0x%08x", static_cast<unsigned>(rc));
diff --git a/src/input/controller_common.cpp b/src/input/controller_common.cpp
index 0df6188..e182597 100644
--- a/src/input/controller_common.cpp
+++ b/src/input/controller_common.cpp
@@ -10,6 +10,7 @@
#include "input/controller.h"
#include "input/controller_backend.h"
#include "input/gyro.h"
+#include "input/pad_usb.h"
#include "input/tuning.h"
#include "platform/platform.h"
#include "util/log.h"
@@ -132,8 +133,13 @@ void applyTriggerMotors(int index, Pad& pad) {
void applyRumble(int index, Pad& pad) {
uint32_t v;
- if (pad.motors.due(v))
- backend::setMotors(index, static_cast<uint8_t>(v >> 8), static_cast<uint8_t>(v), v ? pad.motors.remainingMs() : 0);
+ if (pad.motors.due(v)) {
+ uint8_t large = static_cast<uint8_t>(v >> 8);
+ uint8_t small = static_cast<uint8_t>(v);
+ if (backend::padOpen(index))
+ backend::setMotors(index, large, small, v ? pad.motors.remainingMs() : 0);
+ setUsbPadRumble(index, large, small);
+ }
TriggerStyle style = backend::triggerStyle(index);
if (style == TriggerStyle::Motors) return applyTriggerMotors(index, pad);
if (style != TriggerStyle::Adaptive) return;
@@ -264,9 +270,10 @@ void applyPadSettings(ControllerState& s) {
bool pollPad(int index, ControllerState& out) {
out = {};
- if (index < 0 || index >= kMaxPads || !backend::padOpen(index)) return false;
+ if (index < 0 || index >= kMaxPads) return false;
Pad& slot = g_pads[index];
applyRumble(index, slot);
+ if (!backend::padOpen(index)) return false;
applyLightBar(index, slot);
RawPad pad;
slot.connected = backend::readPad(index, pad);
diff --git a/src/input/controller_ps4.cpp b/src/input/controller_ps4.cpp
index c35c7f2..3b8e81f 100644
--- a/src/input/controller_ps4.cpp
+++ b/src/input/controller_ps4.cpp
@@ -322,7 +322,7 @@ void shutdown() {
bool poll(ControllerState& out) {
if (pollPad(0, out)) return true;
for (int i = 1; i < 4; ++i) {
- if (g_slots[i].handle >= 0 && pollPad(i, out)) return true;
+ if (pollPad(i, out)) return true;
}
return false;
}
diff --git a/src/input/pad_usb.cpp b/src/input/pad_usb.cpp
index 3d61548..152a5c4 100644
--- a/src/input/pad_usb.cpp
+++ b/src/input/pad_usb.cpp
@@ -12,14 +12,18 @@
#include <algorithm>
#include <array>
+#include <atomic>
#include <mutex>
namespace xc::input {
namespace {
+std::atomic<bool> g_usbPadsEnabled{true};
+
int16_t le16(const uint8_t* p) { return static_cast<int16_t>(p[0] | (p[1] << 8)); }
+
float stick(int16_t v) { return std::clamp(static_cast<float>(v) / 32767.0f, -1.0f, 1.0f); }
// XInput and GIP sticks have +y up; ControllerState has +y down.
@@ -90,6 +94,7 @@ void movePlayer(Slot& s, int slot, int player) {
// let go too); otherwise those playing as it, but `except`.
bool pollWhere(int player, int except, ControllerState& out) {
out = ControllerState{};
+ if (!g_usbPadsEnabled.load(std::memory_order_relaxed)) return false;
bool any = false;
std::lock_guard<std::mutex> lock(g_mutex);
assignPlayers();
@@ -716,4 +721,48 @@ uint64_t usbPadActiveAt(int player) {
return at;
}
+void setUsbPadsEnabled(bool enabled) {
+ bool was = g_usbPadsEnabled.exchange(enabled);
+ if (was && !enabled) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ for (int s = 0; s < kMaxUsbPads; ++s) {
+ Slot& slot = g_slots[s];
+ if (slot.attached) {
+ if (slot.player >= 0) {
+ g_events.push_back({UsbPadEvent::Kind::Disconnected, slot.player, slot.name, s});
+ }
+ slot = Slot{};
+ }
+ }
+ usbPadsStop();
+ } else if (!was && enabled) {
+ usbPadsStart();
+ }
+}
+
+bool usbPadsEnabled() {
+ return g_usbPadsEnabled.load(std::memory_order_relaxed);
+}
+
+void setUsbPadRumble(int player, uint8_t large, uint8_t small) {
+ if (player < 0 || player >= kMaxPads) return;
+ int slot = -1;
+ {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ for (int s = 0; s < kMaxUsbPads; ++s) {
+ if (g_slots[s].attached && g_slots[s].player == player) {
+ slot = s;
+ break;
+ }
+ }
+ }
+ if (slot >= 0) {
+ setUsbPadSlotRumble(slot, large, small);
+ }
+}
+
+void __attribute__((weak)) usbPadsStart() {}
+void __attribute__((weak)) usbPadsStop() {}
+void __attribute__((weak)) setUsbPadSlotRumble(int /*slot*/, uint8_t /*large*/, uint8_t /*small*/) {}
+
} // namespace xc::input
diff --git a/src/input/pad_usb.h b/src/input/pad_usb.h
index 1a3f35a..22659d8 100644
--- a/src/input/pad_usb.h
+++ b/src/input/pad_usb.h
@@ -111,9 +111,14 @@ void usbPadsWaitRelease();
std::string usbPadNameFor(int player);
uint64_t usbPadActiveAt(int player);
-// PS5: starts and stops looking for USB pads (pad_usb_ps5.cpp; called by
-// controller_ps5.cpp). Not defined on the other platforms.
+void setUsbPadsEnabled(bool enabled);
+bool usbPadsEnabled();
+void setUsbPadRumble(int player, uint8_t large, uint8_t small);
+void setUsbPadSlotRumble(int slot, uint8_t large, uint8_t small);
+
+// PS4 & PS5: starts and stops looking for USB pads. Not defined on the other platforms.
void usbPadsStart();
void usbPadsStop();
} // namespace xc::input
+
diff --git a/src/input/pad_usb_ps4.cpp b/src/input/pad_usb_ps4.cpp
index 8dea54d..195316d 100644
--- a/src/input/pad_usb_ps4.cpp
+++ b/src/input/pad_usb_ps4.cpp
@@ -5,6 +5,7 @@
// Ported and adapted from OneFamily (ChiricoG/OneFamily, MIT) and OmniPad CE.
#include "input/pad_usb.h"
#include "input/pad_usb_hid.h"
+#include "platform/platform.h"
#include "util/log.h"
#include <stdint.h>
@@ -367,10 +368,12 @@ bool identifyController(libusb_device* dev, const struct libusb_device_descripto
if (vid == XBOX_VID) {
if (pid == XBOX360_PID) {
out.protocol = UsbPadProtocol::XInput;
- out.interfaceNum = 0;
- out.epIn = 0x81;
- out.epOut = 0x01;
out.name = "Xbox 360 Controller";
+ if (!detectXboxByDescriptor(dev, out)) {
+ out.interfaceNum = 0;
+ out.epIn = 0x81;
+ out.epOut = 0x02;
+ }
return true;
}
if (isXboxOnePid(pid)) {
@@ -463,6 +466,8 @@ struct Device {
bool hidConfigured = false;
GenericHidContext hidCtx{};
int disconnectErrors = 0;
+ std::atomic<uint32_t> pendingRumble{0};
+ std::atomic<bool> hasPendingRumble{false};
std::atomic<bool> stop{false};
std::atomic<bool> dead{false};
std::atomic<bool> attached{false};
@@ -593,19 +598,104 @@ void sendInitHandshake(Device& d) {
}
}
+void sendDeviceRumble(Device& d, uint8_t large, uint8_t small) {
+ if (!d.handle) return;
+ if (d.protocol == UsbPadProtocol::XInput) {
+ if (d.epOut && p_sceUsbdInterruptTransfer) {
+ uint8_t pkt[8] = {0x00, 0x08, 0x00, large, small, 0x00, 0x00, 0x00};
+ int transferred = 0;
+ p_sceUsbdInterruptTransfer(d.handle, d.epOut, pkt, sizeof(pkt), &transferred, 50);
+ }
+ } else if (d.protocol == UsbPadProtocol::Gip) {
+ if (d.epOut && p_sceUsbdInterruptTransfer) {
+ static uint8_t s_rumbleSeq = 1;
+ uint8_t pkt[13] = {
+ 0x09, 0x00, s_rumbleSeq++, 0x09, 0x00,
+ 0x0F,
+ 0x00, 0x00,
+ large, small,
+ 0xFF, 0x00, 0xFF
+ };
+ int transferred = 0;
+ p_sceUsbdInterruptTransfer(d.handle, d.epOut, pkt, sizeof(pkt), &transferred, 50);
+ }
+ } else if (d.protocol == UsbPadProtocol::DualShock4) {
+ if (d.epOut && p_sceUsbdInterruptTransfer) {
+ uint8_t pkt[32] = {};
+ pkt[0] = 0x05;
+ pkt[1] = 0xFF;
+ pkt[2] = 0x04;
+ pkt[4] = small;
+ pkt[5] = large;
+ int transferred = 0;
+ p_sceUsbdInterruptTransfer(d.handle, d.epOut, pkt, sizeof(pkt), &transferred, 50);
+ }
+ } else if (d.protocol == UsbPadProtocol::DualSense) {
+ if (d.epOut && p_sceUsbdInterruptTransfer) {
+ uint8_t pkt[48] = {};
+ pkt[0] = 0x02;
+ pkt[1] = 0x03;
+ pkt[2] = 0x14;
+ pkt[3] = small;
+ pkt[4] = large;
+ int transferred = 0;
+ p_sceUsbdInterruptTransfer(d.handle, d.epOut, pkt, sizeof(pkt), &transferred, 50);
+ }
+ } else if (d.protocol == UsbPadProtocol::DualShock3) {
+ if (p_sceUsbdControlTransfer) {
+ uint8_t pkt[49] = {};
+ pkt[0] = 0x01;
+ pkt[1] = 0x00;
+ pkt[2] = small ? 0x01 : 0x00;
+ pkt[3] = 0x00;
+ pkt[4] = large;
+ p_sceUsbdControlTransfer(d.handle, 0x21, 0x09, 0x0201, d.interfaceNum, pkt, sizeof(pkt), 50);
+ }
+ } else if (d.protocol == UsbPadProtocol::SwitchPro) {
+ if (d.epOut && p_sceUsbdInterruptTransfer) {
+ static uint8_t s_proSeq = 0;
+ uint8_t pkt[49] = {};
+ pkt[0] = 0x10;
+ pkt[1] = (s_proSeq++) & 0x0F;
+ if (large > 0 || small > 0) {
+ pkt[2] = 0x28; pkt[3] = 0x88; pkt[4] = 0x60; pkt[5] = 0x61;
+ pkt[6] = 0x28; pkt[7] = 0x88; pkt[8] = 0x60; pkt[9] = 0x61;
+ } else {
+ pkt[2] = 0x00; pkt[3] = 0x01; pkt[4] = 0x40; pkt[5] = 0x40;
+ pkt[6] = 0x00; pkt[7] = 0x01; pkt[8] = 0x40; pkt[9] = 0x40;
+ }
+ int transferred = 0;
+ p_sceUsbdInterruptTransfer(d.handle, d.epOut, pkt, sizeof(pkt), &transferred, 50);
+ }
+ }
+}
+
void readLoop(Device* d) {
+ std::string tname = "ps4_usb_" + std::to_string(d->slot);
+ platform::setThreadAffinity(platform::ThreadRole::Worker, tname.c_str());
XC_LOGI("usb pad %d: read thread started for %s (%04x:%04x, %s)", d->slot, d->name.c_str(), d->vid, d->pid,
usbPadProtocolName(d->protocol));
usbPadAttached(d->slot, d->name);
d->attached = true;
sendInitHandshake(*d);
+ auto checkRumble = [&]() {
+ if (d->hasPendingRumble.exchange(false, std::memory_order_acq_rel)) {
+ uint32_t val = d->pendingRumble.load(std::memory_order_relaxed);
+ uint8_t large = static_cast<uint8_t>(val >> 8);
+ uint8_t small = static_cast<uint8_t>(val & 0xFF);
+ sendDeviceRumble(*d, large, small);
+ }
+ };
+
ControllerState state;
uint8_t buf[256];
int errors = 0;
while (!d->stop) {
+ checkRumble();
int transferred = 0;
int rc = p_sceUsbdInterruptTransfer(d->handle, d->epIn, buf, sizeof(buf), &transferred, 20);
+ checkRumble();
bool isTimeout = (rc == -7 || rc == static_cast<int>(0x80240007));
if (rc != 0 || transferred <= 0) {
if (rc != 0 && !isTimeout) {
@@ -644,6 +734,7 @@ void readLoop(Device* d) {
}
}
+ sendDeviceRumble(*d, 0, 0);
d->dead = true;
XC_LOGI("usb pad %d: read thread finished", d->slot);
}
@@ -668,6 +759,11 @@ void closeDevice(Device& d) {
void scan() {
std::lock_guard<std::mutex> lock(g_mutex);
+ if (!usbPadsEnabled()) {
+ for (auto& d : g_devices) closeDevice(*d);
+ g_devices.clear();
+ return;
+ }
// 1. Remove disconnected / dead devices
for (auto it = g_devices.begin(); it != g_devices.end();) {
@@ -776,6 +872,7 @@ void scan() {
}
void scanLoop() {
+ platform::setThreadAffinity(platform::ThreadRole::Worker, "ps4_usb_scan");
XC_LOGI("usb pad: starting PS4 USB scan loop");
while (g_running) {
scan();
@@ -791,7 +888,23 @@ void scanLoop() {
} // namespace
+void setUsbPadSlotRumble(int slot, uint8_t large, uint8_t small) {
+ std::lock_guard<std::mutex> lock(g_mutex);
+ for (auto& d : g_devices) {
+ if (d->slot == slot) {
+ uint32_t val = (static_cast<uint32_t>(large) << 8) | small;
+ d->pendingRumble.store(val, std::memory_order_relaxed);
+ d->hasPendingRumble.store(true, std::memory_order_release);
+ break;
+ }
+ }
+}
+
void usbPadsStart() {
+ if (!usbPadsEnabled()) {
+ XC_LOGI("usb pad: USB controllers driver disabled in settings");
+ return;
+ }
if (g_running.exchange(true)) return;
if (!loadUsbd()) {
g_running = false;
diff --git a/src/platform/ps4/platform_ps4.cpp b/src/platform/ps4/platform_ps4.cpp
index 47e9fdf..2bae1a2 100644
--- a/src/platform/ps4/platform_ps4.cpp
+++ b/src/platform/ps4/platform_ps4.cpp
@@ -372,6 +372,20 @@ int socket(int domain, int type, int protocol) {
if ((type & SOCK_NONBLOCK) || (type & 04000) || (type & 0x800) || (type & 0x4000) || (type & 0x20000000)) {
setSocketNonBlock(s, 1);
}
+ if (baseType == SOCK_DGRAM) {
+ const int rcvCandidates[] = { 2097152, 1048576, 524288, 262144, 131072 };
+ for (int sz : rcvCandidates) {
+ if (sceNetSetsockopt(s, 0xffff /*SOL_SOCKET*/, 0x1002 /*SO_RCVBUF*/, &sz, sizeof(sz)) >= 0) {
+ break;
+ }
+ }
+ const int sndCandidates[] = { 1048576, 524288, 262144, 131072 };
+ for (int sz : sndCandidates) {
+ if (sceNetSetsockopt(s, 0xffff /*SOL_SOCKET*/, 0x1001 /*SO_SNDBUF*/, &sz, sizeof(sz)) >= 0) {
+ break;
+ }
+ }
+ }
return s;
}
@@ -585,8 +599,43 @@ int accept(int fd, struct sockaddr* addr, socklen_t* addrlen) {
return ret;
}
+static inline void translateSockOpt(int& level, int& optname) {
+ if (level == 1) { // Linux SOL_SOCKET
+ level = 0xffff; // FreeBSD / Orbis SOL_SOCKET
+ switch (optname) {
+ case 1: optname = 0x0001; break; // SO_DEBUG
+ case 2: optname = 0x0004; break; // SO_REUSEADDR
+ case 3: optname = 0x1008; break; // SO_TYPE
+ case 4: optname = 0x1007; break; // SO_ERROR
+ case 5: optname = 0x0010; break; // SO_DONTROUTE
+ case 6: optname = 0x0020; break; // SO_BROADCAST
+ case 7: optname = 0x1001; break; // SO_SNDBUF
+ case 8: optname = 0x1002; break; // SO_RCVBUF
+ case 9: optname = 0x0008; break; // SO_KEEPALIVE
+ case 10: optname = 0x0100; break; // SO_OOBINLINE
+ case 13: optname = 0x0080; break; // SO_LINGER
+ case 15: optname = 0x0200; break; // SO_REUSEPORT
+ case 18: optname = 0x1004; break; // SO_RCVLOWAT
+ case 19: optname = 0x1003; break; // SO_SNDLOWAT
+ case 20: optname = 0x1006; break; // SO_RCVTIMEO
+ case 21: optname = 0x1005; break; // SO_SNDTIMEO
+ default: break;
+ }
+ }
+}
+
int setsockopt(int fd, int level, int optname, const void* optval, socklen_t optlen) {
+ translateSockOpt(level, optname);
int ret = sceNetSetsockopt(fd, level, optname, optval, optlen);
+ if (ret < 0 && level == 0xffff && (optname == 0x1002 || optname == 0x1001) && optval && optlen == sizeof(int)) {
+ int req = *reinterpret_cast<const int*>(optval);
+ int step = req / 2;
+ while (step >= 65536) {
+ ret = sceNetSetsockopt(fd, level, optname, &step, sizeof(step));
+ if (ret >= 0) break;
+ step /= 2;
+ }
+ }
if (ret < 0) {
errno = getNetErrno(ret);
return -1;
@@ -595,6 +644,7 @@ int setsockopt(int fd, int level, int optname, const void* optval, socklen_t opt
}
int getsockopt(int fd, int level, int optname, void* optval, socklen_t* optlen) {
+ translateSockOpt(level, optname);
unsigned int olen = optlen ? static_cast<unsigned int>(*optlen) : 0;
int ret = sceNetGetsockopt(fd, level, optname, optval, optlen ? &olen : nullptr);
if (ret < 0) {
diff --git a/tests/test_main.cpp b/tests/test_main.cpp
index aa13a26..8368c03 100644
--- a/tests/test_main.cpp
+++ b/tests/test_main.cpp
@@ -4697,6 +4697,18 @@ static void testUsbPadSlots() {
input::usbPadState(2, bitdo); // a slot that was never attached
CHECK(!input::pollUsbPad(out) && input::usbPadPlayer(2) == -1);
input::usbPadState(9, bitdo); // out of range: ignored
+
+ // USB Pads Enabled toggle and rumble
+ CHECK(input::usbPadsEnabled());
+ input::usbPadAttached(0, "Test Pad");
+ input::setUsbPadRumble(0, 128, 64);
+ input::setUsbPadRumble(5, 128, 64); // out of bounds
+ input::setUsbPadsEnabled(false);
+ CHECK(!input::usbPadsEnabled());
+ CHECK(input::usbPadCount() == 0);
+ input::setUsbPadsEnabled(true);
+ CHECK(input::usbPadsEnabled());
+ input::takeUsbPadEvents();
}
static void testDesktopMouseNav() {