summaryrefslogtreecommitdiff
path: root/src/input_common/drivers
diff options
context:
space:
mode:
Diffstat (limited to 'src/input_common/drivers')
-rw-r--r--src/input_common/drivers/gc_adapter.cpp483
-rw-r--r--src/input_common/drivers/gc_adapter.h128
-rw-r--r--src/input_common/drivers/tas_input.cpp320
-rw-r--r--src/input_common/drivers/tas_input.h200
4 files changed, 1131 insertions, 0 deletions
diff --git a/src/input_common/drivers/gc_adapter.cpp b/src/input_common/drivers/gc_adapter.cpp
new file mode 100644
index 000000000..6721ba4f7
--- /dev/null
+++ b/src/input_common/drivers/gc_adapter.cpp
@@ -0,0 +1,483 @@
1// Copyright 2014 Dolphin Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#include <fmt/format.h>
6#include <libusb.h>
7
8#include "common/logging/log.h"
9#include "common/param_package.h"
10#include "common/settings_input.h"
11#include "common/thread.h"
12#include "input_common/drivers/gc_adapter.h"
13
14namespace InputCommon {
15
16class LibUSBContext {
17public:
18 explicit LibUSBContext() {
19 init_result = libusb_init(&ctx);
20 }
21
22 ~LibUSBContext() {
23 libusb_exit(ctx);
24 }
25
26 LibUSBContext& operator=(const LibUSBContext&) = delete;
27 LibUSBContext(const LibUSBContext&) = delete;
28
29 LibUSBContext& operator=(LibUSBContext&&) noexcept = delete;
30 LibUSBContext(LibUSBContext&&) noexcept = delete;
31
32 [[nodiscard]] int InitResult() const noexcept {
33 return init_result;
34 }
35
36 [[nodiscard]] libusb_context* get() noexcept {
37 return ctx;
38 }
39
40private:
41 libusb_context* ctx;
42 int init_result{};
43};
44
45class LibUSBDeviceHandle {
46public:
47 explicit LibUSBDeviceHandle(libusb_context* ctx, uint16_t vid, uint16_t pid) noexcept {
48 handle = libusb_open_device_with_vid_pid(ctx, vid, pid);
49 }
50
51 ~LibUSBDeviceHandle() noexcept {
52 if (handle) {
53 libusb_release_interface(handle, 1);
54 libusb_close(handle);
55 }
56 }
57
58 LibUSBDeviceHandle& operator=(const LibUSBDeviceHandle&) = delete;
59 LibUSBDeviceHandle(const LibUSBDeviceHandle&) = delete;
60
61 LibUSBDeviceHandle& operator=(LibUSBDeviceHandle&&) noexcept = delete;
62 LibUSBDeviceHandle(LibUSBDeviceHandle&&) noexcept = delete;
63
64 [[nodiscard]] libusb_device_handle* get() noexcept {
65 return handle;
66 }
67
68private:
69 libusb_device_handle* handle{};
70};
71
72GCAdapter::GCAdapter(const std::string input_engine_) : InputEngine(input_engine_) {
73 if (usb_adapter_handle) {
74 return;
75 }
76 LOG_INFO(Input, "GC Adapter Initialization started");
77
78 libusb_ctx = std::make_unique<LibUSBContext>();
79 const int init_res = libusb_ctx->InitResult();
80 if (init_res == LIBUSB_SUCCESS) {
81 adapter_scan_thread =
82 std::jthread([this](std::stop_token stop_token) { AdapterScanThread(stop_token); });
83 } else {
84 LOG_ERROR(Input, "libusb could not be initialized. failed with error = {}", init_res);
85 }
86}
87
88GCAdapter::~GCAdapter() {
89 Reset();
90}
91
92void GCAdapter::AdapterInputThread(std::stop_token stop_token) {
93 LOG_DEBUG(Input, "GC Adapter input thread started");
94 Common::SetCurrentThreadName("yuzu:input:GCAdapter");
95 s32 payload_size{};
96 AdapterPayload adapter_payload{};
97
98 adapter_scan_thread = {};
99
100 while (!stop_token.stop_requested()) {
101 libusb_interrupt_transfer(usb_adapter_handle->get(), input_endpoint, adapter_payload.data(),
102 static_cast<s32>(adapter_payload.size()), &payload_size, 16);
103 if (IsPayloadCorrect(adapter_payload, payload_size)) {
104 UpdateControllers(adapter_payload);
105 UpdateVibrations();
106 }
107 std::this_thread::yield();
108 }
109
110 if (restart_scan_thread) {
111 adapter_scan_thread =
112 std::jthread([this](std::stop_token token) { AdapterScanThread(token); });
113 restart_scan_thread = false;
114 }
115}
116
117bool GCAdapter::IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size) {
118 if (payload_size != static_cast<s32>(adapter_payload.size()) ||
119 adapter_payload[0] != LIBUSB_DT_HID) {
120 LOG_DEBUG(Input, "Error reading payload (size: {}, type: {:02x})", payload_size,
121 adapter_payload[0]);
122 if (input_error_counter++ > 20) {
123 LOG_ERROR(Input, "GC adapter timeout, Is the adapter connected?");
124 adapter_input_thread.request_stop();
125 restart_scan_thread = true;
126 }
127 return false;
128 }
129
130 input_error_counter = 0;
131 return true;
132}
133
134void GCAdapter::UpdateControllers(const AdapterPayload& adapter_payload) {
135 for (std::size_t port = 0; port < pads.size(); ++port) {
136 const std::size_t offset = 1 + (9 * port);
137 const auto type = static_cast<ControllerTypes>(adapter_payload[offset] >> 4);
138 UpdatePadType(port, type);
139 if (DeviceConnected(port)) {
140 const u8 b1 = adapter_payload[offset + 1];
141 const u8 b2 = adapter_payload[offset + 2];
142 UpdateStateButtons(port, b1, b2);
143 UpdateStateAxes(port, adapter_payload);
144 }
145 }
146}
147
148void GCAdapter::UpdatePadType(std::size_t port, ControllerTypes pad_type) {
149 if (pads[port].type == pad_type) {
150 return;
151 }
152 // Device changed reset device and set new type
153 pads[port] = {};
154 pads[port].type = pad_type;
155}
156
157void GCAdapter::UpdateStateButtons(std::size_t port, [[maybe_unused]] u8 b1,
158 [[maybe_unused]] u8 b2) {
159 if (port >= pads.size()) {
160 return;
161 }
162
163 static constexpr std::array<PadButton, 8> b1_buttons{
164 PadButton::ButtonA, PadButton::ButtonB, PadButton::ButtonX, PadButton::ButtonY,
165 PadButton::ButtonLeft, PadButton::ButtonRight, PadButton::ButtonDown, PadButton::ButtonUp,
166 };
167
168 static constexpr std::array<PadButton, 4> b2_buttons{
169 PadButton::ButtonStart,
170 PadButton::TriggerZ,
171 PadButton::TriggerR,
172 PadButton::TriggerL,
173 };
174
175 for (std::size_t i = 0; i < b1_buttons.size(); ++i) {
176 const bool button_status = (b1 & (1U << i)) != 0;
177 const int button = static_cast<int>(b1_buttons[i]);
178 SetButton(pads[port].identifier, button, button_status);
179 }
180
181 for (std::size_t j = 0; j < b2_buttons.size(); ++j) {
182 const bool button_status = (b2 & (1U << j)) != 0;
183 const int button = static_cast<int>(b2_buttons[j]);
184 SetButton(pads[port].identifier, button, button_status);
185 }
186}
187
188void GCAdapter::UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload) {
189 if (port >= pads.size()) {
190 return;
191 }
192
193 const std::size_t offset = 1 + (9 * port);
194 static constexpr std::array<PadAxes, 6> axes{
195 PadAxes::StickX, PadAxes::StickY, PadAxes::SubstickX,
196 PadAxes::SubstickY, PadAxes::TriggerLeft, PadAxes::TriggerRight,
197 };
198
199 for (const PadAxes axis : axes) {
200 const auto index = static_cast<std::size_t>(axis);
201 const u8 axis_value = adapter_payload[offset + 3 + index];
202 if (pads[port].reset_origin_counter <= 18) {
203 if (pads[port].axis_origin[index] != axis_value) {
204 pads[port].reset_origin_counter = 0;
205 }
206 pads[port].axis_origin[index] = axis_value;
207 pads[port].reset_origin_counter++;
208 }
209 const f32 axis_status = (axis_value - pads[port].axis_origin[index]) / 110.0f;
210 SetAxis(pads[port].identifier, static_cast<int>(index), axis_status);
211 }
212}
213
214void GCAdapter::AdapterScanThread(std::stop_token stop_token) {
215 Common::SetCurrentThreadName("yuzu:input:ScanGCAdapter");
216 usb_adapter_handle = nullptr;
217 pads = {};
218 while (!stop_token.stop_requested() && !Setup()) {
219 std::this_thread::sleep_for(std::chrono::seconds(2));
220 }
221}
222
223bool GCAdapter::Setup() {
224 constexpr u16 nintendo_vid = 0x057e;
225 constexpr u16 gc_adapter_pid = 0x0337;
226 usb_adapter_handle =
227 std::make_unique<LibUSBDeviceHandle>(libusb_ctx->get(), nintendo_vid, gc_adapter_pid);
228 if (!usb_adapter_handle->get()) {
229 return false;
230 }
231 if (!CheckDeviceAccess()) {
232 usb_adapter_handle = nullptr;
233 return false;
234 }
235
236 libusb_device* const device = libusb_get_device(usb_adapter_handle->get());
237
238 LOG_INFO(Input, "GC adapter is now connected");
239 // GC Adapter found and accessible, registering it
240 if (GetGCEndpoint(device)) {
241 rumble_enabled = true;
242 input_error_counter = 0;
243 output_error_counter = 0;
244
245 std::size_t port = 0;
246 for (GCController& pad : pads) {
247 pad.identifier = {
248 .guid = Common::UUID{""},
249 .port = port++,
250 .pad = 0,
251 };
252 PreSetController(pad.identifier);
253 }
254
255 adapter_input_thread =
256 std::jthread([this](std::stop_token stop_token) { AdapterInputThread(stop_token); });
257 return true;
258 }
259 return false;
260}
261
262bool GCAdapter::CheckDeviceAccess() {
263 // This fixes payload problems from offbrand GCAdapters
264 const s32 control_transfer_error =
265 libusb_control_transfer(usb_adapter_handle->get(), 0x21, 11, 0x0001, 0, nullptr, 0, 1000);
266 if (control_transfer_error < 0) {
267 LOG_ERROR(Input, "libusb_control_transfer failed with error= {}", control_transfer_error);
268 }
269
270 s32 kernel_driver_error = libusb_kernel_driver_active(usb_adapter_handle->get(), 0);
271 if (kernel_driver_error == 1) {
272 kernel_driver_error = libusb_detach_kernel_driver(usb_adapter_handle->get(), 0);
273 if (kernel_driver_error != 0 && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
274 LOG_ERROR(Input, "libusb_detach_kernel_driver failed with error = {}",
275 kernel_driver_error);
276 }
277 }
278
279 if (kernel_driver_error && kernel_driver_error != LIBUSB_ERROR_NOT_SUPPORTED) {
280 usb_adapter_handle = nullptr;
281 return false;
282 }
283
284 const int interface_claim_error = libusb_claim_interface(usb_adapter_handle->get(), 0);
285 if (interface_claim_error) {
286 LOG_ERROR(Input, "libusb_claim_interface failed with error = {}", interface_claim_error);
287 usb_adapter_handle = nullptr;
288 return false;
289 }
290
291 return true;
292}
293
294bool GCAdapter::GetGCEndpoint(libusb_device* device) {
295 libusb_config_descriptor* config = nullptr;
296 const int config_descriptor_return = libusb_get_config_descriptor(device, 0, &config);
297 if (config_descriptor_return != LIBUSB_SUCCESS) {
298 LOG_ERROR(Input, "libusb_get_config_descriptor failed with error = {}",
299 config_descriptor_return);
300 return false;
301 }
302
303 for (u8 ic = 0; ic < config->bNumInterfaces; ic++) {
304 const libusb_interface* interfaceContainer = &config->interface[ic];
305 for (int i = 0; i < interfaceContainer->num_altsetting; i++) {
306 const libusb_interface_descriptor* interface = &interfaceContainer->altsetting[i];
307 for (u8 e = 0; e < interface->bNumEndpoints; e++) {
308 const libusb_endpoint_descriptor* endpoint = &interface->endpoint[e];
309 if ((endpoint->bEndpointAddress & LIBUSB_ENDPOINT_IN) != 0) {
310 input_endpoint = endpoint->bEndpointAddress;
311 } else {
312 output_endpoint = endpoint->bEndpointAddress;
313 }
314 }
315 }
316 }
317 // This transfer seems to be responsible for clearing the state of the adapter
318 // Used to clear the "busy" state of when the device is unexpectedly unplugged
319 unsigned char clear_payload = 0x13;
320 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, &clear_payload,
321 sizeof(clear_payload), nullptr, 16);
322 return true;
323}
324
325bool GCAdapter::SetRumble(const PadIdentifier& identifier, const Input::VibrationStatus vibration) {
326 const auto mean_amplitude = (vibration.low_amplitude + vibration.high_amplitude) * 0.5f;
327 const auto processed_amplitude =
328 static_cast<u8>((mean_amplitude + std::pow(mean_amplitude, 0.3f)) * 0.5f * 0x8);
329
330 pads[identifier.port].rumble_amplitude = processed_amplitude;
331 return rumble_enabled;
332}
333
334void GCAdapter::UpdateVibrations() {
335 // Use 8 states to keep the switching between on/off fast enough for
336 // a human to feel different vibration strenght
337 // More states == more rumble strengths == slower update time
338 constexpr u8 vibration_states = 8;
339
340 vibration_counter = (vibration_counter + 1) % vibration_states;
341
342 for (GCController& pad : pads) {
343 const bool vibrate = pad.rumble_amplitude > vibration_counter;
344 vibration_changed |= vibrate != pad.enable_vibration;
345 pad.enable_vibration = vibrate;
346 }
347 SendVibrations();
348}
349
350void GCAdapter::SendVibrations() {
351 if (!rumble_enabled || !vibration_changed) {
352 return;
353 }
354 s32 size{};
355 constexpr u8 rumble_command = 0x11;
356 const u8 p1 = pads[0].enable_vibration;
357 const u8 p2 = pads[1].enable_vibration;
358 const u8 p3 = pads[2].enable_vibration;
359 const u8 p4 = pads[3].enable_vibration;
360 std::array<u8, 5> payload = {rumble_command, p1, p2, p3, p4};
361 const int err =
362 libusb_interrupt_transfer(usb_adapter_handle->get(), output_endpoint, payload.data(),
363 static_cast<s32>(payload.size()), &size, 16);
364 if (err) {
365 LOG_DEBUG(Input, "Adapter libusb write failed: {}", libusb_error_name(err));
366 if (output_error_counter++ > 5) {
367 LOG_ERROR(Input, "GC adapter output timeout, Rumble disabled");
368 rumble_enabled = false;
369 }
370 return;
371 }
372 output_error_counter = 0;
373 vibration_changed = false;
374}
375
376bool GCAdapter::DeviceConnected(std::size_t port) const {
377 return pads[port].type != ControllerTypes::None;
378}
379
380void GCAdapter::Reset() {
381 adapter_scan_thread = {};
382 adapter_input_thread = {};
383 usb_adapter_handle = nullptr;
384 pads = {};
385 libusb_ctx = nullptr;
386}
387
388std::vector<Common::ParamPackage> GCAdapter::GetInputDevices() const {
389 std::vector<Common::ParamPackage> devices;
390 for (std::size_t port = 0; port < pads.size(); ++port) {
391 if (!DeviceConnected(port)) {
392 continue;
393 }
394 const std::string name = fmt::format("Gamecube Controller {}", port + 1);
395 devices.emplace_back(Common::ParamPackage{
396 {"engine", "gcpad"},
397 {"display", std::move(name)},
398 {"port", std::to_string(port)},
399 });
400 }
401 return devices;
402}
403
404ButtonMapping GCAdapter::GetButtonMappingForDevice(const Common::ParamPackage& params) {
405 // This list is missing ZL/ZR since those are not considered buttons.
406 // We will add those afterwards
407 // This list also excludes any button that can't be really mapped
408 static constexpr std::array<std::pair<Settings::NativeButton::Values, PadButton>, 12>
409 switch_to_gcadapter_button = {
410 std::pair{Settings::NativeButton::A, PadButton::ButtonA},
411 {Settings::NativeButton::B, PadButton::ButtonB},
412 {Settings::NativeButton::X, PadButton::ButtonX},
413 {Settings::NativeButton::Y, PadButton::ButtonY},
414 {Settings::NativeButton::Plus, PadButton::ButtonStart},
415 {Settings::NativeButton::DLeft, PadButton::ButtonLeft},
416 {Settings::NativeButton::DUp, PadButton::ButtonUp},
417 {Settings::NativeButton::DRight, PadButton::ButtonRight},
418 {Settings::NativeButton::DDown, PadButton::ButtonDown},
419 {Settings::NativeButton::SL, PadButton::TriggerL},
420 {Settings::NativeButton::SR, PadButton::TriggerR},
421 {Settings::NativeButton::R, PadButton::TriggerZ},
422 };
423 if (!params.Has("port")) {
424 return {};
425 }
426
427 ButtonMapping mapping{};
428 for (const auto& [switch_button, gcadapter_button] : switch_to_gcadapter_button) {
429 Common::ParamPackage button_params({{"engine", "gcpad"}});
430 button_params.Set("port", params.Get("port", 0));
431 button_params.Set("button", static_cast<int>(gcadapter_button));
432 mapping.insert_or_assign(switch_button, std::move(button_params));
433 }
434
435 // Add the missing bindings for ZL/ZR
436 static constexpr std::array<std::tuple<Settings::NativeButton::Values, PadButton, PadAxes>, 2>
437 switch_to_gcadapter_axis = {
438 std::tuple{Settings::NativeButton::ZL, PadButton::TriggerL, PadAxes::TriggerLeft},
439 {Settings::NativeButton::ZR, PadButton::TriggerR, PadAxes::TriggerRight},
440 };
441 for (const auto& [switch_button, gcadapter_buton, gcadapter_axis] : switch_to_gcadapter_axis) {
442 Common::ParamPackage button_params({{"engine", "gcpad"}});
443 button_params.Set("port", params.Get("port", 0));
444 button_params.Set("button", static_cast<s32>(gcadapter_buton));
445 button_params.Set("axis", static_cast<s32>(gcadapter_axis));
446 button_params.Set("threshold", 0.5f);
447 button_params.Set("range", 1.9f);
448 button_params.Set("direction", "+");
449 mapping.insert_or_assign(switch_button, std::move(button_params));
450 }
451 return mapping;
452}
453
454AnalogMapping GCAdapter::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
455 if (!params.Has("port")) {
456 return {};
457 }
458
459 AnalogMapping mapping = {};
460 Common::ParamPackage left_analog_params;
461 left_analog_params.Set("engine", "gcpad");
462 left_analog_params.Set("port", params.Get("port", 0));
463 left_analog_params.Set("axis_x", static_cast<int>(PadAxes::StickX));
464 left_analog_params.Set("axis_y", static_cast<int>(PadAxes::StickY));
465 mapping.insert_or_assign(Settings::NativeAnalog::LStick, std::move(left_analog_params));
466 Common::ParamPackage right_analog_params;
467 right_analog_params.Set("engine", "gcpad");
468 right_analog_params.Set("port", params.Get("port", 0));
469 right_analog_params.Set("axis_x", static_cast<int>(PadAxes::SubstickX));
470 right_analog_params.Set("axis_y", static_cast<int>(PadAxes::SubstickY));
471 mapping.insert_or_assign(Settings::NativeAnalog::RStick, std::move(right_analog_params));
472 return mapping;
473}
474
475std::string GCAdapter::GetUIName(const Common::ParamPackage& params) const {
476 if (params.Has("button")) {
477 return fmt::format("Button {}", params.Get("button", 0));
478 }
479
480 return "Bad GC Adapter";
481}
482
483} // namespace InputCommon
diff --git a/src/input_common/drivers/gc_adapter.h b/src/input_common/drivers/gc_adapter.h
new file mode 100644
index 000000000..c0bf1ed7a
--- /dev/null
+++ b/src/input_common/drivers/gc_adapter.h
@@ -0,0 +1,128 @@
1// Copyright 2014 Dolphin Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <mutex>
8#include <stop_token>
9#include <thread>
10
11#include "input_common/input_engine.h"
12
13struct libusb_context;
14struct libusb_device;
15struct libusb_device_handle;
16
17namespace InputCommon {
18
19class LibUSBContext;
20class LibUSBDeviceHandle;
21
22class GCAdapter : public InputCommon::InputEngine {
23public:
24 explicit GCAdapter(const std::string input_engine_);
25 ~GCAdapter();
26
27 bool SetRumble(const PadIdentifier& identifier,
28 const Input::VibrationStatus vibration) override;
29
30 /// Used for automapping features
31 std::vector<Common::ParamPackage> GetInputDevices() const override;
32 ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& params) override;
33 AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) override;
34 std::string GetUIName(const Common::ParamPackage& params) const override;
35
36private:
37 enum class PadButton {
38 Undefined = 0x0000,
39 ButtonLeft = 0x0001,
40 ButtonRight = 0x0002,
41 ButtonDown = 0x0004,
42 ButtonUp = 0x0008,
43 TriggerZ = 0x0010,
44 TriggerR = 0x0020,
45 TriggerL = 0x0040,
46 ButtonA = 0x0100,
47 ButtonB = 0x0200,
48 ButtonX = 0x0400,
49 ButtonY = 0x0800,
50 ButtonStart = 0x1000,
51 };
52
53 enum class PadAxes : u8 {
54 StickX,
55 StickY,
56 SubstickX,
57 SubstickY,
58 TriggerLeft,
59 TriggerRight,
60 Undefined,
61 };
62
63 enum class ControllerTypes {
64 None,
65 Wired,
66 Wireless,
67 };
68
69 struct GCController {
70 ControllerTypes type = ControllerTypes::None;
71 PadIdentifier identifier{};
72 bool enable_vibration = false;
73 u8 rumble_amplitude{};
74 std::array<u8, 6> axis_origin{};
75 u8 reset_origin_counter{};
76 };
77
78 using AdapterPayload = std::array<u8, 37>;
79
80 void UpdatePadType(std::size_t port, ControllerTypes pad_type);
81 void UpdateControllers(const AdapterPayload& adapter_payload);
82 void UpdateStateButtons(std::size_t port, u8 b1, u8 b2);
83 void UpdateStateAxes(std::size_t port, const AdapterPayload& adapter_payload);
84
85 void AdapterInputThread(std::stop_token stop_token);
86
87 void AdapterScanThread(std::stop_token stop_token);
88
89 bool IsPayloadCorrect(const AdapterPayload& adapter_payload, s32 payload_size);
90
91 /// For use in initialization, querying devices to find the adapter
92 bool Setup();
93
94 /// Returns true if we successfully gain access to GC Adapter
95 bool CheckDeviceAccess();
96
97 /// Captures GC Adapter endpoint address
98 /// Returns true if the endpoint was set correctly
99 bool GetGCEndpoint(libusb_device* device);
100
101 /// Returns true if there is a device connected to port
102 bool DeviceConnected(std::size_t port) const;
103
104 /// For shutting down, clear all data, join all threads, release usb
105 void Reset();
106
107 void UpdateVibrations();
108 // Updates vibration state of all controllers
109 void SendVibrations();
110 std::unique_ptr<LibUSBDeviceHandle> usb_adapter_handle;
111 std::array<GCController, 4> pads;
112
113 std::jthread adapter_input_thread;
114 std::jthread adapter_scan_thread;
115 bool restart_scan_thread{};
116
117 std::unique_ptr<LibUSBContext> libusb_ctx;
118
119 u8 input_endpoint{0};
120 u8 output_endpoint{0};
121 u8 input_error_counter{0};
122 u8 output_error_counter{0};
123 int vibration_counter{0};
124
125 bool rumble_enabled{true};
126 bool vibration_changed{true};
127};
128} // namespace InputCommon
diff --git a/src/input_common/drivers/tas_input.cpp b/src/input_common/drivers/tas_input.cpp
new file mode 100644
index 000000000..5e2101b27
--- /dev/null
+++ b/src/input_common/drivers/tas_input.cpp
@@ -0,0 +1,320 @@
1// Copyright 2021 yuzu Emulator Project
2// Licensed under GPLv2+
3// Refer to the license.txt file included.
4
5#include <cstring>
6#include <regex>
7#include <fmt/format.h>
8
9#include "common/fs/file.h"
10#include "common/fs/fs_types.h"
11#include "common/fs/path_util.h"
12#include "common/logging/log.h"
13#include "common/settings.h"
14#include "input_common/drivers/tas_input.h"
15
16namespace InputCommon::TasInput {
17
18enum TasAxes : u8 {
19 StickX,
20 StickY,
21 SubstickX,
22 SubstickY,
23 Undefined,
24};
25
26// Supported keywords and buttons from a TAS file
27constexpr std::array<std::pair<std::string_view, TasButton>, 20> text_to_tas_button = {
28 std::pair{"KEY_A", TasButton::BUTTON_A},
29 {"KEY_B", TasButton::BUTTON_B},
30 {"KEY_X", TasButton::BUTTON_X},
31 {"KEY_Y", TasButton::BUTTON_Y},
32 {"KEY_LSTICK", TasButton::STICK_L},
33 {"KEY_RSTICK", TasButton::STICK_R},
34 {"KEY_L", TasButton::TRIGGER_L},
35 {"KEY_R", TasButton::TRIGGER_R},
36 {"KEY_PLUS", TasButton::BUTTON_PLUS},
37 {"KEY_MINUS", TasButton::BUTTON_MINUS},
38 {"KEY_DLEFT", TasButton::BUTTON_LEFT},
39 {"KEY_DUP", TasButton::BUTTON_UP},
40 {"KEY_DRIGHT", TasButton::BUTTON_RIGHT},
41 {"KEY_DDOWN", TasButton::BUTTON_DOWN},
42 {"KEY_SL", TasButton::BUTTON_SL},
43 {"KEY_SR", TasButton::BUTTON_SR},
44 {"KEY_CAPTURE", TasButton::BUTTON_CAPTURE},
45 {"KEY_HOME", TasButton::BUTTON_HOME},
46 {"KEY_ZL", TasButton::TRIGGER_ZL},
47 {"KEY_ZR", TasButton::TRIGGER_ZR},
48};
49
50Tas::Tas(const std::string input_engine_) : InputCommon::InputEngine(input_engine_) {
51 for (size_t player_index = 0; player_index < PLAYER_NUMBER; player_index++) {
52 PadIdentifier identifier{
53 .guid = Common::UUID{},
54 .port = player_index,
55 .pad = 0,
56 };
57 PreSetController(identifier);
58 }
59 ClearInput();
60 if (!Settings::values.tas_enable) {
61 needs_reset = true;
62 return;
63 }
64 LoadTasFiles();
65}
66
67Tas::~Tas() {
68 Stop();
69};
70
71void Tas::LoadTasFiles() {
72 script_length = 0;
73 for (size_t i = 0; i < commands.size(); i++) {
74 LoadTasFile(i);
75 if (commands[i].size() > script_length) {
76 script_length = commands[i].size();
77 }
78 }
79}
80
81void Tas::LoadTasFile(size_t player_index) {
82 if (!commands[player_index].empty()) {
83 commands[player_index].clear();
84 }
85 std::string file =
86 Common::FS::ReadStringFromFile(Common::FS::GetYuzuPath(Common::FS::YuzuPath::TASDir) /
87 fmt::format("script0-{}.txt", player_index + 1),
88 Common::FS::FileType::BinaryFile);
89 std::stringstream command_line(file);
90 std::string line;
91 int frame_no = 0;
92 while (std::getline(command_line, line, '\n')) {
93 if (line.empty()) {
94 continue;
95 }
96 std::smatch m;
97
98 std::stringstream linestream(line);
99 std::string segment;
100 std::vector<std::string> seglist;
101
102 while (std::getline(linestream, segment, ' ')) {
103 seglist.push_back(segment);
104 }
105
106 if (seglist.size() < 4) {
107 continue;
108 }
109
110 while (frame_no < std::stoi(seglist.at(0))) {
111 commands[player_index].push_back({});
112 frame_no++;
113 }
114
115 TASCommand command = {
116 .buttons = ReadCommandButtons(seglist.at(1)),
117 .l_axis = ReadCommandAxis(seglist.at(2)),
118 .r_axis = ReadCommandAxis(seglist.at(3)),
119 };
120 commands[player_index].push_back(command);
121 frame_no++;
122 }
123 LOG_INFO(Input, "TAS file loaded! {} frames", frame_no);
124}
125
126void Tas::WriteTasFile(std::u8string file_name) {
127 std::string output_text;
128 for (size_t frame = 0; frame < record_commands.size(); frame++) {
129 const TASCommand& line = record_commands[frame];
130 output_text += fmt::format("{} {} {} {} {}\n", frame, WriteCommandButtons(line.buttons),
131 WriteCommandAxis(line.l_axis), WriteCommandAxis(line.r_axis));
132 }
133 const auto bytes_written = Common::FS::WriteStringToFile(
134 Common::FS::GetYuzuPath(Common::FS::YuzuPath::TASDir) / file_name,
135 Common::FS::FileType::TextFile, output_text);
136 if (bytes_written == output_text.size()) {
137 LOG_INFO(Input, "TAS file written to file!");
138 } else {
139 LOG_ERROR(Input, "Writing the TAS-file has failed! {} / {} bytes written", bytes_written,
140 output_text.size());
141 }
142}
143
144void Tas::RecordInput(u32 buttons, TasAnalog left_axis, TasAnalog right_axis) {
145 last_input = {
146 .buttons = buttons,
147 .l_axis = FlipAxisY(left_axis),
148 .r_axis = FlipAxisY(right_axis),
149 };
150}
151
152TasAnalog Tas::FlipAxisY(TasAnalog old) {
153 return {
154 .x = old.x,
155 .y = -old.y,
156 };
157}
158
159std::tuple<TasState, size_t, size_t> Tas::GetStatus() const {
160 TasState state;
161 if (is_recording) {
162 return {TasState::Recording, 0, record_commands.size()};
163 }
164
165 if (is_running) {
166 state = TasState::Running;
167 } else {
168 state = TasState::Stopped;
169 }
170
171 return {state, current_command, script_length};
172}
173
174void Tas::UpdateThread() {
175 if (!Settings::values.tas_enable) {
176 if (is_running) {
177 Stop();
178 }
179 return;
180 }
181
182 if (is_recording) {
183 record_commands.push_back(last_input);
184 }
185 if (needs_reset) {
186 current_command = 0;
187 needs_reset = false;
188 LoadTasFiles();
189 LOG_DEBUG(Input, "tas_reset done");
190 }
191
192 if (!is_running) {
193 ClearInput();
194 return;
195 }
196 if (current_command < script_length) {
197 LOG_DEBUG(Input, "Playing TAS {}/{}", current_command, script_length);
198 size_t frame = current_command++;
199 for (size_t player_index = 0; player_index < commands.size(); player_index++) {
200 TASCommand command{};
201 if (frame < commands[player_index].size()) {
202 command = commands[player_index][frame];
203 }
204
205 PadIdentifier identifier{
206 .guid = Common::UUID{},
207 .port = player_index,
208 .pad = 0,
209 };
210 for (std::size_t i = 0; i < sizeof(command.buttons); ++i) {
211 const bool button_status = (command.buttons & (1U << i)) != 0;
212 const int button = static_cast<int>(i);
213 SetButton(identifier, button, button_status);
214 }
215 SetAxis(identifier, TasAxes::StickX, command.l_axis.x);
216 SetAxis(identifier, TasAxes::StickY, command.l_axis.y);
217 SetAxis(identifier, TasAxes::SubstickX, command.r_axis.x);
218 SetAxis(identifier, TasAxes::SubstickY, command.r_axis.y);
219 }
220 } else {
221 is_running = Settings::values.tas_loop.GetValue();
222 current_command = 0;
223 ClearInput();
224 }
225}
226
227void Tas::ClearInput() {
228 ResetButtonState();
229 ResetAnalogState();
230}
231
232TasAnalog Tas::ReadCommandAxis(const std::string& line) const {
233 std::stringstream linestream(line);
234 std::string segment;
235 std::vector<std::string> seglist;
236
237 while (std::getline(linestream, segment, ';')) {
238 seglist.push_back(segment);
239 }
240
241 const float x = std::stof(seglist.at(0)) / 32767.0f;
242 const float y = std::stof(seglist.at(1)) / 32767.0f;
243
244 return {x, y};
245}
246
247u32 Tas::ReadCommandButtons(const std::string& data) const {
248 std::stringstream button_text(data);
249 std::string line;
250 u32 buttons = 0;
251 while (std::getline(button_text, line, ';')) {
252 for (auto [text, tas_button] : text_to_tas_button) {
253 if (text == line) {
254 buttons |= static_cast<u32>(tas_button);
255 break;
256 }
257 }
258 }
259 return buttons;
260}
261
262std::string Tas::WriteCommandButtons(u32 buttons) const {
263 std::string returns = "";
264 for (auto [text_button, tas_button] : text_to_tas_button) {
265 if ((buttons & static_cast<u32>(tas_button)) != 0)
266 returns += fmt::format("{};", text_button.substr(4));
267 }
268 return returns.empty() ? "NONE" : returns.substr(2);
269}
270
271std::string Tas::WriteCommandAxis(TasAnalog analog) const {
272 return fmt::format("{};{}", analog.x * 32767, analog.y * 32767);
273}
274
275void Tas::StartStop() {
276 if (!Settings::values.tas_enable) {
277 return;
278 }
279 if (is_running) {
280 Stop();
281 } else {
282 is_running = true;
283 }
284}
285
286void Tas::Stop() {
287 is_running = false;
288}
289
290void Tas::Reset() {
291 if (!Settings::values.tas_enable) {
292 return;
293 }
294 needs_reset = true;
295}
296
297bool Tas::Record() {
298 if (!Settings::values.tas_enable) {
299 return true;
300 }
301 is_recording = !is_recording;
302 return is_recording;
303}
304
305void Tas::SaveRecording(bool overwrite_file) {
306 if (is_recording) {
307 return;
308 }
309 if (record_commands.empty()) {
310 return;
311 }
312 WriteTasFile(u8"record.txt");
313 if (overwrite_file) {
314 WriteTasFile(u8"script0-1.txt");
315 }
316 needs_reset = true;
317 record_commands.clear();
318}
319
320} // namespace InputCommon::TasInput
diff --git a/src/input_common/drivers/tas_input.h b/src/input_common/drivers/tas_input.h
new file mode 100644
index 000000000..9fadc118b
--- /dev/null
+++ b/src/input_common/drivers/tas_input.h
@@ -0,0 +1,200 @@
1// Copyright 2020 yuzu Emulator Project
2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included.
4
5#pragma once
6
7#include <array>
8
9#include "common/common_types.h"
10#include "common/settings_input.h"
11#include "input_common/input_engine.h"
12#include "input_common/main.h"
13
14/*
15To play back TAS scripts on Yuzu, select the folder with scripts in the configuration menu below
16Tools -> Configure TAS. The file itself has normal text format and has to be called script0-1.txt
17for controller 1, script0-2.txt for controller 2 and so forth (with max. 8 players).
18
19A script file has the same format as TAS-nx uses, so final files will look like this:
20
211 KEY_B 0;0 0;0
226 KEY_ZL 0;0 0;0
2341 KEY_ZL;KEY_Y 0;0 0;0
2443 KEY_X;KEY_A 32767;0 0;0
2544 KEY_A 32767;0 0;0
2645 KEY_A 32767;0 0;0
2746 KEY_A 32767;0 0;0
2847 KEY_A 32767;0 0;0
29
30After placing the file at the correct location, it can be read into Yuzu with the (default) hotkey
31CTRL+F6 (refresh). In the bottom left corner, it will display the amount of frames the script file
32has. Playback can be started or stopped using CTRL+F5.
33
34However, for playback to actually work, the correct input device has to be selected: In the Controls
35menu, select TAS from the device list for the controller that the script should be played on.
36
37Recording a new script file is really simple: Just make sure that the proper device (not TAS) is
38connected on P1, and press CTRL+F7 to start recording. When done, just press the same keystroke
39again (CTRL+F7). The new script will be saved at the location previously selected, as the filename
40record.txt.
41
42For debugging purposes, the common controller debugger can be used (View -> Debugging -> Controller
43P1).
44*/
45
46namespace InputCommon::TasInput {
47
48constexpr size_t PLAYER_NUMBER = 10;
49
50enum class TasButton : u32 {
51 BUTTON_A = 1U << 0,
52 BUTTON_B = 1U << 1,
53 BUTTON_X = 1U << 2,
54 BUTTON_Y = 1U << 3,
55 STICK_L = 1U << 4,
56 STICK_R = 1U << 5,
57 TRIGGER_L = 1U << 6,
58 TRIGGER_R = 1U << 7,
59 TRIGGER_ZL = 1U << 8,
60 TRIGGER_ZR = 1U << 9,
61 BUTTON_PLUS = 1U << 10,
62 BUTTON_MINUS = 1U << 11,
63 BUTTON_LEFT = 1U << 12,
64 BUTTON_UP = 1U << 13,
65 BUTTON_RIGHT = 1U << 14,
66 BUTTON_DOWN = 1U << 15,
67 BUTTON_SL = 1U << 16,
68 BUTTON_SR = 1U << 17,
69 BUTTON_HOME = 1U << 18,
70 BUTTON_CAPTURE = 1U << 19,
71};
72
73struct TasAnalog {
74 float x{};
75 float y{};
76};
77
78enum class TasState {
79 Running,
80 Recording,
81 Stopped,
82};
83
84class Tas final : public InputCommon::InputEngine {
85public:
86 explicit Tas(const std::string input_engine_);
87 ~Tas();
88
89 /**
90 * Changes the input status that will be stored in each frame
91 * @param buttons: bitfield with the status of the buttons
92 * @param left_axis: value of the left axis
93 * @param right_axis: value of the right axis
94 */
95 void RecordInput(u32 buttons, TasAnalog left_axis, TasAnalog right_axis);
96
97 // Main loop that records or executes input
98 void UpdateThread();
99
100 // Sets the flag to start or stop the TAS command excecution and swaps controllers profiles
101 void StartStop();
102
103 // Stop the TAS and reverts any controller profile
104 void Stop();
105
106 // Sets the flag to reload the file and start from the begining in the next update
107 void Reset();
108
109 /**
110 * Sets the flag to enable or disable recording of inputs
111 * @return Returns true if the current recording status is enabled
112 */
113 bool Record();
114
115 /**
116 * Saves contents of record_commands on a file
117 * @param overwrite_file: Indicates if player 1 should be overwritten
118 */
119 void SaveRecording(bool overwrite_file);
120
121 /**
122 * Returns the current status values of TAS playback/recording
123 * @return Tuple of
124 * TasState indicating the current state out of Running ;
125 * Current playback progress ;
126 * Total length of script file currently loaded or being recorded
127 */
128 std::tuple<TasState, size_t, size_t> GetStatus() const;
129
130private:
131 struct TASCommand {
132 u32 buttons{};
133 TasAnalog l_axis{};
134 TasAnalog r_axis{};
135 };
136
137 /// Loads TAS files from all players
138 void LoadTasFiles();
139
140 /** Loads TAS file from the specified player
141 * @param player_index: player number where data is going to be stored
142 */
143 void LoadTasFile(size_t player_index);
144
145 /** Writes a TAS file from the recorded commands
146 * @param file_name: name of the file to be written
147 */
148 void WriteTasFile(std::u8string file_name);
149
150 /** Inverts the Y axis polarity
151 * @param old: value of the axis
152 * @return new value of the axis
153 */
154 TasAnalog FlipAxisY(TasAnalog old);
155
156 /**
157 * Parses a string containing the axis values. X and Y have a range from -32767 to 32767
158 * @param line: string containing axis values with the following format "x;y"
159 * @return Returns a TAS analog object with axis values with range from -1.0 to 1.0
160 */
161 TasAnalog ReadCommandAxis(const std::string& line) const;
162
163 /**
164 * Parses a string containing the button values. Each button is represented by it's text format
165 * specified in text_to_tas_button array
166 * @param line: string containing button name with the following format "a;b;c;d..."
167 * @return Returns a u32 with each bit representing the status of a button
168 */
169 u32 ReadCommandButtons(const std::string& line) const;
170
171 /**
172 * Reset state of all players
173 */
174 void ClearInput();
175
176 /**
177 * Converts an u32 containing the button status into the text equivalent
178 * @param buttons: bitfield with the status of the buttons
179 * @return Returns a string with the name of the buttons to be written to the file
180 */
181 std::string WriteCommandButtons(u32 buttons) const;
182
183 /**
184 * Converts an TAS analog object containing the axis status into the text equivalent
185 * @param data: value of the axis
186 * @return A string with the value of the axis to be written to the file
187 */
188 std::string WriteCommandAxis(TasAnalog data) const;
189
190 size_t script_length{0};
191 bool is_old_input_saved{false};
192 bool is_recording{false};
193 bool is_running{false};
194 bool needs_reset{false};
195 std::array<std::vector<TASCommand>, PLAYER_NUMBER> commands{};
196 std::vector<TASCommand> record_commands{};
197 size_t current_command{0};
198 TASCommand last_input{}; // only used for recording
199};
200} // namespace InputCommon::TasInput