Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ SRCS = \
src/vpad.c \
src/controllers/switch_pro.c \
src/controllers/xbox360.c \
src/controllers/ds4.c \
src/transport/usb.c

OBJS = $(SRCS:.c=.o)
Expand Down
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Use non-PlayStation controllers on a jailbroken PS5. AnyController is an ELF pay
| Nintendo Switch Pro Controller (`057e:2009`) | USB cable | Working |
| Xbox 360 / XInput controllers (`045e:028e`) | USB cable or 2.4GHz dongle | Working |
| GameSir T4 Pro | 2.4GHz dongle (X-input mode) | Working |
| Sony DualShock 4 (`054c:05c4`, `054c:09cc`) | USB cable | Driver added, untested on hardware |

Many third-party pads and dongles have an X-input mode that reports as an Xbox 360 controller, so they should work too.

Expand Down Expand Up @@ -66,6 +67,10 @@ Buttons are mapped **by position**, so the bottom face button is always Cross:
| Touchpad click | Capture | — |
| PS button | Home | Guide |

DualShock 4 maps one to one, since its face buttons are already in PlayStation
positions: Share becomes **Create**, Options stays **Options**, and the
touchpad click is reported as the touchpad button.

## Building

Requires the PS5 payload SDK from **[ps5-payload-dev/sdk](https://github.com/ps5-payload-dev/sdk)**, v0.45 or newer. Its README covers installation (clang-18 and lld-18 on Linux or WSL).
Expand Down Expand Up @@ -101,6 +106,7 @@ The [Release workflow](.github/workflows/release.yml) builds the payload and pub
- **USB access:** the PS5 has no `uhid` device. Controllers appear only as FreeBSD `ugen` nodes (`/dev/usb/B.A.E`). AnyController identifies devices by their USB descriptor, detaches Sony's HID driver, claims the interface and reads reports from the interrupt endpoints. See [`src/transport/usb.c`](src/transport/usb.c).
- **Switch Pro Controller:** over USB it drops off the bus every second or so until the host sends the USB handshake and the "no timeout" command. The driver sends the same sequence as Linux's `hid-nintendo`, then enables full 0x30 reports and the motion sensor. See [`src/controllers/switch_pro.c`](src/controllers/switch_pro.c).
- **Xbox 360 / XInput:** standard 20-byte input reports. The driver sends the player-LED command on connect, which also makes multi-mode dongles stay in X-input mode instead of cycling. See [`src/controllers/xbox360.c`](src/controllers/xbox360.c).
- **DualShock 4:** over USB the pad streams 64-byte input report `0x01` at ~250 Hz with no handshake needed, so the driver only unpacks the d-pad hat — sticks and triggers already arrive in PlayStation convention. See [`src/controllers/ds4.c`](src/controllers/ds4.c).
- **Brief drops:** if a controller drops off USB, its virtual DualSense is kept for 3 seconds. A quick reconnect then resumes on the same pad, without a disconnect or user re-pick.

### Adding a controller
Expand All @@ -122,7 +128,7 @@ AnyController logs to the kernel log. With a klog server running on the console
- Bluetooth controllers
- Rumble from games, and the light bar
- Motion controls (gyro)
- Other controller families (Xbox One/Series, DualShock 4, generic HID gamepads)
- Other controller families (Xbox One/Series, generic HID gamepads)
- The Create button bit is unverified

## Credits
Expand Down
58 changes: 58 additions & 0 deletions include/controllers/ds4.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Sony DualShock 4 driver.
*
* Over USB the pad streams 64-byte input report 0x01 at ~250 Hz and needs no
* handshake, so this driver is pure translation: sticks and triggers already
* arrive in PlayStation convention and only the d-pad hat has to be unpacked.
* Bluetooth uses report 0x11, which this driver does not handle.
*
* Report 0x01 layout:
* 0 report id, 0x01
* 1..4 left X, left Y, right X, right Y (0..255, centre 128, Y down)
* 5 [7:4] triangle, circle, cross, square [3:0] d-pad hat
* 6 [7] R3 [6] L3 [5] options [4] share [3] R2 [2] L2 [1] R1 [0] L1
* 7 [1] touchpad click [0] PS
* 8..9 L2, R2 analog
*/

#ifndef DS4_H
#define DS4_H

#include "../controller.h"

#define SONY_VID 0x054C
#define DS4_PID_V1 0x05C4 /* CUH-ZCT1x, 2013 */
#define DS4_PID_V2 0x09CC /* CUH-ZCT2x, 2016 */

#define DS4_REPORT_INPUT_USB 0x01
#define DS4_INPUT_LEN 64

/* Buttons, byte 5 (upper nibble; lower nibble is the d-pad hat) */
#define DS4_SQUARE 0x10
#define DS4_CROSS 0x20
#define DS4_CIRCLE 0x40
#define DS4_TRIANGLE 0x80

/* Buttons, byte 6 */
#define DS4_L1 0x01
#define DS4_R1 0x02
#define DS4_L2 0x04
#define DS4_R2 0x08
#define DS4_SHARE 0x10
#define DS4_OPTIONS 0x20
#define DS4_L3 0x40
#define DS4_R3 0x80

/* Buttons, byte 7 */
#define DS4_PS 0x01
#define DS4_TOUCHPAD 0x02

/* Hat: 0 up, 2 right, 4 down, 6 left, odd values are diagonals, >= 8 is
* released. */
#define DS4_DPAD_MASK 0x0F
#define DS4_DPAD_RELEASED 8

/* V1 and V2 speak the same protocol; only the USB id differs. */
const ControllerDriver *ds4_get_driver(int variant); /* 0 = V1, 1 = V2 */

#endif /* DS4_H */
12 changes: 11 additions & 1 deletion include/vpad.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@
/* User id FGG-XSense registers pads under; verified on hardware. */
#define VPAD_DEFAULT_USER 1

/* Handles of the pads we register are recorded here, so that a payload killed
* without cleaning up leaves nothing behind for the next run to trip over. */
#define VPAD_LEDGER_FILE "/data/anycontroller.vpads"

/* Request taken by HID_ADD_DEVICE and HID_INSERT_DATA */
typedef struct {
uint32_t cmd; /* HID_CMD_ADD, or the device handle for insert */
Expand Down Expand Up @@ -92,9 +96,15 @@ Vpad *vpad_create(uint32_t user_id);
/* Translate and submit one frame of input. Returns 0 on success. */
int vpad_submit_input(Vpad *vpad, const NormalizedInput *input);

/* Remove a virtual pad. A pad left registered outlives the payload. */
/* Remove a virtual pad. A pad left registered by a payload that was killed
* (SIGKILL, crash) is removed by the next instance; see vpad_reap_stale. */
void vpad_destroy(Vpad *vpad);

/* Remove the pads a previous instance recorded in the ledger and clear the
* ledger. Call once after vpad_init(), before creating any pad: handles are
* not enumerable, so this is the only way back to a clean state. */
void vpad_reap_stale(void);

/* Remove all pads and close /dev/hid. */
void vpad_shutdown(void);

Expand Down
3 changes: 3 additions & 0 deletions src/controller.c
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
#include "../include/controller.h"
#include "../include/controllers/switch_pro.h"
#include "../include/controllers/xbox360.h"
#include "../include/controllers/ds4.h"

#include <stddef.h>

Expand Down Expand Up @@ -45,4 +46,6 @@ void controller_drivers_init(void)
driver_count = 0;
controller_driver_register(switch_pro_get_driver());
controller_driver_register(xbox360_get_driver());
controller_driver_register(ds4_get_driver(0));
controller_driver_register(ds4_get_driver(1));
}
102 changes: 102 additions & 0 deletions src/controllers/ds4.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* DualShock 4 driver — maps USB input report 0x01 to NormalizedInput.
*/

#include "../../include/controllers/ds4.h"

#include <string.h>

/* The d-pad is a hat switch; the virtual pad wants individual directions, so
* diagonals set two of them. */
static void map_dpad(uint8_t hat, NormalizedInput *out)
{
if (hat >= DS4_DPAD_RELEASED) return;

out->dpad_up = (hat == 0 || hat == 1 || hat == 7);
out->dpad_right = (hat == 1 || hat == 2 || hat == 3);
out->dpad_down = (hat == 3 || hat == 4 || hat == 5);
out->dpad_left = (hat == 5 || hat == 6 || hat == 7);
}

static int ds4_init(Controller *ctrl)
{
ctrl->priv = NULL;
return 0;
}

static int ds4_parse_input(Controller *ctrl, const uint8_t *r, int len,
NormalizedInput *out)
{
(void)ctrl;

if (len < DS4_INPUT_LEN || r[0] != DS4_REPORT_INPUT_USB)
return -1;

memset(out, 0, sizeof(*out));

/* Sticks are already 0..255, centre 128, Y growing downwards — exactly
* what the virtual pad report takes, so no scaling or inversion. */
out->left_stick_x = r[1];
out->left_stick_y = r[2];
out->right_stick_x = r[3];
out->right_stick_y = r[4];

uint8_t face = r[5];
out->square = !!(face & DS4_SQUARE);
out->cross = !!(face & DS4_CROSS);
out->circle = !!(face & DS4_CIRCLE);
out->triangle = !!(face & DS4_TRIANGLE);
map_dpad(face & DS4_DPAD_MASK, out);

uint8_t sys = r[6];
out->l1 = !!(sys & DS4_L1);
out->r1 = !!(sys & DS4_R1);
out->l3 = !!(sys & DS4_L3);
out->r3 = !!(sys & DS4_R3);
out->create = !!(sys & DS4_SHARE); /* Share → Create */
out->options = !!(sys & DS4_OPTIONS);

out->ps_button = !!(r[7] & DS4_PS);
out->touchpad = !!(r[7] & DS4_TOUCHPAD);

/* Analog triggers; the pad's own digital L2/R2 bits are redundant, vpad
* derives those from the analog value. */
out->l2_analog = r[8];
out->r2_analog = r[9];

return 0;
}

static void ds4_cleanup(Controller *ctrl)
{
(void)ctrl;
}

static const ControllerDriver ds4_driver_v1 = {
.name = "DualShock 4",
.type = CTRL_TYPE_DS4,
.vendor_id = SONY_VID,
.product_id = DS4_PID_V1,
.init = ds4_init,
.setup = NULL, /* no handshake: the pad streams input on its own */
.parse_input = ds4_parse_input,
.build_output = NULL, /* no rumble/lightbar support yet */
.cleanup = ds4_cleanup,
};

static const ControllerDriver ds4_driver_v2 = {
.name = "DualShock 4 v2",
.type = CTRL_TYPE_DS4,
.vendor_id = SONY_VID,
.product_id = DS4_PID_V2,
.init = ds4_init,
.setup = NULL,
.parse_input = ds4_parse_input,
.build_output = NULL,
.cleanup = ds4_cleanup,
};

const ControllerDriver *ds4_get_driver(int variant)
{
return variant == 1 ? &ds4_driver_v2 : &ds4_driver_v1;
}
69 changes: 64 additions & 5 deletions src/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,13 @@ static bool is_payload_process(pid_t pid)
}

