diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index 913d11914..ad5e03374 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -266,6 +266,31 @@ static std::unordered_map &ff_effects() { return *map; } +// Every fd the maps hold, readable without controller_mutex(): the hooks see each read, write, +// ioctl and poll a process makes, and almost none are on these. Set before an fd is handed out, +// cleared once no map holds it; an fd past the bitmap takes the lock once any such fd exists. +static constexpr int kWatchedFds = 1 << 16; +static constexpr int kWatchedBits = sizeof(unsigned long) * 8; +static std::atomic watched_fds[kWatchedFds / kWatchedBits]; +static std::atomic watched_beyond{false}; + +static void watch_fd(int fd) { + if (fd < 0) return; + if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release); + else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release); +} + +static void unwatch_fd(int fd) { + if (fd >= 0 && fd < kWatchedFds) + watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release); +} + +static bool watched(int fd) { + if (fd < 0) return false; + if (fd >= kWatchedFds) return watched_beyond.load(std::memory_order_acquire); + return (watched_fds[fd / kWatchedBits].load(std::memory_order_acquire) >> (fd % kWatchedBits)) & 1; +} + static const char *fake_hook_dir() { return config().hook_dir; } static const char *fake_udev_data_dir() { return config().udev_data_dir; } static bool fake_vibration_enabled() { return config().vibration_enabled; } @@ -692,6 +717,7 @@ open_fake_input_ring(const char *event, int flags) { { std::lock_guard guard(controller_mutex()); controller_map()[fd] = controller; + watch_fd(fd); } Logger::log("Adding ring-backed controller, fd %d event %s slot %d\n", fd, @@ -774,20 +800,29 @@ copy_slot_ioctl_string(int op, void *argp, const char *format, int event_number) } __attribute__((visibility("hidden"))) static bool is_fake_input_fd(int fd) { + if (!watched(fd)) return false; std::lock_guard guard(controller_mutex()); return controller_map().find(fd) != controller_map().end(); } +static bool fake_pad_withdrawn(const FakeController &fake); + +// A node whose pad is gone: the app republished its ring, or the pad was switched to a type that +// is not this node (it became the Deck or the Steam Controller again, fake_pad_withdrawn). +static bool controller_gone(const FakeController &fake) { + return ring_generation(fake.ring) != fake.generation || fake_pad_withdrawn(fake); +} + __attribute__((visibility("hidden"))) static bool fake_fd_is_stale(int fd) { + if (!watched(fd)) return false; std::lock_guard guard(controller_mutex()); auto controller = controller_map().find(fd); - return controller != controller_map().end() && - ring_generation(controller->second->ring) != controller->second->generation; + return controller != controller_map().end() && controller_gone(*controller->second); } // Caller holds controller_mutex(). static bool fake_has_unread_data(const FakeController &fake) { - if (ring_generation(fake.ring) != fake.generation) + if (controller_gone(fake)) return false; // Readiness never consumes resync requests or changes the read cursor. // Do not spin a nonblocking guest on a producer's unfinished publication. @@ -810,7 +845,7 @@ static bool fake_fd_has_unread_data(int fd) { static short fake_poll_revents(const std::shared_ptr &fake, short events) { std::lock_guard guard(controller_mutex()); if (fake->closed) return POLLNVAL; - if (ring_generation(fake->ring) != fake->generation) return POLLHUP; + if (controller_gone(*fake)) return POLLHUP; short ready = events & (POLLOUT | POLLWRNORM); if ((events & (POLLIN | POLLRDNORM)) && fake_has_unread_data(*fake)) ready |= events & (POLLIN | POLLRDNORM); @@ -892,6 +927,7 @@ __attribute__((visibility("hidden"))) static int open_uinput(int flags) { writer->owner = getpid(); std::lock_guard guard(controller_mutex()); uinput_map()[fd] = writer; + watch_fd(fd); Logger::log("uinput: opened as fd %d\n", fd); return fd; } @@ -1239,6 +1275,8 @@ struct DeckHidraw { uint8_t pending_feature = 0; bool touch = false; // Steam's touch controller (below), not the Deck bool triton = false; // The paired 2025 Steam Controller, with native BLE report IDs + bool emulated = false; // That Steam Controller made from the app's own pad (FAKE_EVDEV_TRITON_PAD) + uint8_t sony = 0; // The app's own pad as a DualShock 4 (4) or DualSense (5), else 0 }; // What the Deck has and an Xbox pad does not, after the ring's events: motion (PadMotion) and the @@ -1254,7 +1292,9 @@ struct DeckImu { int16_t pads[4]; // left X, Y, right X, Y: -32768..32767, Y up uint16_t pressure[2]; // left, right: 0..32767 uint32_t controls; // DECK_EXTRA_* bits + uint32_t pad_type; // PAD_TYPE_* | 0x80000000, written by the app; 0 until it does }; +static_assert(offsetof(DeckImu, pad_type) == 44, "DeckImu::pad_type matches FakeInputWriter"); // DeckImu::controls (DeckControls.kt). static constexpr uint32_t DECK_EXTRA_L4 = 1, DECK_EXTRA_R4 = 2, DECK_EXTRA_L5 = 4, DECK_EXTRA_R5 = 8, DECK_EXTRA_LPAD_TOUCH = 16, @@ -1278,7 +1318,7 @@ static_assert(sizeof(DeckImu) <= DECK_IMU_BLOCK_SIZE, "the IMU block is 64 bytes // report characteristic and answers with get_reply set to the same number. struct TritonSharedData { uint32_t magic; - uint32_t reserved; + uint32_t connected; // written by the app: the paired controller is connected and streaming uint64_t input_seq; uint32_t report_id; uint32_t input_length; @@ -1296,6 +1336,7 @@ struct TritonSharedData { static constexpr uint32_t TRITON_SHARED_MAGIC = 0x4e525454; static constexpr size_t TRITON_SHARED_BLOCK_SIZE = 256; static constexpr size_t TRITON_SHARED_OFFSET = FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE; +static_assert(offsetof(TritonSharedData, connected) == 4, "Triton connected offset"); static_assert(offsetof(TritonSharedData, input_seq) == 8, "Triton input sequence offset"); static_assert(offsetof(TritonSharedData, report_id) == 16, "Triton report ID offset"); static_assert(offsetof(TritonSharedData, input) == 24, "Triton input offset"); @@ -1312,6 +1353,9 @@ static_assert(sizeof(TritonSharedData) <= TRITON_SHARED_BLOCK_SIZE, "Triton ring static constexpr const char *TRITON_HIDRAW_PATH = "/dev/hidraw18"; static constexpr unsigned int TRITON_HIDRAW_MAJOR = 240; static constexpr unsigned int TRITON_HIDRAW_MINOR = 18; +// The app's own pad as the wired Steam Controller: a node of its own, so a paired one keeps 18. +static constexpr const char *TRITON_PAD_HIDRAW_PATH = "/dev/hidraw19"; +static constexpr unsigned int TRITON_PAD_HIDRAW_MINOR = 19; static constexpr int TRITON_REPORT_ID_BYTES = 1; static constexpr int TRITON_STATE_BYTES = 45; static constexpr int TRITON_REPORT_INTERVAL_US = 4000; @@ -1363,6 +1407,71 @@ static bool fake_deck_enabled() { return enabled == 1; } +// What the app's own pad is to the client, switchable while the session runs (the drawer's +// Controller page): the Deck (/dev/hidraw16), the wired Steam Controller (/dev/hidraw19, built from +// ring slot 0 as the Deck's reports are), or an Xbox 360 pad (its own evdev node, no HID device). +// The app writes the choice into the slot's Deck block (DeckImu::pad_type); until it has, +// FAKE_EVDEV_PAD_TYPE says what the session started with. Only the chosen device can be opened; +// the others end their streams, and the client is told through udev (pad_type_thread). +static constexpr uint32_t PAD_TYPE_DECK = 0, PAD_TYPE_STEAM = 1, PAD_TYPE_XBOX = 2, PAD_TYPE_DS4 = 3, + PAD_TYPE_DUALSENSE = 4, PAD_TYPE_LAST = PAD_TYPE_DUALSENSE; +static constexpr uint32_t PAD_TYPE_SET = 0x80000000u; + +__attribute__((visibility("hidden"))) static uint32_t session_pad_type() { + static int type = -1; + if (type < 0) { + const char *env = getenv("FAKE_EVDEV_PAD_TYPE"); + type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM + : env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX + : env && !strcmp(env, "dualshock4") ? PAD_TYPE_DS4 + : env && !strcmp(env, "dualsense") ? PAD_TYPE_DUALSENSE : PAD_TYPE_DECK; + } + return static_cast(type); +} + +// Slot 0's Deck and Triton blocks, mapped once, read-only; null until the ring file has them. +__attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() { + static std::atomic block{nullptr}; + static std::atomic tries{0}; + const uint8_t *mapped = block.load(std::memory_order_acquire); + if (mapped || tries.load(std::memory_order_relaxed) > 200) return mapped; + static std::mutex lock; + std::lock_guard guard(lock); + if ((mapped = block.load(std::memory_order_acquire))) return mapped; + tries.fetch_add(1, std::memory_order_relaxed); + static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); + std::string path = get_ring_path_for_slot(0); + int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd < 0) return nullptr; + struct stat st; + void *mapping = MAP_FAILED; + const size_t size = TRITON_SHARED_OFFSET + TRITON_SHARED_BLOCK_SIZE; + if (fstat(fd, &st) == 0 && static_cast(st.st_size) >= size) + mapping = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0); + syscall(SYS_close, fd); + if (mapping == MAP_FAILED) return nullptr; + mapped = static_cast(mapping); + block.store(mapped, std::memory_order_release); + return mapped; +} + +// The paired Bluetooth controller is offered only while the app has it connected: Steam asks a +// device it is offered for its info, and one that never answers holds up every other controller. +__attribute__((visibility("hidden"))) static bool triton_connected() { + const uint8_t *blocks = ring_blocks(); + if (!blocks) return false; + const auto *shared = reinterpret_cast(blocks + TRITON_SHARED_OFFSET); + return __atomic_load_n(&shared->magic, __ATOMIC_ACQUIRE) == TRITON_SHARED_MAGIC && + __atomic_load_n(&shared->connected, __ATOMIC_ACQUIRE) != 0; +} + +__attribute__((visibility("hidden"))) static uint32_t live_pad_type() { + const uint8_t *blocks = ring_blocks(); + const DeckImu *imu = blocks ? reinterpret_cast(blocks + FAKE_INPUT_RING_SIZE) : nullptr; + uint32_t value = imu ? __atomic_load_n(&imu->pad_type, __ATOMIC_ACQUIRE) : 0; + return value & PAD_TYPE_SET ? value & 0xff : session_pad_type(); +} + static bool fake_triton_enabled() { static int enabled = -1; if (enabled < 0) @@ -1397,17 +1506,37 @@ __attribute__((constructor)) static void log_client_start() { } __attribute__((visibility("hidden"))) static bool is_deck_hidraw_path(const char *pathname) { - return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH); + return pathname && fake_deck_enabled() && !strcmp(pathname, DECK_HIDRAW_PATH) && live_pad_type() == PAD_TYPE_DECK; +} + +// The app's own pad as a PlayStation controller: /dev/hidraw20 (DualShock 4) or /dev/hidraw21 +// (DualSense), USB devices of their own in SteamDeckPad's sysfs. Returns 4 or 5, or 0. +static constexpr const char *DS4_HIDRAW_PATH = "/dev/hidraw20"; +static constexpr const char *DUALSENSE_HIDRAW_PATH = "/dev/hidraw21"; +static constexpr unsigned int DS4_HIDRAW_MINOR = 20, DUALSENSE_HIDRAW_MINOR = 21; + +__attribute__((visibility("hidden"))) static int sony_pad_path(const char *pathname) { + if (!pathname || !fake_deck_enabled() || strncmp(pathname, "/dev/hidraw2", 12)) return 0; + if (!strcmp(pathname, DS4_HIDRAW_PATH)) return live_pad_type() == PAD_TYPE_DS4 ? 4 : 0; + if (!strcmp(pathname, DUALSENSE_HIDRAW_PATH)) return live_pad_type() == PAD_TYPE_DUALSENSE ? 5 : 0; + return 0; +} + +__attribute__((visibility("hidden"))) static bool is_triton_pad_path(const char *pathname) { + return pathname && fake_deck_enabled() && !strcmp(pathname, TRITON_PAD_HIDRAW_PATH) && + live_pad_type() == PAD_TYPE_STEAM; } __attribute__((visibility("hidden"))) static bool is_triton_hidraw_path(const char *pathname) { - return pathname && fake_triton_enabled() && !strcmp(pathname, TRITON_HIDRAW_PATH); + return pathname && fake_triton_enabled() && !strcmp(pathname, TRITON_HIDRAW_PATH) && triton_connected(); } // The app's first pad is the Deck now: its evdev node is withdrawn from everyone. Further players' // pads are left to the client alone, which hands them to games through Steam Input. __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const char *pathname) { if (!fake_deck_enabled() || !pathname || strncmp(pathname, "/dev/input/", 11)) return false; + // As an Xbox 360 pad it is its own evdev node again, for the client and games alike. + if (live_pad_type() == PAD_TYPE_XBOX) return false; const char *event = strrchr(pathname, '/') + 1; if (strncmp(event, "event", 5) && strncmp(event, "js", 2)) return false; int number = get_event_number(event); @@ -1415,6 +1544,13 @@ __attribute__((visibility("hidden"))) static bool is_withdrawn_pad_path(const ch return number == 0 || !process_is_steam_client(); } +static bool fake_pad_withdrawn(const FakeController &fake) { + if (fake.uinput || !fake.event) return false; + char path[64]; + snprintf(path, sizeof(path), "/dev/input/%s", fake.event); + return is_withdrawn_pad_path(path); +} + static inline void put16(uint8_t *at, int value) { at[0] = static_cast(value & 0xff); at[1] = static_cast((value >> 8) & 0xff); @@ -1486,7 +1622,8 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg) uint32_t buttons = 0; int32_t axes[8] = {}; DeckExtras extras; - for (;;) { + // Switched to another type, the stream ends: the client's read fails and it lets the Deck go. + while (live_pad_type() == PAD_TYPE_DECK) { if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) { buttons = snap.buttons; memcpy(axes, snap.axes, sizeof(axes)); @@ -1507,18 +1644,151 @@ __attribute__((visibility("hidden"))) static void *deck_report_thread(void *arg) return nullptr; } -__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { +// ---- The pad as a PlayStation controller ---- +// +// The DualShock 4 (054c:09cc) and DualSense (054c:0ce6) as they are on USB, read by the client's +// own PlayStation drivers (SDL's hidapi ps4/ps5 are the reference): input report 1 every 4 ms, +// the feature reports a driver reads at start answered here (calibration, serial, firmware), and +// output reports' rumble on the handheld's motor. Built from the same ring as the Deck's report: +// sticks, triggers, buttons, motion (in the units the calibration below declares), and the +// touchpad from the Deck controls' two trackpads, the left one on its left half and the right one +// on its right half, either's click as the touchpad's. +static constexpr int SONY_REPORT_BYTES = 64; +static constexpr int SONY_TOUCH_WIDTH = 1920; +static constexpr int SONY_TOUCH_HEIGHT_DS4 = 942, SONY_TOUCH_HEIGHT_DUALSENSE = 1080; +static constexpr const uint8_t SONY_MAC[6] = {0x5e, 0x43, 0x4b, 0x44, 0x44, 0x02}; + +struct SonyTouch { + bool down[2] = {}; + uint8_t id[2] = {}; + uint8_t next_id = 0; +}; + +// One finger per trackpad: Deck pads are -32768..32767 with Y up; the touchpad counts from its top +// left, 12 bits per axis. +__attribute__((visibility("hidden"))) static void put_sony_touch(uint8_t *at, SonyTouch &touch, int side, + bool down, int16_t x, int16_t y, int height) { + if (down && !touch.down[side]) touch.id[side] = touch.next_id++ & 0x7f; + touch.down[side] = down; + int half = SONY_TOUCH_WIDTH / 2; + int px = side * half + (static_cast(x) + 32768) * (half - 1) / 65535; + int py = (32767 - static_cast(y)) * (height - 1) / 65535; + at[0] = static_cast(touch.id[side] | (down ? 0 : 0x80)); + at[1] = static_cast(px & 0xff); + at[2] = static_cast(((px >> 8) & 0x0f) | ((py & 0x0f) << 4)); + at[3] = static_cast(py >> 4); +} + +__attribute__((visibility("hidden"))) static void +build_sony_report(uint8_t *report, uint8_t model, uint32_t packet, uint32_t buttons, const int32_t *axes, + const DeckExtras &extras, SonyTouch &touch) { + memset(report, 0, SONY_REPORT_BYTES); + report[0] = 0x01; + uint8_t *p = report + 1; + auto stick = [](int32_t value) { return static_cast(std::max(0, std::min(255, (value + 32768) >> 8))); }; + p[0] = stick(axes[0]); + p[1] = stick(axes[1]); // evdev and the PlayStation pads both count Y downwards + p[2] = stick(axes[2]); + p[3] = stick(axes[3]); + int32_t hat_x = axes[6], hat_y = axes[7]; + static const uint8_t kHat[3][3] = {{7, 0, 1}, {6, 8, 2}, {5, 4, 3}}; // [y+1][x+1] + uint8_t hat = kHat[(hat_y > 0) - (hat_y < 0) + 1][(hat_x > 0) - (hat_x < 0) + 1]; + // Snapshot order (kButtonBits): A B X Y L1 R1 View Menu L3 R3 Steam. + uint8_t face = (buttons & 4 ? 0x10 : 0) | (buttons & 1 ? 0x20 : 0) | (buttons & 2 ? 0x40 : 0) | (buttons & 8 ? 0x80 : 0); + uint8_t shoulders = (buttons & 16 ? 0x01 : 0) | (buttons & 32 ? 0x02 : 0) | (axes[5] > 0 ? 0x04 : 0) | + (axes[4] > 0 ? 0x08 : 0) | (buttons & 64 ? 0x10 : 0) | (buttons & 128 ? 0x20 : 0) | + (buttons & 256 ? 0x40 : 0) | (buttons & 512 ? 0x80 : 0); + bool click = extras.controls & (DECK_EXTRA_LPAD_CLICK | DECK_EXTRA_RPAD_CLICK); + uint8_t system = (buttons & 1024 ? 0x01 : 0) | (click ? 0x02 : 0); + uint8_t left_trigger = static_cast(std::max(0, std::min(255, axes[5]))); + uint8_t right_trigger = static_cast(std::max(0, std::min(255, axes[4]))); + // Motion: the Deck block's gyro is 2000 dps and its accel 2 g over 16 bits; the calibration + // reports declare 16 units per degree/s and 8192 per g, and the axes are the Deck's reordered as + // SDL reads both (Deck X, Z, -Y). + int16_t gyro[3] = {extras.gyro[0], extras.gyro[2], static_cast(-extras.gyro[1])}; + int16_t accel[3] = {static_cast(extras.accel[0] / 2), static_cast(extras.accel[2] / 2), + static_cast(-extras.accel[1] / 2)}; + bool left = extras.controls & DECK_EXTRA_LPAD_TOUCH, right = extras.controls & DECK_EXTRA_RPAD_TOUCH; + if (model == 4) { + p[4] = static_cast(hat | face); + p[5] = shoulders; + p[6] = static_cast(system | ((packet & 0x3f) << 2)); + p[7] = left_trigger; + p[8] = right_trigger; + put16(p + 9, static_cast(packet * 750)); // 5.33 us ticks: 4 ms + for (int i = 0; i < 3; i++) { + put16(p + 12 + i * 2, gyro[i]); + put16(p + 18 + i * 2, accel[i]); + } + p[29] = 0x1b; // on the cable, full + p[32] = 1; // one touch packet + p[33] = static_cast(packet); + put_sony_touch(p + 34, touch, 0, left, extras.pads[0], extras.pads[1], SONY_TOUCH_HEIGHT_DS4); + put_sony_touch(p + 38, touch, 1, right, extras.pads[2], extras.pads[3], SONY_TOUCH_HEIGHT_DS4); + } else { + p[4] = left_trigger; + p[5] = right_trigger; + p[6] = static_cast(packet); + p[7] = static_cast(hat | face); + p[8] = shoulders; + p[9] = system; + put32(p + 11, packet); + for (int i = 0; i < 3; i++) { + put16(p + 15 + i * 2, gyro[i]); + put16(p + 21 + i * 2, accel[i]); + } + put32(p + 27, packet * 12000); // 0.33 us ticks: 4 ms + put_sony_touch(p + 32, touch, 0, left, extras.pads[0], extras.pads[1], SONY_TOUCH_HEIGHT_DUALSENSE); + put_sony_touch(p + 36, touch, 1, right, extras.pads[2], extras.pads[3], SONY_TOUCH_HEIGHT_DUALSENSE); + p[52] = 0x2a; // charging, full + p[53] = 0x08; // USB + } +} + +__attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg) { + auto *holder = static_cast *>(arg); + std::shared_ptr self = *holder; + delete holder; + uint32_t type = self->sony == 4 ? PAD_TYPE_DS4 : PAD_TYPE_DUALSENSE; + uint32_t packet = 0; + SnapshotState snap; + uint32_t buttons = 0; + int32_t axes[8] = {}; + DeckExtras extras; + SonyTouch touch; + // Switched to another type, the stream ends, as unplugging the controller would. + while (live_pad_type() == type) { + if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) { + buttons = snap.buttons; + memcpy(axes, snap.axes, sizeof(axes)); + } + read_deck_extras(*self, extras); + uint8_t report[SONY_REPORT_BYTES]; + build_sony_report(report, self->sony, ++packet, buttons, axes, extras, touch); + if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && + errno != EAGAIN && errno != EWOULDBLOCK) + break; + struct timespec interval = {0, DECK_REPORT_INTERVAL_US * 1000L}; + nanosleep(&interval, nullptr); + } + syscall(SYS_close, self->peer); + munmap(self->ring, self->mapping_size); + return nullptr; +} + +__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) { + const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH; static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); if (!process_is_steam_client()) { // Only the client reads the Deck; a game sees Steam Input's virtual pad instead. - Logger::log("deck: %s refused: not the Steam client\n", DECK_HIDRAW_PATH); + Logger::log("deck: %s refused: not the Steam client\n", path); errno = ENOENT; return -1; } std::string ring_path = get_ring_path_for_slot(0); int ring_fd = ring_path.empty() ? -1 : my_open(ring_path.c_str(), O_RDONLY | O_CLOEXEC); if (ring_fd < 0) { - Logger::log("deck: %s refused: ring %s not openable (%s)\n", DECK_HIDRAW_PATH, + Logger::log("deck: %s refused: ring %s not openable (%s)\n", path, ring_path.empty() ? "(none configured)" : ring_path.c_str(), strerror(errno)); errno = ENODEV; return -1; @@ -1532,7 +1802,7 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { void *mapping = mmap(nullptr, mapping_size, PROT_READ, MAP_SHARED, ring_fd, 0); syscall(SYS_close, ring_fd); if (mapping == MAP_FAILED || !ring_header_is_valid(static_cast(mapping))) { - Logger::log("deck: %s refused: ring %s %s\n", DECK_HIDRAW_PATH, ring_path.c_str(), + Logger::log("deck: %s refused: ring %s %s\n", path, ring_path.c_str(), mapping == MAP_FAILED ? "could not be mapped" : "has no valid header"); if (mapping != MAP_FAILED) munmap(mapping, mapping_size); errno = ENODEV; @@ -1540,7 +1810,7 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { } int pair[2]; if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, pair) < 0) { - Logger::log("deck: %s refused: socketpair failed (%s)\n", DECK_HIDRAW_PATH, strerror(errno)); + Logger::log("deck: %s refused: socketpair failed (%s)\n", path, strerror(errno)); munmap(mapping, mapping_size); return -1; } @@ -1553,16 +1823,19 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { deck->peer = pair[1]; deck->ring = static_cast(mapping); deck->mapping_size = mapping_size; + deck->sony = sony; { std::lock_guard guard(controller_mutex()); deck_map()[pair[0]] = deck; + watch_fd(pair[0]); } pthread_t thread; auto *arg = new std::shared_ptr(deck); - if (pthread_create(&thread, nullptr, deck_report_thread, arg) != 0) { + if (pthread_create(&thread, nullptr, sony ? sony_report_thread : deck_report_thread, arg) != 0) { delete arg; std::lock_guard guard(controller_mutex()); deck_map().erase(pair[0]); + unwatch_fd(pair[0]); syscall(SYS_close, pair[0]); syscall(SYS_close, pair[1]); munmap(mapping, mapping_size); @@ -1570,7 +1843,8 @@ __attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags) { return -1; } pthread_detach(thread); - Logger::log("deck: %s opened as fd %d\n", DECK_HIDRAW_PATH, pair[0]); + Logger::log("deck: %s opened as fd %d%s\n", path, pair[0], + sony == 4 ? " (a DualShock 4)" : sony == 5 ? " (a DualSense)" : ""); return pair[0]; } @@ -1605,7 +1879,8 @@ __attribute__((visibility("hidden"))) static void *triton_report_thread(void *ar uint8_t report[TRITON_REPORT_ID_BYTES + 64] = {}; uint8_t report_id = 0x45; size_t length = TRITON_STATE_BYTES; - for (;;) { + // A disconnect ends the stream, as unplugging the controller would. + while (triton_connected()) { if (read_triton_state(*self, report_id, report + 1, length)) { report[0] = report_id; if (send(self->peer, report, length + 1, MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && @@ -1620,7 +1895,112 @@ __attribute__((visibility("hidden"))) static void *triton_report_thread(void *ar return nullptr; } -__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags) { +// Button bits of the Triton state report (SDL, SDL_hidapi_steam_triton.c). SDL reads MENU as Back +// and VIEW as Start, the reverse of the Deck's names. +static constexpr uint32_t TRITON_A = 0x00000001, TRITON_B = 0x00000002, TRITON_X = 0x00000004, + TRITON_Y = 0x00000008, TRITON_QAM = 0x00000010, TRITON_R3 = 0x00000020, + TRITON_VIEW = 0x00000040, TRITON_R4 = 0x00000080, TRITON_R5 = 0x00000100, + TRITON_R = 0x00000200, TRITON_DOWN = 0x00000400, TRITON_RIGHT = 0x00000800, + TRITON_LEFT = 0x00001000, TRITON_UP = 0x00002000, TRITON_MENU = 0x00004000, + TRITON_L3 = 0x00008000, TRITON_STEAM = 0x00010000, TRITON_L4 = 0x00020000, + TRITON_L5 = 0x00040000, TRITON_L = 0x00080000, + TRITON_RSTICK_TOUCH = 0x00100000, TRITON_RPAD_TOUCH = 0x00200000, + TRITON_RPAD_CLICK = 0x00400000, TRITON_RTRIGGER_CLICK = 0x00800000, + TRITON_LSTICK_TOUCH = 0x01000000, TRITON_LPAD_TOUCH = 0x02000000, + TRITON_LPAD_CLICK = 0x04000000, TRITON_LTRIGGER_CLICK = 0x08000000, + TRITON_RGRIP_TOUCH = 0x10000000, TRITON_LGRIP_TOUCH = 0x20000000; +// The pad is built in, so it is the wired controller: 28de:1302 on USB, state report 0x42 (the +// same layout as the Bluetooth 0x45), where the paired one is 28de:1303 on Bluetooth. +static constexpr uint8_t TRITON_STATE_WIRED = 0x42; +static constexpr int16_t TRITON_WIRED_PRODUCT = 0x1302; +// A stick counts as touched once it leaves its centre: the pad has no capacitive caps to ask. +static constexpr int32_t TRITON_STICK_TOUCH = 2000; + +// The Triton BLE state report (SDL, controller_structs.h: TritonMTUNoQuat_t) from the ring's +// snapshot and the Deck block, which already hold the trackpads, back buttons and motion in the +// units both controllers share. A handheld is held whenever it is played, so both grips read as +// touched: Steam's grip-sense activators (gyro while held, say) then simply stay on. +__attribute__((visibility("hidden"))) static void +build_triton_report(uint8_t *report, uint32_t packet, uint32_t buttons, const int32_t *axes, + const DeckExtras &extras) { + memset(report, 0, TRITON_STATE_BYTES); + report[0] = static_cast(packet); + static const uint32_t kButtonBits[11] = {TRITON_A, TRITON_B, TRITON_X, TRITON_Y, + TRITON_L, TRITON_R, TRITON_MENU, TRITON_VIEW, + TRITON_L3, TRITON_R3, TRITON_STEAM}; + uint32_t bits = TRITON_LGRIP_TOUCH | TRITON_RGRIP_TOUCH; + for (int i = 0; i < 11; i++) + if (buttons & (1u << i)) bits |= kButtonBits[i]; + if (buttons & SNAPSHOT_QAM_BIT) bits |= TRITON_QAM; + if (axes[7] < 0) bits |= TRITON_UP; + if (axes[7] > 0) bits |= TRITON_DOWN; + if (axes[6] < 0) bits |= TRITON_LEFT; + if (axes[6] > 0) bits |= TRITON_RIGHT; + int32_t left_trigger = axes[5], right_trigger = axes[4]; // ABS_BRAKE, ABS_GAS: 0..255 + if (left_trigger >= 250) bits |= TRITON_LTRIGGER_CLICK; + if (right_trigger >= 250) bits |= TRITON_RTRIGGER_CLICK; + if (abs(axes[0]) > TRITON_STICK_TOUCH || abs(axes[1]) > TRITON_STICK_TOUCH) bits |= TRITON_LSTICK_TOUCH; + if (abs(axes[2]) > TRITON_STICK_TOUCH || abs(axes[3]) > TRITON_STICK_TOUCH) bits |= TRITON_RSTICK_TOUCH; + uint32_t controls = extras.controls; + if (controls & DECK_EXTRA_L4) bits |= TRITON_L4; + if (controls & DECK_EXTRA_R4) bits |= TRITON_R4; + if (controls & DECK_EXTRA_L5) bits |= TRITON_L5; + if (controls & DECK_EXTRA_R5) bits |= TRITON_R5; + if (controls & DECK_EXTRA_LPAD_TOUCH) bits |= TRITON_LPAD_TOUCH; + if (controls & DECK_EXTRA_RPAD_TOUCH) bits |= TRITON_RPAD_TOUCH; + if (controls & DECK_EXTRA_LPAD_CLICK) bits |= TRITON_LPAD_CLICK; + if (controls & DECK_EXTRA_RPAD_CLICK) bits |= TRITON_RPAD_CLICK; + put32(report + 1, bits); + put16(report + 5, std::min(32767, left_trigger * 32767 / 255)); + put16(report + 7, std::min(32767, right_trigger * 32767 / 255)); + auto stick = [](int32_t value) { return std::max(-32767, std::min(32767, value)); }; + put16(report + 9, stick(axes[0])); + put16(report + 11, stick(-axes[1])); + put16(report + 13, stick(axes[2])); + put16(report + 15, stick(-axes[3])); + put16(report + 17, extras.pads[0]); + put16(report + 19, extras.pads[1]); + put16(report + 21, extras.pressure[0]); + put16(report + 23, extras.pads[2]); + put16(report + 25, extras.pads[3]); + put16(report + 27, extras.pressure[1]); + put32(report + 29, packet * TRITON_REPORT_INTERVAL_US); // IMU timestamp, microseconds + for (int i = 0; i < 3; i++) { + put16(report + 33 + i * 2, extras.accel[i]); + put16(report + 39 + i * 2, extras.gyro[i]); + } +} + +__attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg) { + auto *holder = static_cast *>(arg); + std::shared_ptr self = *holder; + delete holder; + uint32_t packet = 0; + SnapshotState snap; + uint32_t buttons = 0; + int32_t axes[8] = {}; + DeckExtras extras; + while (live_pad_type() == PAD_TYPE_STEAM) { + if (read_snapshot(self->ring, snap) && snap.generation == ring_generation(self->ring)) { + buttons = snap.buttons; + memcpy(axes, snap.axes, sizeof(axes)); + } + read_deck_extras(*self, extras); + uint8_t report[TRITON_REPORT_ID_BYTES + TRITON_STATE_BYTES]; + report[0] = TRITON_STATE_WIRED; + build_triton_report(report + 1, ++packet, buttons, axes, extras); + if (send(self->peer, report, sizeof(report), MSG_DONTWAIT | MSG_NOSIGNAL) < 0 && + errno != EAGAIN && errno != EWOULDBLOCK) + break; + struct timespec interval = {0, TRITON_REPORT_INTERVAL_US * 1000L}; + nanosleep(&interval, nullptr); + } + syscall(SYS_close, self->peer); + munmap(self->ring, self->mapping_size); + return nullptr; +} + +__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) { static auto my_open = reinterpret_cast(dlsym(RTLD_NEXT, "open")); if (!process_is_steam_client()) { errno = ENOENT; @@ -1663,16 +2043,19 @@ __attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags) { triton->ring = static_cast(mapping); triton->mapping_size = mapping_size; triton->triton = true; + triton->emulated = emulated; { std::lock_guard guard(controller_mutex()); deck_map()[pair[0]] = triton; + watch_fd(pair[0]); } pthread_t thread; auto *thread_arg = new std::shared_ptr(triton); - if (pthread_create(&thread, nullptr, triton_report_thread, thread_arg) != 0) { + if (pthread_create(&thread, nullptr, triton->emulated ? triton_pad_thread : triton_report_thread, thread_arg) != 0) { delete thread_arg; std::lock_guard guard(controller_mutex()); deck_map().erase(pair[0]); + unwatch_fd(pair[0]); syscall(SYS_close, pair[0]); syscall(SYS_close, pair[1]); munmap(mapping, mapping_size); @@ -1680,7 +2063,8 @@ __attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags) { return -1; } pthread_detach(thread); - Logger::log("triton: %s opened as fd %d (28de:1303)\n", TRITON_HIDRAW_PATH, pair[0]); + Logger::log("triton: %s opened as fd %d (%s)\n", emulated ? TRITON_PAD_HIDRAW_PATH : TRITON_HIDRAW_PATH, pair[0], + emulated ? "28de:1302, the app's pad" : "28de:1303"); return pair[0]; } @@ -1898,6 +2282,7 @@ __attribute__((visibility("hidden"))) static int open_touch_hidraw(int flags) { { std::lock_guard guard(controller_mutex()); deck_map()[pair[0]] = touch; + watch_fd(pair[0]); } touch_state([](TouchRingFile &r) { r.opened++; }); pthread_t thread; @@ -1906,6 +2291,7 @@ __attribute__((visibility("hidden"))) static int open_touch_hidraw(int flags) { delete arg; std::lock_guard guard(controller_mutex()); deck_map().erase(pair[0]); + unwatch_fd(pair[0]); syscall(SYS_close, pair[0]); syscall(SYS_close, pair[1]); touch_state([](TouchRingFile &r) { if (r.opened) r.opened--; }); @@ -1971,13 +2357,117 @@ __attribute__((visibility("hidden"))) static int ioctl_touch(DeckHidraw &touch, // Plugging in and out: the app flips `plugged`; this tells the client's HID discovery, which // otherwise never looks again (the sandbox gives it no kernel uevents). -__attribute__((visibility("hidden"))) static void touch_uevent(const char *action) { +__attribute__((visibility("hidden"))) static int inject_uevent(const char *action, const char *devpath, + const char *subsystem, const char *devname, + unsigned major, unsigned minor) { using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned); static auto inject = reinterpret_cast(dlsym(RTLD_DEFAULT, "bl_udevmon_inject")); - int sent = inject ? inject(action, TOUCH_DEVPATH, "hidraw", TOUCH_HIDRAW_PATH, DECK_HIDRAW_MAJOR, TOUCH_HIDRAW_MINOR) : -1; + return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1; +} + +__attribute__((visibility("hidden"))) static void touch_uevent(const char *action) { + int sent = inject_uevent(action, TOUCH_DEVPATH, "hidraw", TOUCH_HIDRAW_PATH, DECK_HIDRAW_MAJOR, TOUCH_HIDRAW_MINOR); Logger::log("touch: %s (udev event to %d monitor%s)\n", action, sent, sent == 1 ? "" : "s"); } +// The devices each pad type is, as SteamDeckPad.kt describes them and inputudev.c the evdev node. +static constexpr const char *DECK_DEVPATH = "/devices/droiddeck/usb1/1-1:1.2/0003:28DE:1205.0001/hidraw/hidraw16"; +static constexpr const char *TRITON_PAD_DEVPATH = "/devices/droiddeck/usb3/3-1:1.0/0003:28DE:1302.0004/hidraw/hidraw19"; +static constexpr const char *PAD_EVDEV_DEVPATH = "/devices/virtual/input/droiddeck0/event0"; +static constexpr const char *DS4_DEVPATH = "/devices/droiddeck/usb4/4-1:1.3/0003:054C:09CC.0005/hidraw/hidraw20"; +static constexpr const char *DUALSENSE_DEVPATH = "/devices/droiddeck/usb5/5-1:1.3/0003:054C:0CE6.0006/hidraw/hidraw21"; +static constexpr const char *TRITON_DEVPATH = "/devices/droiddeck/bluetooth/0005:28DE:1303.0003/hidraw/hidraw18"; + +__attribute__((visibility("hidden"))) static int pad_type_uevent(uint32_t type, const char *action) { + if (type == PAD_TYPE_DECK) + return inject_uevent(action, DECK_DEVPATH, "hidraw", DECK_HIDRAW_PATH, DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR); + if (type == PAD_TYPE_DS4) + return inject_uevent(action, DS4_DEVPATH, "hidraw", DS4_HIDRAW_PATH, DECK_HIDRAW_MAJOR, DS4_HIDRAW_MINOR); + if (type == PAD_TYPE_DUALSENSE) + return inject_uevent(action, DUALSENSE_DEVPATH, "hidraw", DUALSENSE_HIDRAW_PATH, DECK_HIDRAW_MAJOR, + DUALSENSE_HIDRAW_MINOR); + if (type == PAD_TYPE_STEAM) + return inject_uevent(action, TRITON_PAD_DEVPATH, "hidraw", TRITON_PAD_HIDRAW_PATH, TRITON_HIDRAW_MAJOR, + TRITON_PAD_HIDRAW_MINOR); + dev_t rdev = get_fake_input_rdev("event0"); + return inject_uevent(action, PAD_EVDEV_DEVPATH, "input", "/dev/input/event0", major(rdev), minor(rdev)); +} + +// SDL's HIDAPI in the client (the PlayStation pads' driver) finds hidraw devices by watching /dev +// with inotify, with udev off, and looks again on any entry named hidraw. The guest cannot +// create one in /dev, so the client's watch of /dev also covers this directory (inotify_add_watch +// below), where a switch makes and removes one. +__attribute__((visibility("hidden"))) static std::string hidraw_event_dir() { + return std::string(fake_hook_dir()) + "/.hidraw-events"; +} + +__attribute__((visibility("hidden"))) static void poke_hidraw_watchers(unsigned minor) { + std::string path = hidraw_event_dir() + "/hidraw" + std::to_string(minor); + int fd = static_cast(syscall(SYS_openat, AT_FDCWD, path.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC, 0600)); + if (fd >= 0) syscall(SYS_close, fd); + unlink(path.c_str()); +} + +__attribute__((visibility("hidden"))) static unsigned pad_type_minor(uint32_t type) { + return type == PAD_TYPE_DS4 ? DS4_HIDRAW_MINOR + : type == PAD_TYPE_DUALSENSE ? DUALSENSE_HIDRAW_MINOR + : type == PAD_TYPE_STEAM ? TRITON_PAD_HIDRAW_MINOR : DECK_HIDRAW_MINOR; +} + +// A switch, as the client sees one: the old device unplugged, then the new one plugged in. +__attribute__((visibility("hidden"))) static void *pad_type_thread(void *) { + static const char *kNames[] = {"Steam Deck controller", "Steam Controller", "Xbox 360 controller", + "DualShock 4", "DualSense"}; + uint32_t was = live_pad_type(); + bool paired = fake_triton_enabled() && triton_connected(); + Logger::log("pad: a %s at start%s\n", kNames[was % 5], paired ? ", the paired Steam Controller connected" : ""); + for (;;) { + struct timespec interval = {0, 50 * 1000 * 1000}; + nanosleep(&interval, nullptr); + bool connected = fake_triton_enabled() && triton_connected(); + if (connected != paired) { + paired = connected; + int sent = inject_uevent(connected ? "add" : "remove", TRITON_DEVPATH, "hidraw", TRITON_HIDRAW_PATH, + TRITON_HIDRAW_MAJOR, TRITON_HIDRAW_MINOR); + Logger::log("pad: the paired Steam Controller %s (udev event to %d monitors)\n", + connected ? "connected" : "disconnected", sent); + } + uint32_t now = live_pad_type(); + if (now == was || now > PAD_TYPE_LAST) continue; + int removed = pad_type_uevent(was, "remove"); + // Time for the client to let the old device go before the new one appears. + struct timespec settle = {0, 300 * 1000 * 1000}; + nanosleep(&settle, nullptr); + int added = pad_type_uevent(now, "add"); + if (was != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(was)); + if (now != PAD_TYPE_XBOX) poke_hidraw_watchers(pad_type_minor(now)); + // The pad's evdev node comes or goes with the Xbox 360 type. Its hotplug is watched with + // inotify on /dev/input (SDL's, with udev off), so it is moved out and back in: everyone + // watching sees it removed and added, and opens it again only if it is the pad now. + if (was == PAD_TYPE_XBOX || now == PAD_TYPE_XBOX) { + std::string node = std::string(fake_hook_dir()) + "/event0"; + std::string aside = std::string(fake_hook_dir()) + "/.event0-switching"; + if (rename(node.c_str(), aside.c_str()) == 0) { + nanosleep(&settle, nullptr); + if (rename(aside.c_str(), node.c_str()) != 0) + Logger::log("pad: event0 not put back (%s)\n", strerror(errno)); + } else { + Logger::log("pad: event0 not moved (%s)\n", strerror(errno)); + } + } + Logger::log("pad: now a %s (udev events to %d/%d monitors)\n", kNames[now], removed, added); + was = now; + } + return nullptr; +} + +__attribute__((constructor)) static void start_pad_type_watch() { + config(); + if (!process_is_steam_client() || !fake_deck_enabled()) return; + pthread_t thread; + if (pthread_create(&thread, nullptr, pad_type_thread, nullptr) == 0) pthread_detach(thread); +} + __attribute__((visibility("hidden"))) static void *touch_plug_thread(void *) { bool was = touch_plugged(); Logger::log("touch: %s at start\n", was ? "plugged in" : "unplugged"); @@ -2171,6 +2661,117 @@ deck_feature(DeckHidraw &deck, ioctl_request_t op, uint8_t *buf, bool set) { return static_cast(length); } +// The PlayStation pads' report descriptor: a gamepad with input report 1, the output report the +// model takes (5 on a DualShock 4, 2 on a DualSense) and the feature reports a driver reads. +static const uint8_t kDs4ReportDescriptor[] = { + 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, + 0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x05, 0x09, 0x21, 0x95, 0x1f, 0x91, 0x02, + 0x85, 0x02, 0x09, 0x24, 0x95, 0x24, 0xb1, 0x02, 0x85, 0x12, 0x09, 0x25, 0x95, 0x0f, 0xb1, 0x02, + 0x85, 0xa3, 0x09, 0x26, 0x95, 0x30, 0xb1, 0x02, 0x85, 0x81, 0x09, 0x27, 0x95, 0x3f, 0xb1, 0x02, + 0xc0}; +static const uint8_t kDualSenseReportDescriptor[] = { + 0x05, 0x01, 0x09, 0x05, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, + 0x85, 0x01, 0x09, 0x20, 0x95, 0x3f, 0x81, 0x02, 0x85, 0x02, 0x09, 0x21, 0x95, 0x2f, 0x91, 0x02, + 0x85, 0x05, 0x09, 0x22, 0x95, 0x28, 0xb1, 0x02, 0x85, 0x09, 0x09, 0x23, 0x95, 0x13, 0xb1, 0x02, + 0x85, 0x20, 0x09, 0x24, 0x95, 0x3f, 0xb1, 0x02, 0xc0}; + +// Calibration both models report the same way (SDL: LoadCalibrationData): no bias, and the +// ranges that make a unit 1/16 degree/s and 1/8192 g, the scale build_sony_report writes in. +__attribute__((visibility("hidden"))) static void put_sony_calibration(uint8_t *reply) { + for (int axis = 0; axis < 3; axis++) { + put16(reply + 7 + axis * 4, 8640); + put16(reply + 9 + axis * 4, -8640); + put16(reply + 23 + axis * 4, 8192); + put16(reply + 25 + axis * 4, -8192); + } + put16(reply + 19, 540); + put16(reply + 21, 540); +} + +__attribute__((visibility("hidden"))) static int sony_feature(const DeckHidraw &pad, uint8_t *buf, size_t size) { + if (!buf || size < 1) { + errno = EINVAL; + return -1; + } + uint8_t id = buf[0]; + uint8_t reply[64] = {}; + reply[0] = id; + size_t length = size; + if ((pad.sony == 4 && id == 0x02) || (pad.sony == 5 && id == 0x05)) { + put_sony_calibration(reply); + } else if ((pad.sony == 4 && (id == 0x12 || id == 0x81)) || (pad.sony == 5 && id == 0x09)) { + for (int i = 0; i < 6; i++) reply[1 + i] = SONY_MAC[5 - i]; // the address, last byte first + } else if (pad.sony == 5 && id == 0x20) { + reply[44] = 0x30; // firmware 0x0430: past the versions SDL treats as old + reply[45] = 0x04; + } + log_deck_feature("read", id); + length = std::min(length, sizeof(reply)); + memcpy(buf, reply, length); + return static_cast(length); +} + +// Rumble from the output report, when its flags say it carries rumble: a DualShock 4's report 5 +// (right/weak, then left/strong at 4 and 5), a DualSense's report 2 (at 3 and 4). +__attribute__((visibility("hidden"))) static void sony_output(const DeckHidraw &pad, const uint8_t *data, size_t size) { + if (!data || size < 6) return; + int weak, strong; + if (pad.sony == 4 && data[0] == 0x05) { + if (!(data[1] & 0x01)) return; + weak = data[4]; + strong = data[5]; + } else if (pad.sony == 5 && data[0] == 0x02) { + if (!(data[1] & 0x03)) return; + weak = data[3]; + strong = data[4]; + } else { + return; + } + // The drivers send a new report when the rumble changes and a zero one to stop it. + send_vibration(strong * 257, weak * 257, strong || weak ? 2000 : 0, 0); +} + +__attribute__((visibility("hidden"))) static int ioctl_sony(DeckHidraw &pad, ioctl_request_t op, void *argp) { + if (_IOC_TYPE(op) != 'H') { + errno = ENOTTY; + return -1; + } + const uint8_t *descriptor = pad.sony == 4 ? kDs4ReportDescriptor : kDualSenseReportDescriptor; + size_t descriptor_size = pad.sony == 4 ? sizeof(kDs4ReportDescriptor) : sizeof(kDualSenseReportDescriptor); + switch (_IOC_NR(op)) { + case 0x01: + *static_cast(argp) = static_cast(descriptor_size); + return 0; + case 0x02: { + auto *out = static_cast(argp); + uint32_t size; + memcpy(&size, out, sizeof(size)); + memcpy(out + 4, descriptor, std::min(size, descriptor_size)); + return 0; + } + case 0x03: { + struct { + uint32_t bustype; + int16_t vendor; + int16_t product; + } info = {BUS_USB, static_cast(0x054c), static_cast(pad.sony == 4 ? 0x09cc : 0x0ce6)}; + memcpy(argp, &info, sizeof(info)); + return 0; + } + case 0x04: + return copy_ioctl_string(op, argp, pad.sony == 4 ? "Sony Interactive Entertainment Wireless Controller" + : "Sony Interactive Entertainment DualSense Wireless Controller"); + case 0x05: return copy_ioctl_string(op, argp, pad.sony == 4 ? "usb-droiddeck-4/input3" : "usb-droiddeck-5/input3"); + case 0x08: return copy_ioctl_string(op, argp, "5e:43:4b:44:44:02"); + case 0x06: // HIDIOCSFEATURE: nothing the pads need is set this way + return static_cast(_IOC_SIZE(op)); + case 0x07: return sony_feature(pad, static_cast(argp), _IOC_SIZE(op)); + default: + errno = EINVAL; + return -1; + } +} + __attribute__((visibility("hidden"))) static int ioctl_deck(DeckHidraw &deck, ioctl_request_t op, void *argp) { if (_IOC_TYPE(op) != 'H') { @@ -2276,6 +2877,85 @@ __attribute__((visibility("hidden"))) static int triton_get_feature(DeckHidraw & return -1; } +// The emulated controller's feature reports: report ID 1, then the Valve message (type, length, +// payload), answered here as the Deck's are. The identity is the one a 2025 Steam Controller gave +// on device (HWID 72, its firmware timestamp), with this library's serial. +static constexpr uint32_t TRITON_HWID = 72; +static constexpr uint32_t TRITON_FW_TIMESTAMP = 0x6AC686B3; + +__attribute__((visibility("hidden"))) static int triton_pad_feature(DeckHidraw &triton, uint8_t *buf, size_t size, bool set) { + if (!buf || size < 2) { + errno = EINVAL; + return -1; + } + if (set) { + triton.pending_feature = buf[1]; + if (buf[1] == DECK_SET_SETTINGS_VALUES && size >= 3) { + int imu_mode = deck_imu_mode_change(buf, size); + if (imu_mode >= 0) publish_imu_mode(triton, imu_mode); + } + log_deck_feature("set", buf[1]); + return static_cast(size); + } + uint8_t reply[65] = {}; + reply[0] = buf[0]; + reply[1] = triton.pending_feature; + switch (triton.pending_feature) { + case DECK_GET_ATTRIBUTES_VALUES: { + // (attribute, 32-bit value) pairs: product id, capabilities, firmware timestamp, hardware id. + static const uint8_t kIds[] = {0x01, 0x02, 0x04, 0x09, 0x0a, 0x0b}; + const uint32_t values[] = {static_cast(TRITON_WIRED_PRODUCT), 0, TRITON_FW_TIMESTAMP, TRITON_HWID, 0, 4000}; + reply[2] = sizeof(kIds) * 5; + for (size_t i = 0; i < sizeof(kIds); i++) { + reply[3 + i * 5] = kIds[i]; + put32(reply + 4 + i * 5, values[i]); + } + break; + } + case DECK_GET_STRING_ATTRIBUTE: + reply[2] = 0x14; + reply[3] = 0x01; // the unit serial + memcpy(reply + 4, TRITON_SERIAL, strlen(TRITON_SERIAL)); + break; + case DECK_GET_CHIP_ID: + reply[2] = 0x11; + memcpy(reply + 4, "DROIDDECKCHIP02", 15); + break; + default: + break; + } + log_deck_feature("read", triton.pending_feature); + size_t length = std::min(size, sizeof(reply)); + memcpy(buf, reply, length); + return static_cast(length); +} + +// The emulated controller's haptic output reports (SDL, controller_structs.h) on the handheld's +// own motor: rumble as asked, the trackpad pulses and effects as short ticks. +__attribute__((visibility("hidden"))) static void triton_pad_output(const uint8_t *data, size_t size) { + if (!data || size < 2) return; + switch (data[0]) { + case 0x80: // ID_OUT_REPORT_HAPTIC_RUMBLE: type, intensity, left {speed, gain}, right {speed, gain} + if (size >= 10) { + int left = data[4] | data[5] << 8, right = data[7] | data[8] << 8; + // SDL repeats a held rumble every 40 ms, so each report lasts a little longer than that. + send_vibration(left, right, left || right ? 100 : 0, 0); + } + break; + case 0x81: // ID_OUT_REPORT_HAPTIC_PULSE: side, on_us, off_us, repeat count + if (size >= 8) { + int on_ms = (data[2] | data[3] << 8) / 1000, repeat = data[6] | data[7] << 8; + send_vibration(0, 40000, std::max(8, std::min(200, on_ms * std::max(1, repeat))), 0); + } + break; + case 0x82: case 0x83: case 0x84: case 0x85: // command, tone, sweep, script + send_vibration(0, 30000, 15, 0); + break; + default: + break; + } +} + __attribute__((visibility("hidden"))) static int ioctl_triton(DeckHidraw &triton, ioctl_request_t op, void *argp) { if (_IOC_TYPE(op) != 'H') { errno = ENOTTY; @@ -2290,6 +2970,8 @@ __attribute__((visibility("hidden"))) static int ioctl_triton(DeckHidraw &triton uint32_t size; memcpy(&size, descriptor, sizeof(size)); memcpy(descriptor + 4, kTritonReportDescriptor, std::min(size, sizeof(kTritonReportDescriptor))); + // The wired controller's state report (SteamDeckPad's TRITON_WIRED_REPORT_DESCRIPTOR). + if (triton.emulated && size > 15) descriptor[4 + 15] = TRITON_STATE_WIRED; return 0; } case 0x03: { @@ -2297,12 +2979,13 @@ __attribute__((visibility("hidden"))) static int ioctl_triton(DeckHidraw &triton uint32_t bustype; int16_t vendor; int16_t product; - } info = {BUS_BLUETOOTH, static_cast(0x28de), static_cast(0x1303)}; + } info = {triton.emulated ? static_cast(BUS_USB) : static_cast(BUS_BLUETOOTH), + static_cast(0x28de), triton.emulated ? TRITON_WIRED_PRODUCT : static_cast(0x1303)}; memcpy(argp, &info, sizeof(info)); return 0; } case 0x04: return copy_ioctl_string(op, argp, TRITON_NAME); - case 0x05: return copy_ioctl_string(op, argp, "bluetooth-droiddeck-1"); + case 0x05: return copy_ioctl_string(op, argp, triton.emulated ? "usb-droiddeck-3/input0" : "bluetooth-droiddeck-1"); case 0x08: return copy_ioctl_string(op, argp, TRITON_SERIAL); case 0x06: { // The client's feature reports are the report ID and 64 bytes; the last is padding the BLE @@ -2312,10 +2995,13 @@ __attribute__((visibility("hidden"))) static int ioctl_triton(DeckHidraw &triton errno = EINVAL; return -1; } + if (triton.emulated) return triton_pad_feature(triton, static_cast(argp), size, true); triton_queue_output(triton, static_cast(argp), std::min(size, 64), true); return static_cast(size); } - case 0x07: return triton_get_feature(triton, static_cast(argp), _IOC_SIZE(op)); + case 0x07: + if (triton.emulated) return triton_pad_feature(triton, static_cast(argp), _IOC_SIZE(op), false); + return triton_get_feature(triton, static_cast(argp), _IOC_SIZE(op)); default: errno = EINVAL; return -1; @@ -2491,7 +3177,9 @@ EXPORT int open(const char *pathname, int flags, ...) { if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags); if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags); - if (is_triton_hidraw_path(pathname)) return open_triton_hidraw(flags); + if (is_triton_hidraw_path(pathname)) return open_triton_hidraw(flags, false); + if (is_triton_pad_path(pathname)) return open_triton_hidraw(flags, true); + if (int sony = sony_pad_path(pathname)) return open_deck_hidraw(flags, static_cast(sony)); if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags); if (is_withdrawn_pad_path(pathname)) { errno = ENOENT; @@ -2567,7 +3255,9 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) { if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags); if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags); - if (is_triton_hidraw_path(pathname)) return open_triton_hidraw(flags); + if (is_triton_hidraw_path(pathname)) return open_triton_hidraw(flags, false); + if (is_triton_pad_path(pathname)) return open_triton_hidraw(flags, true); + if (int sony = sony_pad_path(pathname)) return open_deck_hidraw(flags, static_cast(sony)); if (is_touch_hidraw_path(pathname)) return open_touch_hidraw(flags); if (is_withdrawn_pad_path(pathname)) { errno = ENOENT; @@ -2626,7 +3316,8 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) { template static int fake_stat_path(const char *pathname, S *statbuf, Real real) { if (is_withdrawn_pad_path(pathname) || - ((is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname)) && !process_is_steam_client())) { + ((is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || + sony_pad_path(pathname)) && !process_is_steam_client())) { errno = ENOENT; return -1; } @@ -2642,10 +3333,16 @@ static int fake_stat_path(const char *pathname, S *statbuf, Real real) { statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, DECK_HIDRAW_MINOR); return 0; } - if (is_triton_hidraw_path(pathname)) { + if (int sony = sony_pad_path(pathname)) { memset(statbuf, 0, sizeof(*statbuf)); statbuf->st_mode = S_IFCHR | 0666; - statbuf->st_rdev = makedev(TRITON_HIDRAW_MAJOR, TRITON_HIDRAW_MINOR); + statbuf->st_rdev = makedev(DECK_HIDRAW_MAJOR, sony == 4 ? DS4_HIDRAW_MINOR : DUALSENSE_HIDRAW_MINOR); + return 0; + } + if (is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname)) { + memset(statbuf, 0, sizeof(*statbuf)); + statbuf->st_mode = S_IFCHR | 0666; + statbuf->st_rdev = makedev(TRITON_HIDRAW_MAJOR, is_triton_pad_path(pathname) ? TRITON_PAD_HIDRAW_MINOR : TRITON_HIDRAW_MINOR); return 0; } @@ -2689,12 +3386,17 @@ static int fake_stat_path(const char *pathname, S *statbuf, Real real) { template static int fake_stat_fd(int fd, S *buf, Real real) { int ret = real(fd, buf); + if (ret != 0 || !watched(fd)) return ret; std::lock_guard guard(controller_mutex()); if (ret == 0 && deck_map().count(fd)) { buf->st_mode = (buf->st_mode & ~S_IFMT) | S_IFCHR; const auto &device = *deck_map()[fd]; - unsigned int minor = device.touch ? TOUCH_HIDRAW_MINOR : (device.triton ? TRITON_HIDRAW_MINOR : DECK_HIDRAW_MINOR); + unsigned int minor = device.touch ? TOUCH_HIDRAW_MINOR + : device.sony == 4 ? DS4_HIDRAW_MINOR + : device.sony == 5 ? DUALSENSE_HIDRAW_MINOR + : device.emulated ? TRITON_PAD_HIDRAW_MINOR + : device.triton ? TRITON_HIDRAW_MINOR : DECK_HIDRAW_MINOR; buf->st_rdev = makedev(DECK_HIDRAW_MAJOR, minor); return ret; } @@ -2741,9 +3443,12 @@ EXPORT int access(const char *pathname, int mode) { static auto my_access = reinterpret_cast(dlsym(RTLD_NEXT, "access")); if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0; if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0; - if (is_triton_hidraw_path(pathname) && process_is_steam_client()) return 0; + if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) && + process_is_steam_client()) + return 0; if (is_touch_hidraw_path(pathname)) return 0; - if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname)) { + if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || + is_triton_pad_path(pathname) || sony_pad_path(pathname)) { errno = ENOENT; return -1; } @@ -2779,9 +3484,12 @@ EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) { static auto my_faccessat = reinterpret_cast(dlsym(RTLD_NEXT, "faccessat")); if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0; if (is_deck_hidraw_path(pathname) && process_is_steam_client()) return 0; - if (is_triton_hidraw_path(pathname) && process_is_steam_client()) return 0; + if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) && + process_is_steam_client()) + return 0; if (is_touch_hidraw_path(pathname)) return 0; - if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname)) { + if (is_withdrawn_pad_path(pathname) || is_deck_hidraw_path(pathname) || is_triton_hidraw_path(pathname) || + is_triton_pad_path(pathname) || sony_pad_path(pathname)) { errno = ENOENT; return -1; } @@ -2844,6 +3552,11 @@ EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) { pathname = fake_path; } else if (!strcmp(pathname, "/dev/input")) { pathname = fake_hook_dir(); + } else if (!strcmp(pathname, "/dev") && fake_deck_enabled() && process_is_steam_client()) { + // Beside /dev itself, not instead: the same descriptor gets both directories' events. + std::string events = hidraw_event_dir(); + mkdir(events.c_str(), 0700); + my_inotify_add_watch(fd, events.c_str(), mask); } } @@ -2868,7 +3581,7 @@ static bool wait_snapshot(std::shared_ptr fake, errno = EBADF; return false; } - if (ring_generation(fake->ring) != fake->generation) { + if (controller_gone(*fake)) { errno = ENODEV; return false; } @@ -2898,12 +3611,14 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { // The lock must not be held across the passthrough: binder's transport is a // blocking ioctl(BINDER_WRITE_READ), so a parked binder pool thread would own // controller_mutex() for as long as it waits and deadlock every other ioctl. + if (!watched(fd)) return syscall(SYS_ioctl, fd, op, argp); std::unique_lock guard(controller_mutex()); auto maker = uinput_map().find(fd); if (maker != uinput_map().end()) return ioctl_uinput(*maker->second, op, argp); auto deck = deck_map().find(fd); if (deck != deck_map().end()) { if (deck->second->touch) return ioctl_touch(*deck->second, op, argp); + if (deck->second->sony) return ioctl_sony(*deck->second, op, argp); if (deck->second->triton) { std::shared_ptr triton = deck->second; guard.unlock(); @@ -3117,6 +3832,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) { EXPORT int close(int fd) { static auto my_close = reinterpret_cast(dlsym(RTLD_NEXT, "close")); + if (!watched(fd)) return my_close(fd); close_uinput(fd); std::unique_lock guard(controller_mutex()); deck_map().erase(fd); @@ -3127,6 +3843,7 @@ EXPORT int close(int fd) { controller->second->closed = true; controller_map().erase(fd); } + unwatch_fd(fd); guard.unlock(); return my_close(fd); @@ -3135,6 +3852,7 @@ EXPORT int close(int fd) { static constexpr int kMaxRingWaitMs = 2; EXPORT ssize_t read(int fd, void *buf, size_t count) { + if (!watched(fd)) return syscall(SYS_read, fd, buf, count); std::unique_lock guard(controller_mutex()); auto controller = controller_map().find(fd); if (controller == controller_map().end()) { @@ -3158,7 +3876,7 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { errno = EBADF; return -1; } - if (ring_generation(fake.ring) != fake.generation) { + if (controller_gone(fake)) { errno = ENODEV; return -1; } @@ -3233,11 +3951,14 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { EXPORT ssize_t write(int fd, const void *buf, size_t count) { static auto my_write = reinterpret_cast(dlsym(RTLD_NEXT, "write")); + if (!watched(fd)) return my_write(fd, buf, count); std::unique_lock guard(controller_mutex()); auto made = uinput_map().find(fd); if (made != uinput_map().end()) return write_uinput(*made->second, buf, count); if (deck_map().count(fd)) { if (deck_map()[fd]->touch) touch_output(static_cast(buf), count); + else if (deck_map()[fd]->sony) sony_output(*deck_map()[fd], static_cast(buf), count); + else if (deck_map()[fd]->emulated) triton_pad_output(static_cast(buf), count); else if (deck_map()[fd]->triton) triton_queue_output(*deck_map()[fd], static_cast(buf), count, false); return static_cast(count); } @@ -3262,12 +3983,15 @@ EXPORT ssize_t write(int fd, const void *buf, size_t count) { } EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) { + if (!watched(fd)) return syscall(SYS_writev, fd, iov, iovcnt); std::unique_lock guard(controller_mutex()); if (deck_map().count(fd)) { ssize_t total = 0; auto device = deck_map()[fd]; for (int i = 0; i < iovcnt; i++) { if (device->touch) touch_output(static_cast(iov[i].iov_base), iov[i].iov_len); + else if (device->sony) sony_output(*device, static_cast(iov[i].iov_base), iov[i].iov_len); + else if (device->emulated) triton_pad_output(static_cast(iov[i].iov_base), iov[i].iov_len); else if (device->triton) triton_queue_output(*device, static_cast(iov[i].iov_base), iov[i].iov_len, false); total += static_cast(iov[i].iov_len); } @@ -3312,11 +4036,14 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout, static auto my_poll = reinterpret_cast(dlsym(RTLD_NEXT, "poll")); static auto my_ppoll = reinterpret_cast(dlsym(RTLD_NEXT, "ppoll")); + nfds_t first = 0; + while (first < nfds && !watched(fds[first].fd)) first++; bool has_fake_fds = false; std::vector real_fds; - real_fds.reserve(nfds); - std::vector> fake_fds(nfds); - { + std::vector> fake_fds; + if (first < nfds) { + real_fds.reserve(nfds); + fake_fds.resize(nfds); std::lock_guard guard(controller_mutex()); for (nfds_t i = 0; i < nfds; i++) { real_fds.push_back(fds[i]); diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index d1287bedd..e12aefb38 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -22,8 +22,6 @@ class App : Application() { override fun onCreate() { super.onCreate() CrashHandler.install(this) - // Before anything else touches the session prefs, so the first session already runs in Deck mode. - com.droiddeck.launcher.session.SessionPrefs.settleDeckModeDefault(this) com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this) com.droiddeck.launcher.update.AppUpdates.init(this) GpuClockPin.clearLeftover(this) diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index bab510fab..121abccf4 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -119,7 +119,6 @@ class MainActivity : ComponentActivity() { private var showNonAdreno by mutableStateOf(null) private var glThread by mutableStateOf(true) private var noGlError by mutableStateOf(true) - private var steamDeckMode by mutableStateOf(false) private var steamRepairQueued by mutableStateOf(false) private var mangoapp by mutableStateOf(true) private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK) @@ -341,7 +340,6 @@ class MainActivity : ComponentActivity() { private var resolution by mutableStateOf(com.droiddeck.launcher.session.SessionDisplay.DEFAULT_RESOLUTION) private var fexPreset by mutableStateOf("") private var forceSsbs by mutableStateOf(false) - private var steamChannel by mutableStateOf("steamdeck_publicbeta") private var runSteamAtStartup by mutableStateOf(false) private var theme by mutableStateOf("graphite") private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) @@ -363,6 +361,8 @@ class MainActivity : ComponentActivity() { } private var romsDir by mutableStateOf(null) private var steamGames by mutableStateOf>(emptyList()) + @Volatile private var componentSweepDone = false + @Volatile private var componentSweepSession: String? = null private var emulatorList by mutableStateOf>(emptyList()) private var runningLabel by mutableStateOf(null) private var logsEnabled by mutableStateOf(true) @@ -610,7 +610,15 @@ class MainActivity : ComponentActivity() { .putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true) }, // A store game may need something done first (an Epic game its sign-in code). - onSteamGame = { g -> if (shortcutPicker) chooseGameShortcut(g) else com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) } }, + onSteamGame = { g -> + if (shortcutPicker) chooseGameShortcut(g) + else { + // The launch takes the Windows components already on; the game's list is + // looked at again in the background once the session is over. + com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g) + com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) } + } + }, onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) }, onExportGameFile = { g -> pickGameExport(g) }, onSyncGameFiles = { pickGameExport(null) }, @@ -1295,8 +1303,6 @@ class MainActivity : ComponentActivity() { fexPreset = if (mode == SessionService.MODE_STEAM) fexPreset else null, forceSsbs = forceSsbs, syncBackend = if (mode == SessionService.MODE_STEAM) SessionPrefs.syncBackendOf(fastSync, fsyncFirst, syncFallback) else null, - steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null, - steamDeckMode = mode == SessionService.MODE_STEAM && steamDeckMode, steamRepairQueued = steamRepairQueued, mangoapp = mangoapp, steamController = if (mode == SessionService.MODE_STEAM) steamController else null, @@ -1374,13 +1380,7 @@ class MainActivity : ComponentActivity() { fsyncFirst = SessionPrefs.fsyncFirst(this) syncFallback = SessionPrefs.syncFallback(this) }, - onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id }, onSteamRepair = { steamRepairQueued = SteamRepair.queue(this) }, - onSteamDeckMode = { on -> - SessionPrefs.setSteamDeckMode(this, on) - steamDeckMode = on - steamChannel = SessionPrefs.steamChannel(this) - }, onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on }, onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id }, onRunSteamAtStartup = { on -> @@ -1452,6 +1452,8 @@ class MainActivity : ComponentActivity() { val fresh = folders.mapNotNull { f -> com.droiddeck.launcher.frontend.AddedGames.single(this, f)?.let { com.droiddeck.launcher.frontend.Library.addedGame(this, it) } } + // An added or edited game's Windows components, from its source's list. + fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.refreshLater(this, it) } ui.post { val paths = folders.toSet() steamGames = (steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path in paths } + fresh).distinctBy { it.gameId } @@ -1508,8 +1510,6 @@ class MainActivity : ComponentActivity() { fastSync = SessionPrefs.fastSync(this) fsyncFirst = SessionPrefs.fsyncFirst(this) syncFallback = SessionPrefs.syncFallback(this) - steamChannel = SessionPrefs.steamChannel(this) - steamDeckMode = SessionPrefs.steamDeckMode(this) steamRepairQueued = SteamRepair.queued(this) mangoapp = SessionPrefs.mangoapp(this) steamController = SessionPrefs.steamController(this) @@ -1568,7 +1568,6 @@ class MainActivity : ComponentActivity() { clientOverride = SessionPrefs.clientCpusOverride(this) glThread = SessionPrefs.glThread(this) noGlError = SessionPrefs.noGlError(this) - steamDeckMode = SessionPrefs.steamDeckMode(this) clientCores = CpuCores.parse(SessionPrefs.clientCpus(this)).ifEmpty { CpuCores.all.toSet() } gameCores = CpuCores.parse(SessionPrefs.gameCpus(this)).ifEmpty { CpuCores.all.toSet() } tuSysmem = SessionPrefs.tuSysmem(this) @@ -1609,13 +1608,39 @@ class MainActivity : ComponentActivity() { val scanGeneration = ++libraryScanGeneration if (shortcutPicker) shortcutLibraryScanning = true Thread({ - // One update with the whole list: the wall places games by their position in it, so a - // partial list first would shuffle every capsule when the rest arrived. LibraryCache - // covers the wait. + // Steam's own games first, from their manifests alone (quick), beside the added games + // already listed: a game Steam installed during the session shows as the session ends, + // without waiting for the added games' walk below. Its Windows components' list is + // queued then too, on the low-priority worker, so its page is usually ready. + if (ready) { + val quick = runCatching { Library.steamGames(this) }.getOrNull() + if (quick != null) ui.post { + if (scanGeneration == libraryScanGeneration && steamGames.isNotEmpty()) { + val before = steamGames.map { it.gameId }.toSet() + val fresh = quick.filter { it.gameId !in before } + if (fresh.isNotEmpty()) { + steamGames = (quick + steamGames.filter { it.library == Library.ADDED }).distinctBy { it.gameId } + fresh.forEach { com.droiddeck.launcher.frontend.AutoComponents.queueGame(this, it, asked = false) } + } + } + } + } + // Then one update with the whole list: the wall places games by their position in it, + // so a partial list first would shuffle every capsule when the rest arrived. + // LibraryCache covers the wait. val games = if (ready) Library.launchableGames(this) else emptyList() val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null } val all = games.distinctBy { it.gameId } if (ready) com.droiddeck.launcher.frontend.LibraryCache.save(this, all) + // Once per app start: the Steam games' Windows components from Steam's lists. + // Queued only, after the launcher has been up a little; the worker takes them one at a time. + // And again after each session (a game installed in it, files changed). + val endedSession = SessionState.sessionId.takeIf { !SessionState.running && it != null && it != componentSweepSession } + if (ready && (!componentSweepDone || endedSession != null)) { + componentSweepDone = true + endedSession?.let { componentSweepSession = it } + ui.postDelayed({ Thread({ com.droiddeck.launcher.frontend.AutoComponents.sweep(this, all) }, "components-sweep").start() }, 10_000) + } ui.post { if (scanGeneration == libraryScanGeneration) { steamGames = all diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 78d18e1be..97c408b8c 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -250,6 +250,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER) private var drawerControllerActive by mutableStateOf(false) private var backActionsInverted by mutableStateOf(false) + /** What the pad is to the Steam client (SessionPrefs.CONTROLLER_*), switched from the drawer. */ + private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK) /** The on-screen PC keyboard (ui/PcKeyboard): real key presses, Esc and F1 included. */ private var pcKeyboardOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) @@ -587,6 +589,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onKeyboardButton = { on -> updateControllerPrefs { ControllerPrefs.setKeyboardButton(this@SessionActivity, on) } }, onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ sendSteamGuide() }) else null, onQam = if (SessionState.mode == SessionService.MODE_STEAM) ({ triggerSteamQam() }) else null, + // Only where the session set the pad up to be switched (SessionService: deckPad). + padType = if (SessionState.mode == SessionService.MODE_STEAM && SessionState.deckPad) padType else null, + onPadType = { id -> + SessionPrefs.setSteamController(this@SessionActivity, id) + com.droiddeck.launcher.session.SteamDeckPad.showPad(SessionPrefs.padType(id)) + com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id)) + padType = id + }, backActionsInverted = backActionsInverted, onBackActionsInverted = { inverted -> SessionPrefs.setBackActionsInverted(this@SessionActivity, inverted) @@ -847,6 +857,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) oscMode = SessionPrefs.oscMode(this) backActionsInverted = SessionPrefs.backActionsInverted(this) + padType = SessionPrefs.steamController(this) } // ── Compositor ────────────────────────────────────────────────────────────────────────── diff --git a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt index d23021295..5fa562da9 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/DeviceReport.kt @@ -152,7 +152,6 @@ object DeviceReport { k("Zink lazy descriptors", SessionPrefs.zinkLazy(context)) k("Threaded GL (glthread)", SessionPrefs.glThread(context)) k("No GL error checks", SessionPrefs.noGlError(context)) - k("Steam Deck mode", SessionPrefs.steamDeckMode(context)) k("Steam controller", SessionPrefs.steamController(context)) k("Upscaler", (SessionPrefs.upscalerChoices.firstOrNull { it.first == SessionPrefs.upscaler(context) }?.second ?: "Off") + " (sharpness ${SessionPrefs.upscaleSharpness(context)}%)") diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt index ad48f2664..4406a7028 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt @@ -93,9 +93,12 @@ object LogRedactor { "(?i)(? = emptyList() + private var accounts: List = emptyList() /** * Learns every Steam account on the device from the client's loginusers.vdf - its AccountName @@ -103,12 +106,13 @@ object LogRedactor { * Names under three characters are skipped: blanking every "a" would ruin a log. */ fun learnAccounts(loginUsers: java.io.File) { - val found = ArrayList() + val found = ArrayList() try { if (loginUsers.isFile) { val kv = Regex("\"(AccountName|PersonaName)\"\\s+\"([^\"]*)\"") kv.findAll(loginUsers.readText()).map { it.groupValues[2].trim() }.filter { it.length >= 3 }.distinct().forEach { name -> - found += Regex("(?i)(? = emptyList() + private var own: List = emptyList() /** * Learns the device's addresses from the link file the app writes for the session @@ -133,7 +137,7 @@ object LogRedactor { * private, link-local and loopback addresses identify nobody and are left out. */ fun learnOwnAddresses(linkFile: java.io.File) { - val found = ArrayList() + val found = ArrayList() try { if (linkFile.isFile) linkFile.forEachLine { line -> val addr = line.trim().takeIf { it.startsWith("addr ") }?.split(Regex("\\s+"))?.getOrNull(1) ?: return@forEachLine @@ -142,9 +146,12 @@ object LogRedactor { val groups = expand6(addr)?.take(4) ?: return@forEachLine // Any spelling of an address in this /64: leading zeros dropped, :: anywhere after. val prefix = groups.joinToString(":") { g -> "0{0,3}" + Regex.escape(g.trimStart('0').ifEmpty { "0" }) } - found += Regex("(?i)(? found += Regex("(? found += Learned(Regex("(?$q" } + /** + * A line on its way through [redact]. Each rule runs only on a line holding what it cannot match + * without - a word, enough separators, a long enough run: most of a Steam log is lines no rule + * touches, and a session's logs went through every rule at about a megabyte a second. A line with anything but ASCII in it goes through + * every case-insensitive rule, since Android's regex folds case more widely than lowercase(). + */ + private class Line(var text: String) { + private val unfolded = text.any { it.code >= 0x80 } + private var lower: String? = null + + fun has(vararg words: String): Boolean { + if (unfolded) return true + val folded = lower ?: text.lowercase().also { lower = it } + return words.any { folded.contains(it) } + } + + fun set(next: String) { + if (next != text) { + text = next + lower = null + } + } + + fun holds(c: Char, times: Int): Boolean { + var n = 0 + for (ch in text) if (ch == c && ++n >= times) return true + return false + } + + inline fun hasRun(length: Int, inRun: (Char) -> Boolean): Boolean { + var n = 0 + for (ch in text) if (!inRun(ch)) n = 0 else if (++n >= length) return true + return false + } + } + + private fun isHex(c: Char) = c in '0'..'9' || c in 'a'..'f' || c in 'A'..'F' + /** [line] with every credential shape replaced. Null- and exception-safe by construction. */ fun redact(line: String): String { if (line.isEmpty()) return line return try { - var out = line - out = MAC_FIELD.replace(out) { "${it.groupValues[1]}" } - out = MAC.replace(out, "") - out = DEVICE_IDENTIFIER.replace(out) { + val out = Line(line) + if (out.has("mac")) out.set(MAC_FIELD.replace(out.text) { "${it.groupValues[1]}" }) + if (out.holds(':', 5) || out.holds('-', 5)) out.set(MAC.replace(out.text, "")) + if (out.has("serial", "android")) out.set(DEVICE_IDENTIFIER.replace(out.text) { val value = it.groupValues[2] val quote = value.first().takeIf { char -> char == '\"' || char == '\'' }?.toString().orEmpty() "${it.groupValues[1]}${quote}${quote}" + }) + if (out.holds('-', 4)) out.set(GUID.replace(out.text, "")) + if (out.has("jwt")) out.set(JWT_LABELLED.replace(out.text) { "${it.groupValues[1]}" }) + if ("ey" in out.text) out.set(JWT_BASE64.replace(out.text, "")) + if (out.has("token", "auth", "ticket", "sessionid", "steamloginsecure", "api", "machine", "pass", "pwd", "secret")) { + out.set(SECRET_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}" }) } - out = GUID.replace(out, "") - out = JWT_LABELLED.replace(out) { "${it.groupValues[1]}" } - out = JWT_BASE64.replace(out, "") - out = SECRET_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}" } - out = GUARD_CODE.replace(out) { "${it.groupValues[1]}" } - out = WEBAPI_KEY.replace(out, "") + if (out.has("guard", "factor", "2fa")) out.set(GUARD_CODE.replace(out.text) { "${it.groupValues[1]}" }) + if (out.hasRun(32, ::isHex)) out.set(WEBAPI_KEY.replace(out.text, "")) // Mask, not delete: the last four digits let a reader correlate lines to one account. - out = STEAMID64.replace(out) { "${it.groupValues[1]}********${it.groupValues[3]}" } - out = STEAMID3.replace(out) { m -> + if ("76561" in out.text) out.set(STEAMID64.replace(out.text) { "${it.groupValues[1]}********${it.groupValues[3]}" }) + if ("[U:1:" in out.text) out.set(STEAMID3.replace(out.text) { m -> val id = m.groupValues[1] "[U:1:${if (id.length > 4) "*".repeat(id.length - 4) + id.takeLast(4) else id}]" + }) + if (out.has("external")) out.set(EXTERNAL_ADDR.replace(out.text) { "${it.groupValues[1]}" }) + for (r in own) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "")) + if (out.has("onloginstatechange")) out.set(LOGIN_STATE.replace(out.text) { "${it.groupValues[1]}" }) + if ("OnLoginUsersChanged " in out.text) out.set(LOGIN_USERS.replace(out.text) { "${it.groupValues[1]}" }) + if (out.has("account", "user")) { + out.set(ACCOUNT_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }) } - out = EXTERNAL_ADDR.replace(out) { "${it.groupValues[1]}" } - for (r in own) out = r.replace(out, "") - out = LOGIN_STATE.replace(out) { "${it.groupValues[1]}" } - out = LOGIN_USERS.replace(out) { "${it.groupValues[1]}" } - out = ACCOUNT_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" } - out = LOGIN_KV.replace(out) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" } - for (r in accounts) out = r.replace(out, "") - out = EMAIL.replace(out, "") - out = RESIDUAL.replace(out) { "${it.groupValues[1]}=" } - out = LONG_TOKEN.replace(out, "") - out + if (out.has("login")) out.set(LOGIN_KV.replace(out.text) { "${it.groupValues[1]}${it.groupValues[2]}${quoted(it.groupValues[3])}" }) + for (r in accounts) if (r.needs == null || out.has(r.needs)) out.set(r.regex.replace(out.text, "")) + if ('@' in out.text) out.set(EMAIL.replace(out.text, "")) + if (out.has("jwt", "token", "ticket", "sessionid", "steamloginsecure", "machineauth")) { + out.set(RESIDUAL.replace(out.text) { "${it.groupValues[1]}=" }) + } + if (out.hasRun(88) { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }) { + out.set(LONG_TOKEN.replace(out.text, "")) + } + out.text } catch (t: Throwable) { // A log line is never worth crashing a session over, but an unscrubbed one must not // reach the file either. diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt index a29e43679..1fb5bb272 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameArt.kt @@ -137,8 +137,7 @@ object AddedGameArt { val out = ArrayList