Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
virtualhid_gamepad.cpp
Go to the documentation of this file.
1
6
7#include "src/config.h"
8#include "src/logging.h"
9
10#include <algorithm>
11#include <array>
12#include <map>
13#include <mutex>
14#include <cmath>
15#include <format>
16#include <random>
17#include <string_view>
18#include <utility>
19
20using namespace std::literals;
21
22namespace platf::gamepad {
23 namespace {
24 enum class controller_type {
25 generic,
26 xbox_360,
27 xbox_one,
28 xbox_series,
29 dualshock4,
30 dualsense,
31 switch_pro,
32 };
33
35 constexpr std::array controller_profiles {
36 std::pair {"generic"sv, controller_type::generic},
37 std::pair {"x360"sv, controller_type::xbox_360},
38 std::pair {"xone"sv, controller_type::xbox_one},
39 std::pair {"xseries"sv, controller_type::xbox_series},
40 std::pair {"ds4"sv, controller_type::dualshock4},
41 std::pair {"ds5"sv, controller_type::dualsense},
42 std::pair {"switch"sv, controller_type::switch_pro},
43 };
44
45 bool supports_input_events(lvh::GamepadProfileKind kind) {
46 using enum lvh::GamepadProfileKind;
47 return kind == generic || kind == xbox_360 || kind == xbox_one || kind == xbox_series;
48 }
49
50 bool valid_index(const input_raw_t *raw, int index) {
51 return raw && index >= 0 && static_cast<std::size_t>(index) < raw->gamepads.size();
52 }
53
54 std::shared_ptr<joypad_state> find_gamepad(input_raw_t *raw, int index) {
55 if (!valid_index(raw, index)) {
56 return {};
57 }
58 std::lock_guard lock {raw->gamepads_mutex};
59 return raw->gamepads[index];
60 }
61
62 float normalize_stick(std::int16_t value) {
63 return value < 0 ? static_cast<float>(value) / 32768.0F : static_cast<float>(value) / 32767.0F;
64 }
65
66 float normalize_trigger(std::uint8_t value) {
67 return static_cast<float>(value) / 255.0F;
68 }
69
70 void set_button(lvh::ButtonSet &buttons, std::uint32_t flags, std::uint32_t flag, lvh::GamepadButton button) {
71 buttons.set(button, (flags & flag) != 0);
72 }
73
74 lvh::ClientControllerType client_type(std::uint8_t type) {
75 switch (type) {
76 case LI_CTYPE_XBOX:
77 return lvh::ClientControllerType::xbox;
78 case LI_CTYPE_PS:
79 return lvh::ClientControllerType::playstation;
80 case LI_CTYPE_NINTENDO:
81 return lvh::ClientControllerType::nintendo;
82 default:
83 return lvh::ClientControllerType::unknown;
84 }
85 }
86
87 controller_type select_type(const gamepad_id_t &id, const gamepad_arrival_t &metadata) {
88 for (const auto &[name, type] : controller_profiles) {
89 if (config::input.gamepad == name) {
90 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will use " << name << " (manual selection)";
91 return type;
92 }
93 }
94 if (config::input.linux_gamepad_backend == "uinput"sv) {
95 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will use Xbox Series (automatic input-event policy)";
96 return controller_type::xbox_series;
97 }
98 if (metadata.type == LI_CTYPE_XBOX) {
99 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Xbox Series controller (client type)";
100 return controller_type::xbox_series;
101 }
102 if (metadata.type == LI_CTYPE_PS) {
103 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualSense controller (client type)";
104 return controller_type::dualsense;
105 }
106 if (metadata.type == LI_CTYPE_NINTENDO) {
107 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Nintendo Pro controller (client type)";
108 return controller_type::switch_pro;
109 }
110 if (config::input.motion_as_ds4 && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) {
111 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualSense controller (motion capability)";
112 return controller_type::dualsense;
113 }
114 if (config::input.touchpad_as_ds4 && (metadata.capabilities & LI_CCAP_TOUCHPAD)) {
115 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be DualSense controller (touchpad capability)";
116 return controller_type::dualsense;
117 }
118
119 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " will be Xbox Series controller (default)";
120 return controller_type::xbox_series;
121 }
122
123 // The same client's controller number gets the same MAC in every session
124 // and seat, so Steam, which keeps per-controller layouts by serial (the
125 // MAC on Switch and PlayStation pads), and games recognize it. 0x02: a
126 // locally administered unicast address.
127 std::string client_mac(const std::string &client_id, std::uint8_t controller_number) {
128 std::uint64_t hash = 14695981039346656037ULL;
129 for (const auto character : client_id + '/' + std::to_string(controller_number)) {
130 hash ^= static_cast<std::uint8_t>(character);
131 hash *= 1099511628211ULL;
132 }
133 return std::format(
134 "02:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
135 (hash >> 32U) & 0xFFU,
136 (hash >> 24U) & 0xFFU,
137 (hash >> 16U) & 0xFFU,
138 (hash >> 8U) & 0xFFU,
139 hash & 0xFFU
140 );
141 }
142
143 std::string playstation_stable_id(int global_index, std::string_view session_tag) {
144 if (config::input.virtualhid_randomize_mac) {
145 // A libvirtualhid Runtime numbers devices locally. Leaving stable_id
146 // empty would therefore give the first DualSense in every isolated
147 // Runtime the same generated MAC. Preserve the configuration's actual
148 // randomisation semantics and make collisions between sessions
149 // vanishingly unlikely.
150 std::random_device random;
151 std::array<std::uint8_t, 5> suffix {};
152 for (auto &byte : suffix) {
153 byte = static_cast<std::uint8_t>(random());
154 }
155 return std::format(
156 "02:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
157 suffix[0],
158 suffix[1],
159 suffix[2],
160 suffix[3],
161 suffix[4]
162 );
163 }
164
165 if (session_tag.empty()) {
166 return std::format("02:00:00:00:00:{:02x}", global_index & 0xFF);
167 }
168
169 // Keep deterministic MACs scoped to their private seat. The global
170 // controller index alone can be reused after a session exits; including
171 // the session tag prevents a recreated controller from aliasing another
172 // seat's identity in hid-playstation and userspace caches.
173 std::uint32_t hash = 2166136261U;
174 for (const auto character : session_tag) {
175 hash ^= static_cast<std::uint8_t>(character);
176 hash *= 16777619U;
177 }
178 return std::format(
179 "02:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
180 (hash >> 24U) & 0xFFU,
181 (hash >> 16U) & 0xFFU,
182 (hash >> 8U) & 0xFFU,
183 hash & 0xFFU,
184 global_index & 0xFF
185 );
186 }
187
188 lvh::DeviceProfile profile_for(controller_type type, const std::string &session_tag) {
189 lvh::DeviceProfile profile;
190 switch (type) {
191 case controller_type::generic:
192 profile = lvh::profiles::generic_gamepad();
193 profile.name = "Sunshine Generic (virtual) pad";
194 break;
195 case controller_type::xbox_360:
196 profile = lvh::profiles::xbox_360();
197 profile.name = "Sunshine X-Box 360 (virtual) pad";
198 break;
199 case controller_type::xbox_one:
200 profile = lvh::profiles::xbox_one();
201 profile.name = "Sunshine X-Box One (virtual) pad";
202 break;
203 case controller_type::xbox_series:
204 profile = lvh::profiles::xbox_series();
205 profile.name = "Sunshine X-Box Series (virtual) pad";
206 break;
207 case controller_type::dualshock4:
208 profile = lvh::profiles::dualshock4();
209 profile.name = "Sunshine PS4 (virtual) pad";
210 break;
211 case controller_type::dualsense:
212 profile = lvh::profiles::dualsense_usb();
213 profile.name = "Sunshine PS5 (virtual) pad";
214 break;
215 case controller_type::switch_pro:
216 profile = lvh::profiles::switch_pro();
217 profile.name = "Sunshine Nintendo (virtual) pad";
218 break;
219 }
220 profile.linux_phys = session_tag;
221 return profile;
222 }
223
224 lvh::CreateGamepadOptions creation_options(controller_type type, const gamepad_id_t &id, const gamepad_arrival_t &metadata, const std::string &session_tag) {
225 lvh::CreateGamepadOptions options;
226 options.profile = profile_for(type, session_tag);
227 options.prefer_input_events = prefer_input_events(options.profile.gamepad_kind);
228 options.metadata.global_index = id.globalIndex;
229 options.metadata.client_relative_index = id.clientRelativeIndex;
230 options.metadata.client_type = client_type(metadata.type);
231 options.metadata.has_motion_sensors = (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO)) != 0;
232 options.metadata.has_touchpad = (metadata.capabilities & LI_CCAP_TOUCHPAD) != 0;
233 options.metadata.has_rgb_led = (metadata.capabilities & LI_CCAP_RGB_LED) != 0;
234 options.metadata.has_battery = (metadata.capabilities & LI_CCAP_BATTERY_STATE) != 0;
235
236 const bool hid_pad = type == controller_type::dualsense || type == controller_type::dualshock4 || type == controller_type::switch_pro;
237 if (hid_pad && config::input.virtualhid_stable_mac && !metadata.client_id.empty()) {
238 options.metadata.stable_id = client_mac(metadata.client_id, id.clientRelativeIndex);
239 BOOST_LOG(info) << "Gamepad " << id.globalIndex << " MAC " << options.metadata.stable_id << " (client controller "
240 << int {id.clientRelativeIndex} << ')';
241 } else if (type == controller_type::dualsense || type == controller_type::dualshock4) {
242 options.metadata.stable_id = playstation_stable_id(id.globalIndex, session_tag);
243 } else {
244 options.metadata.stable_id = session_tag.empty() ? std::format("gamepad-{}", id.globalIndex) : std::format("{}-gamepad-{}", session_tag, id.globalIndex);
245 }
246 return options;
247 }
248
249 void warn_unsupported_client_features(controller_type type, const lvh::GamepadProfileSupport &support, int index, const gamepad_arrival_t &metadata) {
250 if (type == controller_type::dualsense || type == controller_type::dualshock4) {
251 if (!(metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) {
252 BOOST_LOG(warning) << "Gamepad " << index << " emulates PlayStation without client motion sensors";
253 }
254 if (!(metadata.capabilities & LI_CCAP_TOUCHPAD)) {
255 BOOST_LOG(warning) << "Gamepad " << index << " emulates PlayStation without a client touchpad";
256 }
257 return;
258 }
259
260 if (!support.supports_motion && (metadata.capabilities & (LI_CCAP_ACCEL | LI_CCAP_GYRO))) {
261 BOOST_LOG(warning) << "Gamepad " << index << " motion cannot be represented by the selected profile";
262 }
263 if (!support.supports_touchpad && (metadata.capabilities & LI_CCAP_TOUCHPAD)) {
264 BOOST_LOG(warning) << "Gamepad " << index << " touchpad cannot be represented by the selected profile";
265 }
266 if (!support.supports_rgb_led && (metadata.capabilities & LI_CCAP_RGB_LED)) {
267 BOOST_LOG(warning) << "Gamepad " << index << " RGB LED cannot be represented by the selected profile";
268 }
269 }
270
271 void handle_output(const std::shared_ptr<joypad_feedback_state> &state, feedback_queue_t feedback_queue, std::uint16_t client_index, const lvh::GamepadOutput &output) {
272 if (!feedback_queue) {
273 return;
274 }
275
276 std::lock_guard lock {state->mutex};
277 switch (output.kind) {
278 case lvh::GamepadOutputKind::rumble:
279 {
280 const std::array values {output.low_frequency_rumble, output.high_frequency_rumble};
281 if (state->last_rumble == values) {
282 return;
283 }
284 state->last_rumble = values;
285 feedback_queue->raise(gamepad_feedback_msg_t::make_rumble(client_index, values[0], values[1]));
286 return;
287 }
288 case lvh::GamepadOutputKind::trigger_rumble:
289 {
290 const std::array values {output.left_trigger_rumble, output.right_trigger_rumble};
291 if (state->last_trigger_rumble == values) {
292 return;
293 }
294 state->last_trigger_rumble = values;
295 feedback_queue->raise(gamepad_feedback_msg_t::make_rumble_triggers(client_index, values[0], values[1]));
296 return;
297 }
298 case lvh::GamepadOutputKind::rgb_led:
299 {
300 const std::array values {output.red, output.green, output.blue};
301 if (state->last_rgb_led == values) {
302 return;
303 }
304 state->last_rgb_led = values;
305 feedback_queue->raise(gamepad_feedback_msg_t::make_rgb_led(client_index, values[0], values[1], values[2]));
306 return;
307 }
308 case lvh::GamepadOutputKind::adaptive_triggers:
309 feedback_queue->raise(gamepad_feedback_msg_t::make_adaptive_triggers(client_index, output.adaptive_trigger_flags, output.left_trigger_effect_type, output.right_trigger_effect_type, output.left_trigger_effect, output.right_trigger_effect));
310 return;
311 case lvh::GamepadOutputKind::player_leds:
312 case lvh::GamepadOutputKind::raw_report:
313 return;
314 }
315 }
316
317 std::optional<std::size_t> contact_slot(const joypad_state &gamepad, std::uint32_t pointer_id, bool active) {
318 for (std::size_t index = 0; index < gamepad.touch_pointer_ids.size(); ++index) {
319 if (gamepad.touch_pointer_ids[index] == pointer_id) {
320 return index;
321 }
322 }
323 if (!active) {
324 return std::nullopt;
325 }
326 for (std::size_t index = 0; index < gamepad.touch_pointer_ids.size(); ++index) {
327 if (!gamepad.touch_pointer_ids[index].has_value()) {
328 return index;
329 }
330 }
331 return std::nullopt;
332 }
333
334 // A detached desktop outlives its streams: the client drops out when it
335 // goes to the background or loses its network, and resumes the same
336 // desktop. Its gamepads stay, with the runtime they belong to, so Steam
337 // and games never see a controller leave. Only the client removing one,
338 // or the desktop stopping, ends it.
339 struct kept_t {
340 std::shared_ptr<lvh::Runtime> runtime;
341 std::map<std::uint8_t, std::shared_ptr<joypad_state>> gamepads;
342 };
343
344 std::mutex kept_mutex;
345 std::map<std::string, kept_t> kept;
346
347 bool keeps(const std::string &session_tag) {
348 return session_tag.starts_with("hermes-detached-");
349 }
350
351 void close(const std::shared_ptr<joypad_state> &gamepad) {
352 if (gamepad && gamepad->adapter) {
353 std::lock_guard lock {gamepad->mutex};
354 virtualhid::log_failure("gamepad close", gamepad->adapter->close());
355 }
356 }
357
358 void set_feedback(joypad_state &state, feedback_queue_t feedback_queue, std::uint8_t client_index) {
359 // The output worker must not own the adapter it calls back from. Keeping
360 // only independent feedback state also avoids joining that worker from
361 // its own callback when a controller disconnects during feedback delivery.
362 const auto feedback_state = std::make_shared<joypad_feedback_state>();
363 state.adapter->set_output_callback(
364 [feedback_state, feedback_queue, client_index = static_cast<std::uint16_t>(client_index)](
365 const lvh::GamepadOutput &output
366 ) {
367 handle_output(feedback_state, feedback_queue, client_index, output);
368 }
369 );
370 if (feedback_queue && state.adapter->support().supports_motion) {
371 feedback_queue->raise(gamepad_feedback_msg_t::make_motion_event_state(client_index, LI_MOTION_TYPE_ACCEL, 100));
372 feedback_queue->raise(gamepad_feedback_msg_t::make_motion_event_state(client_index, LI_MOTION_TYPE_GYRO, 100));
373 }
374 }
375 } // namespace
376
377 std::shared_ptr<lvh::Runtime> runtime_for(const std::string &session_tag) {
378 if (!keeps(session_tag)) {
379 return virtualhid::create_runtime();
380 }
381 std::lock_guard lock {kept_mutex};
382 auto &entry = kept[session_tag];
383 if (!entry.runtime) {
384 entry.runtime = virtualhid::create_runtime();
385 }
386 return entry.runtime;
387 }
388
389 void forget(const std::string &session_tag) {
390 kept_t entry;
391 {
392 std::lock_guard lock {kept_mutex};
393 const auto found = kept.find(session_tag);
394 if (found == kept.end()) {
395 return;
396 }
397 entry = std::move(found->second);
398 kept.erase(found);
399 }
400 for (const auto &[index, gamepad] : entry.gamepads) {
401 close(gamepad);
402 }
403 }
404
405 int alloc(input_raw_t *raw, const gamepad_id_t &id, const gamepad_arrival_t &metadata, feedback_queue_t feedback_queue) {
406 if (!valid_index(raw, id.globalIndex) || !raw->runtime) {
407 return -1;
408 }
409
410 const auto type = select_type(id, metadata);
411 if (keeps(raw->session_tag)) {
412 std::shared_ptr<joypad_state> state;
413 {
414 std::lock_guard lock {kept_mutex};
415 auto &gamepads = kept[raw->session_tag].gamepads;
416 if (const auto found = gamepads.find(id.clientRelativeIndex); found != gamepads.end()) {
417 state = std::move(found->second);
418 gamepads.erase(found);
419 }
420 }
421 if (state && state->type == static_cast<int>(type)) {
422 BOOST_LOG(info) << "Resuming kept gamepad " << int(id.clientRelativeIndex) << " of " << raw->session_tag;
423 set_feedback(*state, feedback_queue, id.clientRelativeIndex);
424 std::lock_guard lock {raw->gamepads_mutex};
425 raw->gamepads[id.globalIndex] = std::move(state);
426 return 0;
427 }
428 // The client now reports another kind of controller in that slot.
429 close(state);
430 }
431 const auto options = creation_options(type, id, metadata, raw->session_tag);
432 if (options.prefer_input_events && !supports_input_events(options.profile.gamepad_kind)) {
433 BOOST_LOG(warning) << "Selected gamepad profile requires native HID; choose the native or auto backend policy";
434 return -1;
435 }
436 auto created = lvh::GamepadStateAdapter::create(
437 *raw->runtime,
438 options
439 );
440 if (!created) {
441 BOOST_LOG(warning) << "Unable to create virtual gamepad " << id.globalIndex << ": "
442 << created.status.message();
443 return -1;
444 }
445
446 auto state = std::make_shared<joypad_state>();
447 state->adapter = std::move(created.adapter);
448 state->client_index = id.clientRelativeIndex;
449 state->type = static_cast<int>(type);
450 warn_unsupported_client_features(type, state->adapter->support(), id.globalIndex, metadata);
451 set_feedback(*state, feedback_queue, id.clientRelativeIndex);
452
453 {
454 std::lock_guard lock {raw->gamepads_mutex};
455 raw->gamepads[id.globalIndex] = std::move(state);
456 }
457 return 0;
458 }
459
460 void free(input_raw_t *raw, int index) {
461 if (!valid_index(raw, index)) {
462 return;
463 }
464 std::shared_ptr<joypad_state> gamepad;
465 {
466 std::lock_guard lock {raw->gamepads_mutex};
467 gamepad = std::exchange(raw->gamepads[index], {});
468 }
469 close(gamepad);
470 }
471
472 void release(input_raw_t *raw, int index) {
473 if (!valid_index(raw, index) || !keeps(raw->session_tag)) {
474 free(raw, index);
475 return;
476 }
477 std::shared_ptr<joypad_state> gamepad;
478 {
479 std::lock_guard lock {raw->gamepads_mutex};
480 gamepad = std::exchange(raw->gamepads[index], {});
481 }
482 if (!gamepad) {
483 return;
484 }
485 // Feedback for a stream that has ended goes nowhere until the next one.
486 set_feedback(*gamepad, {}, gamepad->client_index);
487 std::shared_ptr<joypad_state> replaced;
488 {
489 std::lock_guard lock {kept_mutex};
490 auto &slot = kept[raw->session_tag].gamepads[gamepad->client_index];
491 replaced = std::exchange(slot, gamepad);
492 }
493 close(replaced);
494 BOOST_LOG(info) << "Keeping gamepad " << int(gamepad->client_index) << " of " << raw->session_tag << " for the next stream";
495 }
496
497 void update(input_raw_t *raw, int index, const gamepad_state_t &input) {
498 if (!valid_index(raw, index)) {
499 return;
500 }
501 const auto gamepad = find_gamepad(raw, index);
502 if (!gamepad || !gamepad->adapter) {
503 return;
504 }
505
506 std::lock_guard lock {gamepad->mutex};
507 auto state = gamepad->adapter->state();
508 state.buttons.clear();
509 set_button(state.buttons, input.buttonFlags, A, lvh::GamepadButton::a);
510 set_button(state.buttons, input.buttonFlags, B, lvh::GamepadButton::b);
511 set_button(state.buttons, input.buttonFlags, X, lvh::GamepadButton::x);
512 set_button(state.buttons, input.buttonFlags, Y, lvh::GamepadButton::y);
513 set_button(state.buttons, input.buttonFlags, BACK, lvh::GamepadButton::back);
514 set_button(state.buttons, input.buttonFlags, START, lvh::GamepadButton::start);
515 set_button(state.buttons, input.buttonFlags, HOME, lvh::GamepadButton::guide);
516 set_button(state.buttons, input.buttonFlags, LEFT_STICK, lvh::GamepadButton::left_stick);
517 set_button(state.buttons, input.buttonFlags, RIGHT_STICK, lvh::GamepadButton::right_stick);
518 set_button(state.buttons, input.buttonFlags, LEFT_BUTTON, lvh::GamepadButton::left_shoulder);
519 set_button(state.buttons, input.buttonFlags, RIGHT_BUTTON, lvh::GamepadButton::right_shoulder);
520 set_button(state.buttons, input.buttonFlags, DPAD_UP, lvh::GamepadButton::dpad_up);
521 set_button(state.buttons, input.buttonFlags, DPAD_DOWN, lvh::GamepadButton::dpad_down);
522 set_button(state.buttons, input.buttonFlags, DPAD_LEFT, lvh::GamepadButton::dpad_left);
523 set_button(state.buttons, input.buttonFlags, DPAD_RIGHT, lvh::GamepadButton::dpad_right);
524 set_button(state.buttons, input.buttonFlags, MISC_BUTTON, lvh::GamepadButton::misc1);
525 set_button(state.buttons, input.buttonFlags, TOUCHPAD_BUTTON, lvh::GamepadButton::touchpad);
526 if (gamepad->adapter->support().supports_touchpad && config::input.ds4_back_as_touchpad_click && (input.buttonFlags & BACK)) {
527 state.buttons.set(lvh::GamepadButton::touchpad);
528 }
529 set_button(state.buttons, input.buttonFlags, PADDLE1, lvh::GamepadButton::paddle1);
530 set_button(state.buttons, input.buttonFlags, PADDLE2, lvh::GamepadButton::paddle2);
531 set_button(state.buttons, input.buttonFlags, PADDLE3, lvh::GamepadButton::paddle3);
532 set_button(state.buttons, input.buttonFlags, PADDLE4, lvh::GamepadButton::paddle4);
533 state.left_stick = {normalize_stick(input.lsX), normalize_stick(input.lsY)};
534 state.right_stick = {normalize_stick(input.rsX), normalize_stick(input.rsY)};
535 state.left_trigger = normalize_trigger(input.lt);
536 state.right_trigger = normalize_trigger(input.rt);
537 virtualhid::log_failure("gamepad state", gamepad->adapter->set_state(state));
538 }
539
540 void touch(input_raw_t *raw, const gamepad_touch_t &input) {
541 if (!valid_index(raw, input.id.globalIndex)) {
542 return;
543 }
544 const auto gamepad = find_gamepad(raw, input.id.globalIndex);
545 if (!gamepad || !gamepad->adapter || !gamepad->adapter->support().supports_touchpad) {
546 return;
547 }
548
549 std::lock_guard lock {gamepad->mutex};
550 if (input.eventType == LI_TOUCH_EVENT_CANCEL_ALL) {
551 auto state = gamepad->adapter->state();
552 for (auto &contact : state.touchpad_contacts) {
553 contact.active = false;
554 }
555 const auto result = gamepad->adapter->set_state(state);
556 virtualhid::log_failure("gamepad touch cancel all", result);
557 if (result.ok()) {
558 gamepad->touch_pointer_ids.fill(std::nullopt);
559 }
560 return;
561 }
562 const bool active = input.eventType == LI_TOUCH_EVENT_DOWN || input.eventType == LI_TOUCH_EVENT_MOVE;
563 if (!active && input.eventType != LI_TOUCH_EVENT_UP && input.eventType != LI_TOUCH_EVENT_CANCEL && input.eventType != LI_TOUCH_EVENT_HOVER_LEAVE) {
564 return;
565 }
566 if (active && (!std::isfinite(input.x) || !std::isfinite(input.y))) {
567 return;
568 }
569 const auto slot = contact_slot(*gamepad, input.pointerId, active);
570 if (!slot.has_value()) {
571 if (active) {
572 BOOST_LOG(warning) << "Dropping third simultaneous gamepad touch contact";
573 }
574 return;
575 }
576
577 auto state = gamepad->adapter->state();
578 // The wire pointer id is 32 bits, while DualSense tracking ids are 7 bits.
579 // Allocate an id on contact-down instead of truncating client ids, which
580 // could otherwise make two simultaneous fingers appear identical.
581 auto &contact = state.touchpad_contacts[*slot];
582 const bool new_contact = active && !contact.active;
583 auto tracking_id = static_cast<std::uint8_t>(gamepad->next_touch_id & 0x7F);
584 if (new_contact) {
585 // A finger can remain down while the other cycles through all 128 IDs.
586 // Never reuse the still-active finger's ID when the counter wraps.
587 for (const auto &other : state.touchpad_contacts) {
588 if (other.active && other.id == tracking_id) {
589 tracking_id = static_cast<std::uint8_t>((tracking_id + 1) & 0x7F);
590 }
591 }
592 }
593 if (active) {
594 contact = {
595 .id = new_contact ? tracking_id : contact.id,
596 .active = true,
597 .x = std::clamp(input.x, 0.0F, 1.0F),
598 .y = std::clamp(input.y, 0.0F, 1.0F),
599 };
600 } else {
601 // Release packets need only an ID. Their unused coordinates may be
602 // absent or invalid; preserve the last position so cleanup still works.
603 contact.active = false;
604 }
605 const auto result = gamepad->adapter->set_state(state);
606 virtualhid::log_failure("gamepad touch", result);
607 if (result.ok()) {
608 gamepad->touch_pointer_ids[*slot] = active ? std::optional {input.pointerId} : std::nullopt;
609 if (new_contact) {
610 gamepad->next_touch_id = static_cast<std::uint8_t>((tracking_id + 1) & 0x7F);
611 }
612 }
613 }
614
615 void motion(input_raw_t *raw, const gamepad_motion_t &input) {
616 if (!valid_index(raw, input.id.globalIndex)) {
617 return;
618 }
619 const auto gamepad = find_gamepad(raw, input.id.globalIndex);
620 if (!gamepad || !gamepad->adapter || !gamepad->adapter->support().supports_motion) {
621 return;
622 }
623
624 std::lock_guard lock {gamepad->mutex};
625 auto state = gamepad->adapter->state();
626 const lvh::Vector3 vector {input.x, input.y, input.z};
627 switch (input.motionType) {
628 case LI_MOTION_TYPE_ACCEL:
629 state.acceleration = vector;
630 break;
631 case LI_MOTION_TYPE_GYRO:
632 state.gyroscope = vector;
633 break;
634 default:
635 return;
636 }
637 virtualhid::log_failure("gamepad motion", gamepad->adapter->set_state(state));
638 }
639
640 void battery(input_raw_t *raw, const gamepad_battery_t &input) {
641 if (!valid_index(raw, input.id.globalIndex) || input.percentage == LI_BATTERY_PERCENTAGE_UNKNOWN) {
642 return;
643 }
644 const auto gamepad = find_gamepad(raw, input.id.globalIndex);
645 if (!gamepad || !gamepad->adapter || !gamepad->adapter->support().supports_battery) {
646 return;
647 }
648
649 lvh::GamepadBatteryState translated;
650 switch (input.state) {
651 case LI_BATTERY_STATE_DISCHARGING:
652 translated = lvh::GamepadBatteryState::discharging;
653 break;
654 case LI_BATTERY_STATE_CHARGING:
655 translated = lvh::GamepadBatteryState::charging;
656 break;
657 case LI_BATTERY_STATE_FULL:
658 translated = lvh::GamepadBatteryState::full;
659 break;
660 case LI_BATTERY_STATE_NOT_CHARGING:
661 translated = lvh::GamepadBatteryState::charging_error;
662 break;
663 default:
664 return;
665 }
666
667 std::lock_guard lock {gamepad->mutex};
668 auto state = gamepad->adapter->state();
669 state.battery = lvh::GamepadBattery {
670 .state = translated,
671 .percentage = static_cast<std::uint8_t>(std::min<int>(input.percentage, 100)),
672 };
673 virtualhid::log_failure("gamepad battery", gamepad->adapter->set_state(state));
674 }
675
676 bool prefer_input_events(lvh::GamepadProfileKind kind) {
677 if (config::input.linux_gamepad_backend == "native"sv) {
678 return false;
679 }
680 return config::input.linux_gamepad_backend == "uinput"sv || supports_input_events(kind);
681 }
682
684 if (config::input.linux_gamepad_backend == "uinput"sv) {
685 return false;
686 }
687 if (config::input.gamepad == "auto"sv) {
688 return true;
689 }
690 for (const auto &[name, type] : controller_profiles) {
691 if (config::input.gamepad == name) {
692 const auto &support = lvh::gamepad_profile_support(profile_for(type, {}));
693 return support.supports_touchpad || support.supports_motion;
694 }
695 }
696 return false;
697 }
698
699 std::vector<supported_gamepad_t> &supported_gamepads(input_t *input) {
700 static std::vector options {
701 supported_gamepad_t {"auto", true, ""},
702 supported_gamepad_t {"generic", false, "Input backend has not been initialized"},
703 supported_gamepad_t {"x360", false, "Input backend has not been initialized"},
704 supported_gamepad_t {"xone", false, "Input backend has not been initialized"},
705 supported_gamepad_t {"xseries", false, "Input backend has not been initialized"},
706 supported_gamepad_t {"ds4", false, "Input backend has not been initialized"},
707 supported_gamepad_t {"ds5", false, "Input backend has not been initialized"},
708 supported_gamepad_t {"switch", false, "Input backend has not been initialized"},
709 };
710 if (!input) {
711 return options;
712 }
713
714 auto *raw = static_cast<input_raw_t *>(input->get());
715 if (!raw || !raw->runtime) {
716 return options;
717 }
718
719 const gamepad_id_t probe_id {.globalIndex = MAX_GAMEPADS - 1, .clientRelativeIndex = 0};
720 const gamepad_arrival_t probe_metadata {.type = LI_CTYPE_UNKNOWN, .capabilities = 0, .supportedButtons = 0};
721 for (std::size_t index = 0; index < controller_profiles.size(); ++index) {
722 const auto request = creation_options(controller_profiles[index].second, probe_id, probe_metadata, raw->session_tag);
723 if (request.prefer_input_events && !supports_input_events(request.profile.gamepad_kind)) {
724 options[index + 1].is_enabled = false;
725 options[index + 1].reason_disabled = "This profile requires native HID; change the Linux gamepad backend policy";
726 continue;
727 }
728 auto created = raw->runtime->create_gamepad(request);
729 options[index + 1].is_enabled = static_cast<bool>(created);
730 options[index + 1].reason_disabled = created ? "" : created.status.message();
731 if (!created) {
732 BOOST_LOG(warning) << "Gamepad " << options[index + 1].name << " is disabled: "
733 << options[index + 1].reason_disabled;
734 }
735 }
736 options.front().is_enabled = std::ranges::any_of(options.begin() + 1, options.end(), [](const auto &option) {
737 return option.is_enabled;
738 });
739 options.front().reason_disabled = options.front().is_enabled ? "" : "No virtual gamepad profile is available";
740 return options;
741 }
742} // namespace platf::gamepad
std::vector< supported_gamepad_t > & supported_gamepads(input_t *input)
Gets the supported gamepads for this platform backend.
input_t input(const std::string &session_tag={})
Declarations for the configuration of Sunshine.
sha256_t hash(const std::string_view &plaintext)
Hashes the given plaintext using SHA-256.
Definition crypto.cpp:364
Declarations for logging related functions.
bool prefer_input_events(lvh::GamepadProfileKind kind)
Whether the configured Linux policy prefers an event-device gamepad.
bool supports_controller_extensions()
Whether the configured controller profile can expose motion or touchpad input.
std::shared_ptr< lvh::Runtime > runtime_for(const std::string &session_tag)
The libvirtualhid runtime for a detached desktop's gamepads, kept with them.
void release(input_raw_t *raw, int index)
Free a gamepad whose stream ended; a detached desktop keeps it.
void forget(const std::string &session_tag)
Close the gamepads kept for session_tag, and its runtime.
Gamepad translation for the Linux libvirtualhid backend.