/* Stop a previously deployed instance so two copies don't fight over the
* same USB device, then record our own pid. */
static void take_over_previous_instance(void)
* same USB device, then record our own pid. Returns true when no previous
* instance is left running, i.e. the pads it recorded in the ledger are stale
* and safe to remove. */
static bool take_over_previous_instance(void)
{
bool reap_stale = true;

FILE *f = fopen(PID_FILE, "r");
if (f) {
int old = 0;
Expand All @@ -91,6 +95,12 @@ static void take_over_previous_instance(void)
kill(old, SIGTERM);
for (int i = 0; i < 50 && kill(old, 0) == 0; i++)
usleep(20000);
if (kill(old, 0) == 0) {
/* It refused to go; deleting its pads would fight a live
* process, so leave them registered. */
klog_printf("[AnyController] previous instance pid=%d still running\n", old);
reap_stale = false;
}
}
fclose(f);
}
Expand All @@ -99,13 +109,16 @@ static void take_over_previous_instance(void)
fprintf(f, "%d\n", getpid());
fclose(f);
}
return reap_stale;
}

#define RETRY_BACKOFF_US 2000000ULL
#define RESUME_GRACE_US 3000000ULL
#define KEEPALIVE_US 1000000ULL
#define STATS_WINDOW_US 5000000ULL
#define STALL_US 500000ULL
#define SUBMIT_FAIL_LIMIT 30 /* failed inserts before rebuilding the pad (~250 ms) */
#define VPAD_RETRY_US 2000000ULL /* wait this long before rebuilding the pad again */

typedef struct {
uint64_t last_report_us;
Expand All @@ -115,6 +128,8 @@ typedef struct {
unsigned reports;
unsigned total_reports;
unsigned submits_failed;
unsigned submit_fail_streak; /* consecutive HID_INSERT_DATA failures */
uint64_t vpad_retry_us; /* earliest time to rebuild the virtual pad */
bool stalled;
bool ps_down;
} SlotStats;
Expand Down Expand Up @@ -159,10 +174,41 @@ static void submit_neutral(int i)
vpad_submit_input(vpads[i], &idle);
}

/* The kernel can invalidate a pad handle (account switch, system UI reset) and
* from then on every insert fails. Rebuild the pad on the same slot so the
* controller keeps working without the user re-sending the payload. */
static void recover_vpad(int i, uint64_t now)
{
if (now < stats[i].vpad_retry_us)
return;

if (vpads[i])
vpad_destroy(vpads[i]);
vpads[i] = vpad_create(VPAD_DEFAULT_USER);

stats[i].submit_fail_streak = 0;
stats[i].ps_down = false;
stats[i].vpad_retry_us = now + VPAD_RETRY_US;

if (!vpads[i])
klog_printf("[AnyController] slot %d: could not rebuild virtual pad errno=%d\n",
i, errno);
else
klog_printf("[AnyController] slot %d: virtual pad rebuilt -> handle=%d\n",
i, vpads[i]->handle);
}

/* USB vanished: keep the virtual DualSense registered for a moment so a
* short controller re-enumeration doesn't look like an unplug to the PS5. */
static void begin_grace(int i, uint64_t now)
{
/* Nothing to hold on to when the pad could not be rebuilt: drop the slot
* outright, so the resume path can never touch a NULL virtual pad. */
if (!vpads[i]) {
drop_slot(i, "USB lost without a virtual pad");
return;
}

klog_printf("[AnyController] slot %d: USB lost, holding DualSense for %llu ms\n",
i, (unsigned long long)(RESUME_GRACE_US / 1000));
release_usb(i);
Expand Down Expand Up @@ -326,8 +372,16 @@ static void poll_slot(int i, uint64_t now)
input.ps_button ? "pressed" : "released");
}
input.timestamp_us = now;
if (vpad_submit_input(vpads[i], &input) != 0 && st->submits_failed++ == 0)
klog_printf("[AnyController] slot %d: input submit failed errno=%d\n", i, errno);
if (!vpads[i]) {
recover_vpad(i, now);
} else if (vpad_submit_input(vpads[i], &input) == 0) {
st->submit_fail_streak = 0;
} else {
if (st->submits_failed++ == 0)
klog_printf("[AnyController] slot %d: input submit failed errno=%d\n", i, errno);
if (++st->submit_fail_streak >= SUBMIT_FAIL_LIMIT)
recover_vpad(i, now);
}
}

if (now - st->last_keepalive_us >= KEEPALIVE_US) {
Expand All @@ -353,7 +407,7 @@ int main(void)
ANYCONTROLLER_VERSION_MAJOR, ANYCONTROLLER_VERSION_MINOR,
ANYCONTROLLER_VERSION_PATCH, getpid());

take_over_previous_instance();
bool reap_stale_vpads = take_over_previous_instance();
controller_drivers_init();

if (vpad_init() != 0) {
Expand All @@ -362,6 +416,11 @@ int main(void)
return 1;
}

/* Pads a crashed instance registered are still attached to the system and
* would show up as phantom DualSenses; remove them before adding ours. */
if (reap_stale_vpads)
vpad_reap_stale();

usb_init();
memset(controllers, 0, sizeof(controllers));
for (int i = 0; i < MAX_CONTROLLERS; i++)
Expand Down
Loading