code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <thread>
#include <fmt/format.h>
#include <math.h>

#include "common/param_package.h"
#include "common/settings.h"
#include "common/thread.h"
#include "input_common/drivers/mouse.h"

namespace InputCommon {
constexpr int update_time = 10;
constexpr float default_panning_sensitivity = 0.0010f;
constexpr float default_stick_sensitivity = 0.0006f;
constexpr float default_deadzone_counterweight = 0.01f;
constexpr float default_motion_panning_sensitivity = 2.5f;
constexpr float default_motion_sensitivity = 0.416f;
constexpr float maximum_rotation_speed = 2.0f;
constexpr float maximum_stick_range = 1.5f;
constexpr int mouse_axis_x = 0;
constexpr int mouse_axis_y = 1;
constexpr int wheel_axis_x = 2;
constexpr int wheel_axis_y = 3;
constexpr PadIdentifier identifier = {
    .guid = Common::UUID{},
    .port = 0,
    .pad = 0,
};

constexpr PadIdentifier motion_identifier = {
    .guid = Common::UUID{},
    .port = 0,
    .pad = 1,
};

constexpr PadIdentifier real_mouse_identifier = {
    .guid = Common::UUID{},
    .port = 1,
    .pad = 0,
};

constexpr PadIdentifier touch_identifier = {
    .guid = Common::UUID{},
    .port = 2,
    .pad = 0,
};

Mouse::Mouse(std::string input_engine_) : InputEngine(std::move(input_engine_)) {
    PreSetController(identifier);
    PreSetController(real_mouse_identifier);
    PreSetController(touch_identifier);
    PreSetController(motion_identifier);

    // Initialize all mouse axis
    PreSetAxis(identifier, mouse_axis_x);
    PreSetAxis(identifier, mouse_axis_y);
    PreSetAxis(identifier, wheel_axis_x);
    PreSetAxis(identifier, wheel_axis_y);
    PreSetAxis(real_mouse_identifier, mouse_axis_x);
    PreSetAxis(real_mouse_identifier, mouse_axis_y);
    PreSetAxis(touch_identifier, mouse_axis_x);
    PreSetAxis(touch_identifier, mouse_axis_y);

    // Initialize variables
    mouse_origin = {};
    last_mouse_position = {};
    wheel_position = {};
    last_mouse_change = {};
    last_motion_change = {};

    update_thread = std::jthread([this](std::stop_token stop_token) { UpdateThread(stop_token); });
}

void Mouse::UpdateThread(std::stop_token stop_token) {
    Common::SetCurrentThreadName("Mouse");

    while (!stop_token.stop_requested()) {
        UpdateStickInput();
        UpdateMotionInput();

        std::this_thread::sleep_for(std::chrono::milliseconds(update_time));
    }
}

void Mouse::UpdateStickInput() {
    if (!IsMousePanningEnabled()) {
        return;
    }

    const float length = last_mouse_change.Length();

    // Prevent input from exceeding the max range (1.0f) too much,
    // but allow some room to make it easier to sustain
    if (length > maximum_stick_range) {
        last_mouse_change /= length;
        last_mouse_change *= maximum_stick_range;
    }

    SetAxis(identifier, mouse_axis_x, last_mouse_change.x);
    SetAxis(identifier, mouse_axis_y, -last_mouse_change.y);

    // Decay input over time
    const float clamped_length = std::min(1.0f, length);
    const float decay_strength = Settings::values.mouse_panning_decay_strength.GetValue();
    const float decay = 1 - clamped_length * clamped_length * decay_strength * 0.01f;
    const float min_decay = Settings::values.mouse_panning_min_decay.GetValue();
    const float clamped_decay = std::min(1 - min_decay / 100.0f, decay);
    last_mouse_change *= clamped_decay;
}

void Mouse::UpdateMotionInput() {
    const float sensitivity =
        IsMousePanningEnabled() ? default_motion_panning_sensitivity : default_motion_sensitivity;

    const float rotation_velocity = std::sqrt(last_motion_change.x * last_motion_change.x +
                                              last_motion_change.y * last_motion_change.y);

    // Clamp rotation speed
    if (rotation_velocity > maximum_rotation_speed / sensitivity) {
        const float multiplier = maximum_rotation_speed / rotation_velocity / sensitivity;
        last_motion_change.x = last_motion_change.x * multiplier;
        last_motion_change.y = last_motion_change.y * multiplier;
    }

    const BasicMotion motion_data{
        .gyro_x = last_motion_change.x * sensitivity,
        .gyro_y = last_motion_change.y * sensitivity,
        .gyro_z = last_motion_change.z * sensitivity,
        .accel_x = 0,
        .accel_y = 0,
        .accel_z = 0,
        .delta_timestamp = update_time * 1000,
    };

    if (IsMousePanningEnabled()) {
        last_motion_change.x = 0;
        last_motion_change.y = 0;
    }
    last_motion_change.z = 0;

    SetMotion(motion_identifier, 0, motion_data);
}

void Mouse::Move(int x, int y, int center_x, int center_y) {
    if (IsMousePanningEnabled()) {
        const auto mouse_change =
            (Common::MakeVec(x, y) - Common::MakeVec(center_x, center_y)).Cast<float>();
        const float x_sensitivity =
            Settings::values.mouse_panning_x_sensitivity.GetValue() * default_panning_sensitivity;
        const float y_sensitivity =
            Settings::values.mouse_panning_y_sensitivity.GetValue() * default_panning_sensitivity;
        const float deadzone_counterweight =
            Settings::values.mouse_panning_deadzone_counterweight.GetValue() *
            default_deadzone_counterweight;

        last_motion_change += {-mouse_change.y * x_sensitivity, -mouse_change.x * y_sensitivity, 0};
        last_mouse_change.x += mouse_change.x * x_sensitivity;
        last_mouse_change.y += mouse_change.y * y_sensitivity;

        // Bind the mouse change to [0 <= deadzone_counterweight <= 1.0]
        const float length = last_mouse_change.Length();
        if (length < deadzone_counterweight && length != 0.0f) {
            last_mouse_change /= length;
            last_mouse_change *= deadzone_counterweight;
        }

        return;
    }

    if (button_pressed) {
        const auto mouse_move = Common::MakeVec<int>(x, y) - mouse_origin;
        const float x_sensitivity =
            Settings::values.mouse_panning_x_sensitivity.GetValue() * default_stick_sensitivity;
        const float y_sensitivity =
            Settings::values.mouse_panning_y_sensitivity.GetValue() * default_stick_sensitivity;
        SetAxis(identifier, mouse_axis_x, static_cast<float>(mouse_move.x) * x_sensitivity);
        SetAxis(identifier, mouse_axis_y, static_cast<float>(-mouse_move.y) * y_sensitivity);

        last_motion_change = {
            static_cast<float>(-mouse_move.y) * x_sensitivity,
            static_cast<float>(-mouse_move.x) * y_sensitivity,
            last_motion_change.z,
        };
    }
}

void Mouse::MouseMove(f32 touch_x, f32 touch_y) {
    SetAxis(real_mouse_identifier, mouse_axis_x, touch_x);
    SetAxis(real_mouse_identifier, mouse_axis_y, touch_y);
}

void Mouse::TouchMove(f32 touch_x, f32 touch_y) {
    SetAxis(touch_identifier, mouse_axis_x, touch_x);
    SetAxis(touch_identifier, mouse_axis_y, touch_y);
}

void Mouse::PressButton(int x, int y, MouseButton button) {
    SetButton(identifier, static_cast<int>(button), true);

    // Set initial analog parameters
    mouse_origin = {x, y};
    last_mouse_position = {x, y};
    button_pressed = true;
}

void Mouse::PressMouseButton(MouseButton button) {
    SetButton(real_mouse_identifier, static_cast<int>(button), true);
}

void Mouse::PressTouchButton(f32 touch_x, f32 touch_y, MouseButton button) {
    SetAxis(touch_identifier, mouse_axis_x, touch_x);
    SetAxis(touch_identifier, mouse_axis_y, touch_y);
    SetButton(touch_identifier, static_cast<int>(button), true);
}

void Mouse::ReleaseButton(MouseButton button) {
    SetButton(identifier, static_cast<int>(button), false);
    SetButton(real_mouse_identifier, static_cast<int>(button), false);
    SetButton(touch_identifier, static_cast<int>(button), false);

    if (!IsMousePanningEnabled()) {
        SetAxis(identifier, mouse_axis_x, 0);
        SetAxis(identifier, mouse_axis_y, 0);
    }

    last_motion_change.x = 0;
    last_motion_change.y = 0;

    button_pressed = false;
}

void Mouse::MouseWheelChange(int x, int y) {
    wheel_position.x += x;
    wheel_position.y += y;
    last_motion_change.z += static_cast<f32>(y);
    SetAxis(identifier, wheel_axis_x, static_cast<f32>(wheel_position.x));
    SetAxis(identifier, wheel_axis_y, static_cast<f32>(wheel_position.y));
}

void Mouse::ReleaseAllButtons() {
    ResetButtonState();
    button_pressed = false;
}

bool Mouse::IsMousePanningEnabled() {
    // Disable mouse panning when a real mouse is connected
    return Settings::values.mouse_panning && !Settings::values.mouse_enabled;
}

std::vector<Common::ParamPackage> Mouse::GetInputDevices() const {
    std::vector<Common::ParamPackage> devices;
    devices.emplace_back(Common::ParamPackage{
        {"engine", GetEngineName()},
        {"display", "Keyboard/Mouse"},
    });
    return devices;
}

AnalogMapping Mouse::GetAnalogMappingForDevice(
    [[maybe_unused]] const Common::ParamPackage& params) {
    // Only overwrite different buttons from default
    AnalogMapping mapping = {};
    Common::ParamPackage right_analog_params;
    right_analog_params.Set("engine", GetEngineName());
    right_analog_params.Set("axis_x", 0);
    right_analog_params.Set("axis_y", 1);
    right_analog_params.Set("threshold", 0.5f);
    right_analog_params.Set("range", 1.0f);
    right_analog_params.Set("deadzone", 0.0f);
    mapping.insert_or_assign(Settings::NativeAnalog::RStick, std::move(right_analog_params));
    return mapping;
}

Common::Input::ButtonNames Mouse::GetUIButtonName(const Common::ParamPackage& params) const {
    const auto button = static_cast<MouseButton>(params.Get("button", 0));
    switch (button) {
    case MouseButton::Left:
        return Common::Input::ButtonNames::ButtonLeft;
    case MouseButton::Right:
        return Common::Input::ButtonNames::ButtonRight;
    case MouseButton::Wheel:
        return Common::Input::ButtonNames::ButtonMouseWheel;
    case MouseButton::Backward:
        return Common::Input::ButtonNames::ButtonBackward;
    case MouseButton::Forward:
        return Common::Input::ButtonNames::ButtonForward;
    case MouseButton::Task:
        return Common::Input::ButtonNames::ButtonTask;
    case MouseButton::Extra:
        return Common::Input::ButtonNames::ButtonExtra;
    case MouseButton::Undefined:
    default:
        return Common::Input::ButtonNames::Undefined;
    }
}

Common::Input::ButtonNames Mouse::GetUIName(const Common::ParamPackage& params) const {
    if (params.Has("button")) {
        return GetUIButtonName(params);
    }
    if (params.Has("axis")) {
        return Common::Input::ButtonNames::Value;
    }
    if (params.Has("axis_x") && params.Has("axis_y") && params.Has("axis_z")) {
        return Common::Input::ButtonNames::Engine;
    }
    if (params.Has("motion")) {
        return Common::Input::ButtonNames::Engine;
    }

    return Common::Input::ButtonNames::Invalid;
}

} // namespace InputCommon


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <thread>

#include "common/polyfill_thread.h"
#include "common/vector_math.h"
#include "input_common/input_engine.h"

namespace InputCommon {

enum class MouseButton {
    Left,
    Right,
    Wheel,
    Backward,
    Forward,
    Task,
    Extra,
    Undefined,
};

/**
 * A button device factory representing a keyboard. It receives keyboard events and forward them
 * to all button devices it created.
 */
class Mouse final : public InputEngine {
public:
    explicit Mouse(std::string input_engine_);

    /**
     * Signals that mouse has moved.
     * @param x the x-coordinate of the cursor
     * @param y the y-coordinate of the cursor
     * @param center_x the x-coordinate of the middle of the screen
     * @param center_y the y-coordinate of the middle of the screen
     */
    void Move(int x, int y, int center_x, int center_y);

    /**
     * Signals that real mouse has moved.
     * @param x the absolute position on the touchscreen of the cursor
     * @param y the absolute position on the touchscreen of the cursor
     */
    void MouseMove(f32 touch_x, f32 touch_y);

    /**
     * Signals that touch finger has moved.
     * @param x the absolute position on the touchscreen of the cursor
     * @param y the absolute position on the touchscreen of the cursor
     */
    void TouchMove(f32 touch_x, f32 touch_y);

    /**
     * Sets the status of a button to pressed
     * @param x the x-coordinate of the cursor
     * @param y the y-coordinate of the cursor
     * @param button the id of the button to press
     */
    void PressButton(int x, int y, MouseButton button);

    /**
     * Sets the status of a mouse button to pressed
     * @param button the id of the button to press
     */
    void PressMouseButton(MouseButton button);

    /**
     * Sets the status of touch finger to pressed
     * @param x the absolute position on the touchscreen of the cursor
     * @param y the absolute position on the touchscreen of the cursor
     * @param button the id of the button to press
     */
    void PressTouchButton(f32 touch_x, f32 touch_y, MouseButton button);

    /**
     * Sets the status of all buttons bound with the key to released
     * @param key_code the code of the key to release
     */
    void ReleaseButton(MouseButton button);

    /**
     * Sets the status of the mouse wheel
     * @param x delta movement in the x direction
     * @param y delta movement in the y direction
     */
    void MouseWheelChange(int x, int y);

    void ReleaseAllButtons();

    std::vector<Common::ParamPackage> GetInputDevices() const override;
    AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) override;
    Common::Input::ButtonNames GetUIName(const Common::ParamPackage& params) const override;

private:
    void UpdateThread(std::stop_token stop_token);
    void UpdateStickInput();
    void UpdateMotionInput();

    bool IsMousePanningEnabled();

    Common::Input::ButtonNames GetUIButtonName(const Common::ParamPackage& params) const;

    Common::Vec2<int> mouse_origin;
    Common::Vec2<int> last_mouse_position;
    Common::Vec2<float> last_mouse_change;
    Common::Vec3<float> last_motion_change;
    Common::Vec2<int> wheel_position;
    bool button_pressed;
    std::jthread update_thread;
};

} // namespace InputCommon

repo_name: litucks/torzu

license: mit


code:
// SPDX-FileCopyrightText: 2018 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/logging/log.h"
#include "common/math_util.h"
#include "common/param_package.h"
#include "common/settings.h"
#include "common/thread.h"
#include "common/vector_math.h"
#include "input_common/drivers/sdl_driver.h"

namespace InputCommon {

namespace {
Common::UUID GetGUID(SDL_Joystick* joystick) {
    const SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
    std::array<u8, 16> data{};
    std::memcpy(data.data(), guid.data, sizeof(data));
    // Clear controller name crc
    std::memset(data.data() + 2, 0, sizeof(u16));
    return Common::UUID{data};
}
} // Anonymous namespace

static int SDLEventWatcher(void* user_data, SDL_Event* event) {
    auto* const sdl_state = static_cast<SDLDriver*>(user_data);

    sdl_state->HandleGameControllerEvent(*event);

    return 0;
}

class SDLJoystick {
public:
    SDLJoystick(Common::UUID guid_, int port_, SDL_Joystick* joystick,
                SDL_GameController* game_controller)
        : guid{guid_}, port{port_}, sdl_joystick{joystick, &SDL_JoystickClose},
          sdl_controller{game_controller, &SDL_GameControllerClose} {
        EnableMotion();
    }

    void EnableMotion() {
        if (!sdl_controller) {
            return;
        }
        SDL_GameController* controller = sdl_controller.get();
        if (HasMotion()) {
            SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_ACCEL, SDL_FALSE);
            SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_GYRO, SDL_FALSE);
        }
        has_accel = SDL_GameControllerHasSensor(controller, SDL_SENSOR_ACCEL) == SDL_TRUE;
        has_gyro = SDL_GameControllerHasSensor(controller, SDL_SENSOR_GYRO) == SDL_TRUE;
        if (has_accel) {
            SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_ACCEL, SDL_TRUE);
        }
        if (has_gyro) {
            SDL_GameControllerSetSensorEnabled(controller, SDL_SENSOR_GYRO, SDL_TRUE);
        }
    }

    bool HasMotion() const {
        return has_gyro || has_accel;
    }

    bool UpdateMotion(SDL_ControllerSensorEvent event) {
        constexpr float gravity_constant = 9.80665f;
        std::scoped_lock lock{mutex};
        const u64 time_difference = event.timestamp - last_motion_update;
        last_motion_update = event.timestamp;
        switch (event.sensor) {
        case SDL_SENSOR_ACCEL: {
            motion.accel_x = -event.data[0] / gravity_constant;
            motion.accel_y = event.data[2] / gravity_constant;
            motion.accel_z = -event.data[1] / gravity_constant;
            break;
        }
        case SDL_SENSOR_GYRO: {
            motion.gyro_x = event.data[0] / (Common::PI * 2);
            motion.gyro_y = -event.data[2] / (Common::PI * 2);
            motion.gyro_z = event.data[1] / (Common::PI * 2);
            break;
        }
        }

        // Ignore duplicated timestamps
        if (time_difference == 0) {
            return false;
        }

        // Motion data is invalid
        if (motion.accel_x == 0 && motion.gyro_x == 0 && motion.accel_y == 0 &&
            motion.gyro_y == 0 && motion.accel_z == 0 && motion.gyro_z == 0) {
            if (motion_error_count++ < 200) {
                return false;
            }
            // Try restarting the sensor
            motion_error_count = 0;
            EnableMotion();
            return false;
        }

        motion_error_count = 0;
        motion.delta_timestamp = time_difference * 1000;
        return true;
    }

    const BasicMotion& GetMotion() const {
        return motion;
    }

    bool RumblePlay(const Common::Input::VibrationStatus vibration) {
        constexpr u32 rumble_max_duration_ms = 2000;
        constexpr f32 low_start_sensitivity_limit = 140.0;
        constexpr f32 low_width_sensitivity_limit = 400.0;
        constexpr f32 high_start_sensitivity_limit = 200.0;
        constexpr f32 high_width_sensitivity_limit = 700.0;
        // Try to provide some feeling of the frequency by reducing the amplitude depending on it.
        f32 low_frequency_scale = 1.0;
        if (vibration.low_frequency > low_start_sensitivity_limit) {
            low_frequency_scale =
                std::max(1.0f - (vibration.low_frequency - low_start_sensitivity_limit) /
                                    low_width_sensitivity_limit,
                         0.3f);
        }
        f32 low_amplitude = vibration.low_amplitude * low_frequency_scale;

        f32 high_frequency_scale = 1.0;
        if (vibration.high_frequency > high_start_sensitivity_limit) {
            high_frequency_scale =
                std::max(1.0f - (vibration.high_frequency - high_start_sensitivity_limit) /
                                    high_width_sensitivity_limit,
                         0.3f);
        }
        f32 high_amplitude = vibration.high_amplitude * high_frequency_scale;

        if (sdl_controller) {
            return SDL_GameControllerRumble(sdl_controller.get(), static_cast<u16>(low_amplitude),
                                            static_cast<u16>(high_amplitude),
                                            rumble_max_duration_ms) != -1;
        } else if (sdl_joystick) {
            return SDL_JoystickRumble(sdl_joystick.get(), static_cast<u16>(low_amplitude),
                                      static_cast<u16>(high_amplitude),
                                      rumble_max_duration_ms) != -1;
        }

        return false;
    }

    bool HasHDRumble() const {
        if (sdl_controller) {
            const auto type = SDL_GameControllerGetType(sdl_controller.get());
            return (type == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO) ||
                   (type == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_LEFT) ||
                   (type == SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT) ||
                   (type == SDL_CONTROLLER_TYPE_PS5);
        }
        return false;
    }

    void EnableVibration(bool is_enabled) {
        has_vibration = is_enabled;
        is_vibration_tested = true;
    }

    bool HasVibration() const {
        return has_vibration;
    }

    bool IsVibrationTested() const {
        return is_vibration_tested;
    }

    /**
     * The Pad identifier of the joystick
     */
    const PadIdentifier GetPadIdentifier() const {
        return {
            .guid = guid,
            .port = static_cast<std::size_t>(port),
            .pad = 0,
        };
    }

    /**
     * The guid of the joystick
     */
    const Common::UUID& GetGUID() const {
        return guid;
    }

    /**
     * The number of joystick from the same type that were connected before this joystick
     */
    int GetPort() const {
        return port;
    }

    SDL_Joystick* GetSDLJoystick() const {
        return sdl_joystick.get();
    }

    SDL_GameController* GetSDLGameController() const {
        return sdl_controller.get();
    }

    void SetSDLJoystick(SDL_Joystick* joystick, SDL_GameController* controller) {
        sdl_joystick.reset(joystick);
        sdl_controller.reset(controller);
    }

    bool IsJoyconLeft() const {
        const std::string controller_name = GetControllerName();
        if (std::strstr(controller_name.c_str(), "Joy-Con Left") != nullptr) {
            return true;
        }
        if (std::strstr(controller_name.c_str(), "Joy-Con (L)") != nullptr) {
            return true;
        }
        return false;
    }

    bool IsJoyconRight() const {
        const std::string controller_name = GetControllerName();
        if (std::strstr(controller_name.c_str(), "Joy-Con Right") != nullptr) {
            return true;
        }
        if (std::strstr(controller_name.c_str(), "Joy-Con (R)") != nullptr) {
            return true;
        }
        return false;
    }

    Common::Input::BatteryLevel GetBatteryLevel(SDL_JoystickPowerLevel battery_level) {
        switch (battery_level) {
        case SDL_JOYSTICK_POWER_EMPTY:
            return Common::Input::BatteryLevel::Empty;
        case SDL_JOYSTICK_POWER_LOW:
            return Common::Input::BatteryLevel::Low;
        case SDL_JOYSTICK_POWER_MEDIUM:
            return Common::Input::BatteryLevel::Medium;
        case SDL_JOYSTICK_POWER_FULL:
        case SDL_JOYSTICK_POWER_MAX:
            return Common::Input::BatteryLevel::Full;
        case SDL_JOYSTICK_POWER_WIRED:
            return Common::Input::BatteryLevel::Charging;
        case SDL_JOYSTICK_POWER_UNKNOWN:
        default:
            return Common::Input::BatteryLevel::None;
        }
    }

    std::string GetControllerName() const {
        if (sdl_controller) {
            switch (SDL_GameControllerGetType(sdl_controller.get())) {
            case SDL_CONTROLLER_TYPE_XBOX360:
                return "Xbox 360 Controller";
            case SDL_CONTROLLER_TYPE_XBOXONE:
                return "Xbox One Controller";
            case SDL_CONTROLLER_TYPE_PS3:
                return "DualShock 3 Controller";
            case SDL_CONTROLLER_TYPE_PS4:
                return "DualShock 4 Controller";
            case SDL_CONTROLLER_TYPE_PS5:
                return "DualSense Controller";
            default:
                break;
            }
            const auto name = SDL_GameControllerName(sdl_controller.get());
            if (name) {
                return name;
            }
        }

        if (sdl_joystick) {
            const auto name = SDL_JoystickName(sdl_joystick.get());
            if (name) {
                return name;
            }
        }

        return "Unknown";
    }

private:
    Common::UUID guid;
    int port;
    std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick;
    std::unique_ptr<SDL_GameController, decltype(&SDL_GameControllerClose)> sdl_controller;
    mutable std::mutex mutex;

    u64 last_motion_update{};
    std::size_t motion_error_count{};
    bool has_gyro{false};
    bool has_accel{false};
    bool has_vibration{false};
    bool is_vibration_tested{false};
    BasicMotion motion;
};

std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickByGUID(const Common::UUID& guid, int port) {
    std::scoped_lock lock{joystick_map_mutex};
    const auto it = joystick_map.find(guid);

    if (it != joystick_map.end()) {
        while (it->second.size() <= static_cast<std::size_t>(port)) {
            auto joystick = std::make_shared<SDLJoystick>(guid, static_cast<int>(it->second.size()),
                                                          nullptr, nullptr);
            it->second.emplace_back(std::move(joystick));
        }

        return it->second[static_cast<std::size_t>(port)];
    }

    auto joystick = std::make_shared<SDLJoystick>(guid, 0, nullptr, nullptr);

    return joystick_map[guid].emplace_back(std::move(joystick));
}

std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickByGUID(const std::string& guid, int port) {
    return GetSDLJoystickByGUID(Common::UUID{guid}, port);
}

std::shared_ptr<SDLJoystick> SDLDriver::GetSDLJoystickBySDLID(SDL_JoystickID sdl_id) {
    auto sdl_joystick = SDL_JoystickFromInstanceID(sdl_id);
    const auto guid = GetGUID(sdl_joystick);

    std::scoped_lock lock{joystick_map_mutex};
    const auto map_it = joystick_map.find(guid);

    if (map_it == joystick_map.end()) {
        return nullptr;
    }

    const auto vec_it = std::find_if(map_it->second.begin(), map_it->second.end(),
                                     [&sdl_joystick](const auto& joystick) {
                                         return joystick->GetSDLJoystick() == sdl_joystick;
                                     });

    if (vec_it == map_it->second.end()) {
        return nullptr;
    }

    return *vec_it;
}

void SDLDriver::InitJoystick(int joystick_index) {
    SDL_Joystick* sdl_joystick = SDL_JoystickOpen(joystick_index);
    SDL_GameController* sdl_gamecontroller = nullptr;

    if (SDL_IsGameController(joystick_index)) {
        sdl_gamecontroller = SDL_GameControllerOpen(joystick_index);
    }

    if (!sdl_joystick) {
        LOG_ERROR(Input, "Failed to open joystick {}", joystick_index);
        return;
    }

    const auto guid = GetGUID(sdl_joystick);

    if (Settings::values.enable_joycon_driver) {
        if (guid.uuid[5] == 0x05 && guid.uuid[4] == 0x7e &&
            (guid.uuid[8] == 0x06 || guid.uuid[8] == 0x07)) {
            LOG_WARNING(Input, "Preferring joycon driver for device index {}", joystick_index);
            SDL_JoystickClose(sdl_joystick);
            return;
        }
    }

    if (Settings::values.enable_procon_driver) {
        if (guid.uuid[5] == 0x05 && guid.uuid[4] == 0x7e && guid.uuid[8] == 0x09) {
            LOG_WARNING(Input, "Preferring joycon driver for device index {}", joystick_index);
            SDL_JoystickClose(sdl_joystick);
            return;
        }
    }

    std::scoped_lock lock{joystick_map_mutex};
    if (joystick_map.find(guid) == joystick_map.end()) {
        auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick, sdl_gamecontroller);
        PreSetController(joystick->GetPadIdentifier());
        joystick->EnableMotion();
        joystick_map[guid].emplace_back(std::move(joystick));
        return;
    }

    auto& joystick_guid_list = joystick_map[guid];
    const auto joystick_it =
        std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
                     [](const auto& joystick) { return !joystick->GetSDLJoystick(); });

    if (joystick_it != joystick_guid_list.end()) {
        (*joystick_it)->SetSDLJoystick(sdl_joystick, sdl_gamecontroller);
        (*joystick_it)->EnableMotion();
        return;
    }

    const int port = static_cast<int>(joystick_guid_list.size());
    auto joystick = std::make_shared<SDLJoystick>(guid, port, sdl_joystick, sdl_gamecontroller);
    PreSetController(joystick->GetPadIdentifier());
    joystick->EnableMotion();
    joystick_guid_list.emplace_back(std::move(joystick));
}

void SDLDriver::CloseJoystick(SDL_Joystick* sdl_joystick) {
    const auto guid = GetGUID(sdl_joystick);

    std::scoped_lock lock{joystick_map_mutex};
    // This call to guid is safe since the joystick is guaranteed to be in the map
    const auto& joystick_guid_list = joystick_map[guid];
    const auto joystick_it = std::find_if(joystick_guid_list.begin(), joystick_guid_list.end(),
                                          [&sdl_joystick](const auto& joystick) {
                                              return joystick->GetSDLJoystick() == sdl_joystick;
                                          });

    if (joystick_it != joystick_guid_list.end()) {
        (*joystick_it)->SetSDLJoystick(nullptr, nullptr);
    }
}

void SDLDriver::PumpEvents() const {
    if (initialized) {
        SDL_PumpEvents();
    }
}

void SDLDriver::HandleGameControllerEvent(const SDL_Event& event) {
    switch (event.type) {
    case SDL_JOYBUTTONUP: {
        if (const auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
            const PadIdentifier identifier = joystick->GetPadIdentifier();
            SetButton(identifier, event.jbutton.button, false);
        }
        break;
    }
    case SDL_JOYBUTTONDOWN: {
        if (const auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
            const PadIdentifier identifier = joystick->GetPadIdentifier();
            SetButton(identifier, event.jbutton.button, true);
        }
        break;
    }
    case SDL_JOYHATMOTION: {
        if (const auto joystick = GetSDLJoystickBySDLID(event.jhat.which)) {
            const PadIdentifier identifier = joystick->GetPadIdentifier();
            SetHatButton(identifier, event.jhat.hat, event.jhat.value);
        }
        break;
    }
    case SDL_JOYAXISMOTION: {
        if (const auto joystick = GetSDLJoystickBySDLID(event.jaxis.which)) {
            const PadIdentifier identifier = joystick->GetPadIdentifier();
            SetAxis(identifier, event.jaxis.axis, event.jaxis.value / 32767.0f);
        }
        break;
    }
    case SDL_CONTROLLERSENSORUPDATE: {
        if (auto joystick = GetSDLJoystickBySDLID(event.csensor.which)) {
            if (joystick->UpdateMotion(event.csensor)) {
                const PadIdentifier identifier = joystick->GetPadIdentifier();
                SetMotion(identifier, 0, joystick->GetMotion());
            }
        }
        break;
    }
    case SDL_JOYBATTERYUPDATED: {
        if (auto joystick = GetSDLJoystickBySDLID(event.jbattery.which)) {
            const PadIdentifier identifier = joystick->GetPadIdentifier();
            SetBattery(identifier, joystick->GetBatteryLevel(event.jbattery.level));
        }
        break;
    }
    case SDL_JOYDEVICEREMOVED:
        LOG_DEBUG(Input, "Controller removed with Instance_ID {}", event.jdevice.which);
        CloseJoystick(SDL_JoystickFromInstanceID(event.jdevice.which));
        break;
    case SDL_JOYDEVICEADDED:
        LOG_DEBUG(Input, "Controller connected with device index {}", event.jdevice.which);
        InitJoystick(event.jdevice.which);
        break;
    }
}

void SDLDriver::CloseJoysticks() {
    std::scoped_lock lock{joystick_map_mutex};
    joystick_map.clear();
}

SDLDriver::SDLDriver(std::string input_engine_) : InputEngine(std::move(input_engine_)) {
    // Set our application name. Currently passed to DBus by SDL and visible to the user through
    // their desktop environment.
    SDL_SetHint(SDL_HINT_APP_NAME, "yuzu");

    if (!Settings::values.enable_raw_input) {
        // Disable raw input. When enabled this setting causes SDL to die when a web applet opens
        SDL_SetHint(SDL_HINT_JOYSTICK_RAWINPUT, "0");
    }

    // Prevent SDL from adding undesired axis
    SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");

    // Enable HIDAPI rumble. This prevents SDL from disabling motion on PS4 and PS5 controllers
    SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE, "1");
    SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE, "1");
    SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");

    // Disable hidapi drivers for joycon controllers when the custom joycon driver is enabled
    if (Settings::values.enable_joycon_driver) {
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, "0");
    } else {
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, "1");
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED, "0");
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_COMBINE_JOY_CONS, "0");
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS, "1");
    }

    // Disable hidapi drivers for pro controllers when the custom joycon driver is enabled
    if (Settings::values.enable_procon_driver) {
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, "0");
    } else {
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, "1");
        SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED, "0");
    }

    SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED, "1");
    // Share the same button mapping with non-Nintendo controllers
    SDL_SetHint(SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS, "0");

    // Disable hidapi driver for xbox. Already default on Windows, this causes conflict with native
    // driver on Linux.
    SDL_SetHint(SDL_HINT_JOYSTICK_HIDAPI_XBOX, "0");

    // If the frontend is going to manage the event loop, then we don't start one here
    start_thread = SDL_WasInit(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) == 0;
    if (start_thread && SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
        LOG_CRITICAL(Input, "SDL_Init failed with: {}", SDL_GetError());
        return;
    }

    SDL_AddEventWatch(&SDLEventWatcher, this);

    initialized = true;
    if (start_thread) {
        vibration_thread = std::thread([this] {
            Common::SetCurrentThreadName("SDL_Vibration");
            using namespace std::chrono_literals;
            while (initialized) {
                SendVibrations();
                std::this_thread::sleep_for(10ms);
            }
        });
    }
    // Because the events for joystick connection happens before we have our event watcher added, we
    // can just open all the joysticks right here
    for (int i = 0; i < SDL_NumJoysticks(); ++i) {
        InitJoystick(i);
    }
}

SDLDriver::~SDLDriver() {
    CloseJoysticks();
    SDL_DelEventWatch(&SDLEventWatcher, this);

    initialized = false;
    if (start_thread) {
        vibration_thread.join();
        SDL_QuitSubSystem(SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER);
    }
}

std::vector<Common::ParamPackage> SDLDriver::GetInputDevices() const {
    std::vector<Common::ParamPackage> devices;
    std::unordered_map<int, std::shared_ptr<SDLJoystick>> joycon_pairs;
    for (const auto& [key, value] : joystick_map) {
        for (const auto& joystick : value) {
            if (!joystick->GetSDLJoystick()) {
                continue;
            }
            const std::string name =
                fmt::format("{} {}", joystick->GetControllerName(), joystick->GetPort());
            devices.emplace_back(Common::ParamPackage{
                {"engine", GetEngineName()},
                {"display", std::move(name)},
                {"guid", joystick->GetGUID().RawString()},
                {"port", std::to_string(joystick->GetPort())},
            });
            if (joystick->IsJoyconLeft()) {
                joycon_pairs.insert_or_assign(joystick->GetPort(), joystick);
            }
        }
    }

    // Add dual controllers
    for (const auto& [key, value] : joystick_map) {
        for (const auto& joystick : value) {
            if (joystick->IsJoyconRight()) {
                if (!joycon_pairs.contains(joystick->GetPort())) {
                    continue;
                }
                const auto joystick2 = joycon_pairs.at(joystick->GetPort());

                const std::string name =
                    fmt::format("{} {}", "Nintendo Dual Joy-Con", joystick->GetPort());
                devices.emplace_back(Common::ParamPackage{
                    {"engine", GetEngineName()},
                    {"display", std::move(name)},
                    {"guid", joystick->GetGUID().RawString()},
                    {"guid2", joystick2->GetGUID().RawString()},
                    {"port", std::to_string(joystick->GetPort())},
                });
            }
        }
    }
    return devices;
}

Common::Input::DriverResult SDLDriver::SetVibration(
    const PadIdentifier& identifier, const Common::Input::VibrationStatus& vibration) {
    const auto joystick =
        GetSDLJoystickByGUID(identifier.guid.RawString(), static_cast<int>(identifier.port));
    const auto process_amplitude_exp = [](f32 amplitude, f32 factor) {
        return (amplitude + std::pow(amplitude, factor)) * 0.5f * 0xFFFF;
    };

    // Default exponential curve for rumble
    f32 factor = 0.35f;

    // If vibration is set as a linear output use a flatter value
    if (vibration.type == Common::Input::VibrationAmplificationType::Linear) {
        factor = 0.5f;
    }

    // Amplitude for HD rumble needs no modification
    if (joystick->HasHDRumble()) {
        factor = 1.0f;
    }

    const Common::Input::VibrationStatus new_vibration{
        .low_amplitude = process_amplitude_exp(vibration.low_amplitude, factor),
        .low_frequency = vibration.low_frequency,
        .high_amplitude = process_amplitude_exp(vibration.high_amplitude, factor),
        .high_frequency = vibration.high_frequency,
        .type = Common::Input::VibrationAmplificationType::Exponential,
    };

    vibration_queue.Push(VibrationRequest{
        .identifier = identifier,
        .vibration = new_vibration,
    });

    return Common::Input::DriverResult::Success;
}

bool SDLDriver::IsVibrationEnabled(const PadIdentifier& identifier) {
    const auto joystick =
        GetSDLJoystickByGUID(identifier.guid.RawString(), static_cast<int>(identifier.port));

    static constexpr Common::Input::VibrationStatus test_vibration{
        .low_amplitude = 1,
        .low_frequency = 160.0f,
        .high_amplitude = 1,
        .high_frequency = 320.0f,
        .type = Common::Input::VibrationAmplificationType::Exponential,
    };

    static constexpr Common::Input::VibrationStatus zero_vibration{
        .low_amplitude = 0,
        .low_frequency = 160.0f,
        .high_amplitude = 0,
        .high_frequency = 320.0f,
        .type = Common::Input::VibrationAmplificationType::Exponential,
    };

    if (joystick->IsVibrationTested()) {
        return joystick->HasVibration();
    }

    // First vibration might fail
    joystick->RumblePlay(test_vibration);

    // Wait for about 15ms to ensure the controller is ready for the stop command
    std::this_thread::sleep_for(std::chrono::milliseconds(15));

    if (!joystick->RumblePlay(zero_vibration)) {
        joystick->EnableVibration(false);
        return false;
    }

    joystick->EnableVibration(true);
    return true;
}

void SDLDriver::SendVibrations() {
    std::vector<VibrationRequest> filtered_vibrations{};
    while (!vibration_queue.Empty()) {
        VibrationRequest request;
        vibration_queue.Pop(request);
        const auto joystick = GetSDLJoystickByGUID(request.identifier.guid.RawString(),
                                                   static_cast<int>(request.identifier.port));
        const auto it = std::find_if(filtered_vibrations.begin(), filtered_vibrations.end(),
                                     [request](VibrationRequest vibration) {
                                         return vibration.identifier == request.identifier;
                                     });
        if (it == filtered_vibrations.end()) {
            filtered_vibrations.push_back(std::move(request));
            continue;
        }
        *it = request;
    }

    for (const auto& vibration : filtered_vibrations) {
        const auto joystick = GetSDLJoystickByGUID(vibration.identifier.guid.RawString(),
                                                   static_cast<int>(vibration.identifier.port));
        joystick->RumblePlay(vibration.vibration);
    }
}

Common::ParamPackage SDLDriver::BuildAnalogParamPackageForButton(int port, const Common::UUID& guid,
                                                                 s32 axis, float value) const {
    Common::ParamPackage params{};
    params.Set("engine", GetEngineName());
    params.Set("port", port);
    params.Set("guid", guid.RawString());
    params.Set("axis", axis);
    params.Set("threshold", "0.5");
    params.Set("invert", value < 0 ? "-" : "+");
    return params;
}

Common::ParamPackage SDLDriver::BuildButtonParamPackageForButton(int port, const Common::UUID& guid,
                                                                 s32 button) const {
    Common::ParamPackage params{};
    params.Set("engine", GetEngineName());
    params.Set("port", port);
    params.Set("guid", guid.RawString());
    params.Set("button", button);
    return params;
}

Common::ParamPackage SDLDriver::BuildHatParamPackageForButton(int port, const Common::UUID& guid,
                                                              s32 hat, u8 value) const {
    Common::ParamPackage params{};
    params.Set("engine", GetEngineName());
    params.Set("port", port);
    params.Set("guid", guid.RawString());
    params.Set("hat", hat);
    params.Set("direction", GetHatButtonName(value));
    return params;
}

Common::ParamPackage SDLDriver::BuildMotionParam(int port, const Common::UUID& guid) const {
    Common::ParamPackage params{};
    params.Set("engine", GetEngineName());
    params.Set("motion", 0);
    params.Set("port", port);
    params.Set("guid", guid.RawString());
    return params;
}

Common::ParamPackage SDLDriver::BuildParamPackageForBinding(
    int port, const Common::UUID& guid, const SDL_GameControllerButtonBind& binding) const {
    switch (binding.bindType) {
    case SDL_CONTROLLER_BINDTYPE_NONE:
        break;
    case SDL_CONTROLLER_BINDTYPE_AXIS:
        return BuildAnalogParamPackageForButton(port, guid, binding.value.axis);
    case SDL_CONTROLLER_BINDTYPE_BUTTON:
        return BuildButtonParamPackageForButton(port, guid, binding.value.button);
    case SDL_CONTROLLER_BINDTYPE_HAT:
        return BuildHatParamPackageForButton(port, guid, binding.value.hat.hat,
                                             static_cast<u8>(binding.value.hat.hat_mask));
    }
    return {};
}

Common::ParamPackage SDLDriver::BuildParamPackageForAnalog(PadIdentifier identifier, int axis_x,
                                                           int axis_y, float offset_x,
                                                           float offset_y) const {
    Common::ParamPackage params;
    params.Set("engine", GetEngineName());
    params.Set("port", static_cast<int>(identifier.port));
    params.Set("guid", identifier.guid.RawString());
    params.Set("axis_x", axis_x);
    params.Set("axis_y", axis_y);
    params.Set("offset_x", offset_x);
    params.Set("offset_y", offset_y);
    params.Set("invert_x", "+");
    params.Set("invert_y", "+");
    return params;
}

ButtonMapping SDLDriver::GetButtonMappingForDevice(const Common::ParamPackage& params) {
    if (!params.Has("guid") || !params.Has("port")) {
        return {};
    }
    const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));

    auto* controller = joystick->GetSDLGameController();
    if (controller == nullptr) {
        return {};
    }

    // This list is missing ZL/ZR since those are not considered buttons in SDL GameController.
    // We will add those afterwards
    ButtonBindings switch_to_sdl_button;

    switch_to_sdl_button = GetDefaultButtonBinding(joystick);

    // Add the missing bindings for ZL/ZR
    static constexpr ZButtonBindings switch_to_sdl_axis{{
        {Settings::NativeButton::ZL, SDL_CONTROLLER_AXIS_TRIGGERLEFT},
        {Settings::NativeButton::ZR, SDL_CONTROLLER_AXIS_TRIGGERRIGHT},
    }};

    // Parameters contain two joysticks return dual
    if (params.Has("guid2")) {
        const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));

        if (joystick2->GetSDLGameController() != nullptr) {
            return GetDualControllerMapping(joystick, joystick2, switch_to_sdl_button,
                                            switch_to_sdl_axis);
        }
    }

    return GetSingleControllerMapping(joystick, switch_to_sdl_button, switch_to_sdl_axis);
}

ButtonBindings SDLDriver::GetDefaultButtonBinding(
    const std::shared_ptr<SDLJoystick>& joystick) const {
    // Default SL/SR mapping for other controllers
    auto sll_button = SDL_CONTROLLER_BUTTON_LEFTSHOULDER;
    auto srl_button = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER;
    auto slr_button = SDL_CONTROLLER_BUTTON_LEFTSHOULDER;
    auto srr_button = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER;

    if (joystick->IsJoyconLeft()) {
        sll_button = SDL_CONTROLLER_BUTTON_PADDLE2;
        srl_button = SDL_CONTROLLER_BUTTON_PADDLE4;
    }
    if (joystick->IsJoyconRight()) {
        slr_button = SDL_CONTROLLER_BUTTON_PADDLE3;
        srr_button = SDL_CONTROLLER_BUTTON_PADDLE1;
    }

    return {
        std::pair{Settings::NativeButton::A, SDL_CONTROLLER_BUTTON_B},
        {Settings::NativeButton::B, SDL_CONTROLLER_BUTTON_A},
        {Settings::NativeButton::X, SDL_CONTROLLER_BUTTON_Y},
        {Settings::NativeButton::Y, SDL_CONTROLLER_BUTTON_X},
        {Settings::NativeButton::LStick, SDL_CONTROLLER_BUTTON_LEFTSTICK},
        {Settings::NativeButton::RStick, SDL_CONTROLLER_BUTTON_RIGHTSTICK},
        {Settings::NativeButton::L, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
        {Settings::NativeButton::R, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
        {Settings::NativeButton::Plus, SDL_CONTROLLER_BUTTON_START},
        {Settings::NativeButton::Minus, SDL_CONTROLLER_BUTTON_BACK},
        {Settings::NativeButton::DLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT},
        {Settings::NativeButton::DUp, SDL_CONTROLLER_BUTTON_DPAD_UP},
        {Settings::NativeButton::DRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT},
        {Settings::NativeButton::DDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN},
        {Settings::NativeButton::SLLeft, sll_button},
        {Settings::NativeButton::SRLeft, srl_button},
        {Settings::NativeButton::SLRight, slr_button},
        {Settings::NativeButton::SRRight, srr_button},
        {Settings::NativeButton::Home, SDL_CONTROLLER_BUTTON_GUIDE},
        {Settings::NativeButton::Screenshot, SDL_CONTROLLER_BUTTON_MISC1},
    };
}

ButtonMapping SDLDriver::GetSingleControllerMapping(
    const std::shared_ptr<SDLJoystick>& joystick, const ButtonBindings& switch_to_sdl_button,
    const ZButtonBindings& switch_to_sdl_axis) const {
    ButtonMapping mapping;
    mapping.reserve(switch_to_sdl_button.size() + switch_to_sdl_axis.size());
    auto* controller = joystick->GetSDLGameController();

    for (const auto& [switch_button, sdl_button] : switch_to_sdl_button) {
        const auto& binding = SDL_GameControllerGetBindForButton(controller, sdl_button);
        mapping.insert_or_assign(
            switch_button,
            BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
    }
    for (const auto& [switch_button, sdl_axis] : switch_to_sdl_axis) {
        const auto& binding = SDL_GameControllerGetBindForAxis(controller, sdl_axis);
        mapping.insert_or_assign(
            switch_button,
            BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
    }

    return mapping;
}

ButtonMapping SDLDriver::GetDualControllerMapping(const std::shared_ptr<SDLJoystick>& joystick,
                                                  const std::shared_ptr<SDLJoystick>& joystick2,
                                                  const ButtonBindings& switch_to_sdl_button,
                                                  const ZButtonBindings& switch_to_sdl_axis) const {
    ButtonMapping mapping;
    mapping.reserve(switch_to_sdl_button.size() + switch_to_sdl_axis.size());
    auto* controller = joystick->GetSDLGameController();
    auto* controller2 = joystick2->GetSDLGameController();

    for (const auto& [switch_button, sdl_button] : switch_to_sdl_button) {
        if (IsButtonOnLeftSide(switch_button)) {
            const auto& binding = SDL_GameControllerGetBindForButton(controller2, sdl_button);
            mapping.insert_or_assign(
                switch_button,
                BuildParamPackageForBinding(joystick2->GetPort(), joystick2->GetGUID(), binding));
            continue;
        }
        const auto& binding = SDL_GameControllerGetBindForButton(controller, sdl_button);
        mapping.insert_or_assign(
            switch_button,
            BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
    }
    for (const auto& [switch_button, sdl_axis] : switch_to_sdl_axis) {
        if (IsButtonOnLeftSide(switch_button)) {
            const auto& binding = SDL_GameControllerGetBindForAxis(controller2, sdl_axis);
            mapping.insert_or_assign(
                switch_button,
                BuildParamPackageForBinding(joystick2->GetPort(), joystick2->GetGUID(), binding));
            continue;
        }
        const auto& binding = SDL_GameControllerGetBindForAxis(controller, sdl_axis);
        mapping.insert_or_assign(
            switch_button,
            BuildParamPackageForBinding(joystick->GetPort(), joystick->GetGUID(), binding));
    }

    return mapping;
}

bool SDLDriver::IsButtonOnLeftSide(Settings::NativeButton::Values button) const {
    switch (button) {
    case Settings::NativeButton::DDown:
    case Settings::NativeButton::DLeft:
    case Settings::NativeButton::DRight:
    case Settings::NativeButton::DUp:
    case Settings::NativeButton::L:
    case Settings::NativeButton::LStick:
    case Settings::NativeButton::Minus:
    case Settings::NativeButton::Screenshot:
    case Settings::NativeButton::ZL:
        return true;
    default:
        return false;
    }
}

AnalogMapping SDLDriver::GetAnalogMappingForDevice(const Common::ParamPackage& params) {
    if (!params.Has("guid") || !params.Has("port")) {
        return {};
    }
    const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
    const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
    auto* controller = joystick->GetSDLGameController();
    if (controller == nullptr) {
        return {};
    }

    AnalogMapping mapping = {};
    const auto& binding_left_x =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
    const auto& binding_left_y =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
    if (params.Has("guid2")) {
        const auto identifier = joystick2->GetPadIdentifier();
        PreSetController(identifier);
        PreSetAxis(identifier, binding_left_x.value.axis);
        PreSetAxis(identifier, binding_left_y.value.axis);
        const auto left_offset_x = -GetAxis(identifier, binding_left_x.value.axis);
        const auto left_offset_y = GetAxis(identifier, binding_left_y.value.axis);
        mapping.insert_or_assign(Settings::NativeAnalog::LStick,
                                 BuildParamPackageForAnalog(identifier, binding_left_x.value.axis,
                                                            binding_left_y.value.axis,
                                                            left_offset_x, left_offset_y));
    } else {
        const auto identifier = joystick->GetPadIdentifier();
        PreSetController(identifier);
        PreSetAxis(identifier, binding_left_x.value.axis);
        PreSetAxis(identifier, binding_left_y.value.axis);
        const auto left_offset_x = -GetAxis(identifier, binding_left_x.value.axis);
        const auto left_offset_y = GetAxis(identifier, binding_left_y.value.axis);
        mapping.insert_or_assign(Settings::NativeAnalog::LStick,
                                 BuildParamPackageForAnalog(identifier, binding_left_x.value.axis,
                                                            binding_left_y.value.axis,
                                                            left_offset_x, left_offset_y));
    }
    const auto& binding_right_x =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
    const auto& binding_right_y =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);
    const auto identifier = joystick->GetPadIdentifier();
    PreSetController(identifier);
    PreSetAxis(identifier, binding_right_x.value.axis);
    PreSetAxis(identifier, binding_right_y.value.axis);
    const auto right_offset_x = -GetAxis(identifier, binding_right_x.value.axis);
    const auto right_offset_y = GetAxis(identifier, binding_right_y.value.axis);
    mapping.insert_or_assign(Settings::NativeAnalog::RStick,
                             BuildParamPackageForAnalog(identifier, binding_right_x.value.axis,
                                                        binding_right_y.value.axis, right_offset_x,
                                                        right_offset_y));
    return mapping;
}

MotionMapping SDLDriver::GetMotionMappingForDevice(const Common::ParamPackage& params) {
    if (!params.Has("guid") || !params.Has("port")) {
        return {};
    }
    const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
    const auto joystick2 = GetSDLJoystickByGUID(params.Get("guid2", ""), params.Get("port", 0));
    auto* controller = joystick->GetSDLGameController();
    if (controller == nullptr) {
        return {};
    }

    MotionMapping mapping = {};
    joystick->EnableMotion();

    if (joystick->HasMotion()) {
        mapping.insert_or_assign(Settings::NativeMotion::MotionRight,
                                 BuildMotionParam(joystick->GetPort(), joystick->GetGUID()));
    }
    if (params.Has("guid2")) {
        joystick2->EnableMotion();
        if (joystick2->HasMotion()) {
            mapping.insert_or_assign(Settings::NativeMotion::MotionLeft,
                                     BuildMotionParam(joystick2->GetPort(), joystick2->GetGUID()));
        }
    } else {
        if (joystick->HasMotion()) {
            mapping.insert_or_assign(Settings::NativeMotion::MotionLeft,
                                     BuildMotionParam(joystick->GetPort(), joystick->GetGUID()));
        }
    }

    return mapping;
}

Common::Input::ButtonNames SDLDriver::GetUIName(const Common::ParamPackage& params) const {
    if (params.Has("button")) {
        // TODO(German77): Find how to substitute the values for real button names
        return Common::Input::ButtonNames::Value;
    }
    if (params.Has("hat")) {
        return Common::Input::ButtonNames::Value;
    }
    if (params.Has("axis")) {
        return Common::Input::ButtonNames::Value;
    }
    if (params.Has("axis_x") && params.Has("axis_y") && params.Has("axis_z")) {
        return Common::Input::ButtonNames::Value;
    }
    if (params.Has("motion")) {
        return Common::Input::ButtonNames::Engine;
    }

    return Common::Input::ButtonNames::Invalid;
}

std::string SDLDriver::GetHatButtonName(u8 direction_value) const {
    switch (direction_value) {
    case SDL_HAT_UP:
        return "up";
    case SDL_HAT_DOWN:
        return "down";
    case SDL_HAT_LEFT:
        return "left";
    case SDL_HAT_RIGHT:
        return "right";
    default:
        return {};
    }
}

u8 SDLDriver::GetHatButtonId(const std::string& direction_name) const {
    Uint8 direction;
    if (direction_name == "up") {
        direction = SDL_HAT_UP;
    } else if (direction_name == "down") {
        direction = SDL_HAT_DOWN;
    } else if (direction_name == "left") {
        direction = SDL_HAT_LEFT;
    } else if (direction_name == "right") {
        direction = SDL_HAT_RIGHT;
    } else {
        direction = 0;
    }
    return direction;
}

bool SDLDriver::IsStickInverted(const Common::ParamPackage& params) {
    if (!params.Has("guid") || !params.Has("port")) {
        return false;
    }
    const auto joystick = GetSDLJoystickByGUID(params.Get("guid", ""), params.Get("port", 0));
    if (joystick == nullptr) {
        return false;
    }
    auto* controller = joystick->GetSDLGameController();
    if (controller == nullptr) {
        return false;
    }

    const auto& axis_x = params.Get("axis_x", 0);
    const auto& axis_y = params.Get("axis_y", 0);
    const auto& binding_left_x =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX);
    const auto& binding_right_x =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
    const auto& binding_left_y =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY);
    const auto& binding_right_y =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);

    if (axis_x != binding_left_y.value.axis && axis_x != binding_right_y.value.axis) {
        return false;
    }
    if (axis_y != binding_left_x.value.axis && axis_y != binding_right_x.value.axis) {
        return false;
    }
    return true;
}

} // namespace InputCommon


code:
// SPDX-FileCopyrightText: 2018 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <atomic>
#include <mutex>
#include <thread>
#include <unordered_map>

#include <SDL.h>

#include "common/common_types.h"
#include "common/threadsafe_queue.h"
#include "input_common/input_engine.h"

union SDL_Event;
using SDL_GameController = struct _SDL_GameController;
using SDL_Joystick = struct _SDL_Joystick;
using SDL_JoystickID = s32;

namespace InputCommon {

class SDLJoystick;

using ButtonBindings =
    std::array<std::pair<Settings::NativeButton::Values, SDL_GameControllerButton>, 20>;
using ZButtonBindings =
    std::array<std::pair<Settings::NativeButton::Values, SDL_GameControllerAxis>, 2>;

class SDLDriver : public InputEngine {
public:
    /// Initializes and registers SDL device factories
    explicit SDLDriver(std::string input_engine_);

    /// Unregisters SDL device factories and shut them down.
    ~SDLDriver() override;

    void PumpEvents() const;

    /// Handle SDL_Events for joysticks from SDL_PollEvent
    void HandleGameControllerEvent(const SDL_Event& event);

    /// Get the nth joystick with the corresponding GUID
    std::shared_ptr<SDLJoystick> GetSDLJoystickBySDLID(SDL_JoystickID sdl_id);

    /**
     * Check how many identical joysticks (by guid) were connected before the one with sdl_id and so
     * tie it to a SDLJoystick with the same guid and that port
     */
    std::shared_ptr<SDLJoystick> GetSDLJoystickByGUID(const Common::UUID& guid, int port);
    std::shared_ptr<SDLJoystick> GetSDLJoystickByGUID(const std::string& guid, int port);

    std::vector<Common::ParamPackage> GetInputDevices() const override;

    ButtonMapping GetButtonMappingForDevice(const Common::ParamPackage& params) override;
    AnalogMapping GetAnalogMappingForDevice(const Common::ParamPackage& params) override;
    MotionMapping GetMotionMappingForDevice(const Common::ParamPackage& params) override;
    Common::Input::ButtonNames GetUIName(const Common::ParamPackage& params) const override;

    std::string GetHatButtonName(u8 direction_value) const override;
    u8 GetHatButtonId(const std::string& direction_name) const override;

    bool IsStickInverted(const Common::ParamPackage& params) override;

    Common::Input::DriverResult SetVibration(
        const PadIdentifier& identifier, const Common::Input::VibrationStatus& vibration) override;

    bool IsVibrationEnabled(const PadIdentifier& identifier) override;

private:
    void InitJoystick(int joystick_index);
    void CloseJoystick(SDL_Joystick* sdl_joystick);

    /// Needs to be called before SDL_QuitSubSystem.
    void CloseJoysticks();

    /// Takes all vibrations from the queue and sends the command to the controller
    void SendVibrations();

    Common::ParamPackage BuildAnalogParamPackageForButton(int port, const Common::UUID& guid,
                                                          s32 axis, float value = 0.1f) const;
    Common::ParamPackage BuildButtonParamPackageForButton(int port, const Common::UUID& guid,
                                                          s32 button) const;

    Common::ParamPackage BuildHatParamPackageForButton(int port, const Common::UUID& guid, s32 hat,
                                                       u8 value) const;

    Common::ParamPackage BuildMotionParam(int port, const Common::UUID& guid) const;

    Common::ParamPackage BuildParamPackageForBinding(
        int port, const Common::UUID& guid, const SDL_GameControllerButtonBind& binding) const;

    Common::ParamPackage BuildParamPackageForAnalog(PadIdentifier identifier, int axis_x,
                                                    int axis_y, float offset_x,
                                                    float offset_y) const;

    /// Returns the default button bindings list
    ButtonBindings GetDefaultButtonBinding(const std::shared_ptr<SDLJoystick>& joystick) const;

    /// Returns the button mappings from a single controller
    ButtonMapping GetSingleControllerMapping(const std::shared_ptr<SDLJoystick>& joystick,
                                             const ButtonBindings& switch_to_sdl_button,
                                             const ZButtonBindings& switch_to_sdl_axis) const;

    /// Returns the button mappings from two different controllers
    ButtonMapping GetDualControllerMapping(const std::shared_ptr<SDLJoystick>& joystick,
                                           const std::shared_ptr<SDLJoystick>& joystick2,
                                           const ButtonBindings& switch_to_sdl_button,
                                           const ZButtonBindings& switch_to_sdl_axis) const;

    /// Returns true if the button is on the left joycon
    bool IsButtonOnLeftSide(Settings::NativeButton::Values button) const;

    /// Queue of vibration request to controllers
    Common::SPSCQueue<VibrationRequest> vibration_queue;

    /// Map of GUID of a list of corresponding virtual Joysticks
    std::unordered_map<Common::UUID, std::vector<std::shared_ptr<SDLJoystick>>> joystick_map;
    std::mutex joystick_map_mutex;

    bool start_thread = false;
    std::atomic<bool> initialized = false;

    std::thread vibration_thread;
};
} // namespace InputCommon


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <cstring>
#include <sstream>
#include <fmt/format.h>

#include "common/fs/file.h"
#include "common/fs/fs_types.h"
#include "common/fs/path_util.h"
#include "common/logging/log.h"
#include "common/settings.h"
#include "input_common/drivers/tas_input.h"

namespace InputCommon::TasInput {

enum class Tas::TasAxis : u8 {
    StickX,
    StickY,
    SubstickX,
    SubstickY,
    Undefined,
};

// Supported keywords and buttons from a TAS file
constexpr std::array<std::pair<std::string_view, TasButton>, 18> text_to_tas_button = {
    std::pair{"KEY_A", TasButton::BUTTON_A},
    {"KEY_B", TasButton::BUTTON_B},
    {"KEY_X", TasButton::BUTTON_X},
    {"KEY_Y", TasButton::BUTTON_Y},
    {"KEY_LSTICK", TasButton::STICK_L},
    {"KEY_RSTICK", TasButton::STICK_R},
    {"KEY_L", TasButton::TRIGGER_L},
    {"KEY_R", TasButton::TRIGGER_R},
    {"KEY_PLUS", TasButton::BUTTON_PLUS},
    {"KEY_MINUS", TasButton::BUTTON_MINUS},
    {"KEY_DLEFT", TasButton::BUTTON_LEFT},
    {"KEY_DUP", TasButton::BUTTON_UP},
    {"KEY_DRIGHT", TasButton::BUTTON_RIGHT},
    {"KEY_DDOWN", TasButton::BUTTON_DOWN},
    {"KEY_SL", TasButton::BUTTON_SL},
    {"KEY_SR", TasButton::BUTTON_SR},
    // These buttons are disabled to avoid TAS input from activating hotkeys
    // {"KEY_CAPTURE", TasButton::BUTTON_CAPTURE},
    // {"KEY_HOME", TasButton::BUTTON_HOME},
    {"KEY_ZL", TasButton::TRIGGER_ZL},
    {"KEY_ZR", TasButton::TRIGGER_ZR},
};

Tas::Tas(std::string input_engine_) : InputEngine(std::move(input_engine_)) {
    for (size_t player_index = 0; player_index < PLAYER_NUMBER; player_index++) {
        PadIdentifier identifier{
            .guid = Common::UUID{},
            .port = player_index,
            .pad = 0,
        };
        PreSetController(identifier);
    }
    ClearInput();
    if (!Settings::values.tas_enable) {
        needs_reset = true;
        return;
    }
    LoadTasFiles();
}

Tas::~Tas() {
    Stop();
}

void Tas::LoadTasFiles() {
    script_length = 0;
    for (size_t i = 0; i < commands.size(); i++) {
        LoadTasFile(i, 0);
        if (commands[i].size() > script_length) {
            script_length = commands[i].size();
        }
    }
}

void Tas::LoadTasFile(size_t player_index, size_t file_index) {
    commands[player_index].clear();

    std::string file = Common::FS::ReadStringFromFile(
        Common::FS::GetYuzuPath(Common::FS::YuzuPath::TASDir) /
            fmt::format("script{}-{}.txt", file_index, player_index + 1),
        Common::FS::FileType::BinaryFile);
    std::istringstream command_line(file);
    std::string line;
    int frame_no = 0;
    while (std::getline(command_line, line, '\n')) {
        if (line.empty()) {
            continue;
        }

        std::vector<std::string> seg_list;
        {
            std::istringstream line_stream(line);
            std::string segment;
            while (std::getline(line_stream, segment, ' ')) {
                seg_list.push_back(std::move(segment));
            }
        }

        if (seg_list.size() < 4) {
            continue;
        }

        try {
            const auto num_frames = std::stoi(seg_list[0]);
            while (frame_no < num_frames) {
                commands[player_index].emplace_back();
                frame_no++;
            }
        } catch (const std::invalid_argument&) {
            LOG_ERROR(Input, "Invalid argument: '{}' at command {}", seg_list[0], frame_no);
        } catch (const std::out_of_range&) {
            LOG_ERROR(Input, "Out of range: '{}' at command {}", seg_list[0], frame_no);
        }

        TASCommand command = {
            .buttons = ReadCommandButtons(seg_list[1]),
            .l_axis = ReadCommandAxis(seg_list[2]),
            .r_axis = ReadCommandAxis(seg_list[3]),
        };
        commands[player_index].push_back(command);
        frame_no++;
    }
    LOG_INFO(Input, "TAS file loaded! {} frames", frame_no);
}

void Tas::WriteTasFile(std::u8string_view file_name) {
    std::string output_text;
    for (size_t frame = 0; frame < record_commands.size(); frame++) {
        const TASCommand& line = record_commands[frame];
        output_text += fmt::format("{} {} {} {}\n", frame, WriteCommandButtons(line.buttons),
                                   WriteCommandAxis(line.l_axis), WriteCommandAxis(line.r_axis));
    }

    const auto tas_file_name = Common::FS::GetYuzuPath(Common::FS::YuzuPath::TASDir) / file_name;
    const auto bytes_written =
        Common::FS::WriteStringToFile(tas_file_name, Common::FS::FileType::TextFile, output_text);
    if (bytes_written == output_text.size()) {
        LOG_INFO(Input, "TAS file written to file!");
    } else {
        LOG_ERROR(Input, "Writing the TAS-file has failed! {} / {} bytes written", bytes_written,
                  output_text.size());
    }
}

void Tas::RecordInput(u64 buttons, TasAnalog left_axis, TasAnalog right_axis) {
    last_input = {
        .buttons = buttons,
        .l_axis = left_axis,
        .r_axis = right_axis,
    };
}

std::tuple<TasState, size_t, std::array<size_t, PLAYER_NUMBER>> Tas::GetStatus() const {
    TasState state;
    std::array<size_t, PLAYER_NUMBER> lengths{0};
    if (is_recording) {
        lengths[0] = record_commands.size();
        return {TasState::Recording, record_commands.size(), lengths};
    }

    if (is_running) {
        state = TasState::Running;
    } else {
        state = TasState::Stopped;
    }

    for (size_t i = 0; i < PLAYER_NUMBER; i++) {
        lengths[i] = commands[i].size();
    }

    return {state, current_command, lengths};
}

void Tas::UpdateThread() {
    if (!Settings::values.tas_enable) {
        if (is_running) {
            Stop();
        }
        return;
    }

    if (is_recording) {
        record_commands.push_back(last_input);
    }
    if (needs_reset) {
        current_command = 0;
        needs_reset = false;
        LoadTasFiles();
        LOG_DEBUG(Input, "tas_reset done");
    }

    if (!is_running) {
        ClearInput();
        return;
    }
    if (current_command < script_length) {
        LOG_DEBUG(Input, "Playing TAS {}/{}", current_command, script_length);
        const size_t frame = current_command++;
        for (size_t player_index = 0; player_index < commands.size(); player_index++) {
            TASCommand command{};
            if (frame < commands[player_index].size()) {
                command = commands[player_index][frame];
            }

            PadIdentifier identifier{
                .guid = Common::UUID{},
                .port = player_index,
                .pad = 0,
            };
            for (std::size_t i = 0; i < sizeof(command.buttons) * 8; ++i) {
                const bool button_status = (command.buttons & (1LLU << i)) != 0;
                const int button = static_cast<int>(i);
                SetButton(identifier, button, button_status);
            }
            SetTasAxis(identifier, TasAxis::StickX, command.l_axis.x);
            SetTasAxis(identifier, TasAxis::StickY, command.l_axis.y);
            SetTasAxis(identifier, TasAxis::SubstickX, command.r_axis.x);
            SetTasAxis(identifier, TasAxis::SubstickY, command.r_axis.y);
        }
    } else {
        is_running = Settings::values.tas_loop.GetValue();
        LoadTasFiles();
        current_command = 0;
        ClearInput();
    }
}

void Tas::ClearInput() {
    ResetButtonState();
    ResetAnalogState();
}

TasAnalog Tas::ReadCommandAxis(const std::string& line) const {
    std::vector<std::string> seg_list;
    {
        std::istringstream line_stream(line);
        std::string segment;
        while (std::getline(line_stream, segment, ';')) {
            seg_list.push_back(std::move(segment));
        }
    }

    if (seg_list.size() < 2) {
        LOG_ERROR(Input, "Invalid axis data: '{}'", line);
        return {};
    }

    try {
        const float x = std::stof(seg_list.at(0)) / 32767.0f;
        const float y = std::stof(seg_list.at(1)) / 32767.0f;
        return {x, y};
    } catch (const std::invalid_argument&) {
        LOG_ERROR(Input, "Invalid argument: '{}'", line);
    } catch (const std::out_of_range&) {
        LOG_ERROR(Input, "Out of range: '{}'", line);
    }
    return {};
}

u64 Tas::ReadCommandButtons(const std::string& line) const {
    std::istringstream button_text(line);
    std::string button_line;
    u64 buttons = 0;
    while (std::getline(button_text, button_line, ';')) {
        for (const auto& [text, tas_button] : text_to_tas_button) {
            if (text == button_line) {
                buttons |= static_cast<u64>(tas_button);
                break;
            }
        }
    }
    return buttons;
}

std::string Tas::WriteCommandButtons(u64 buttons) const {
    std::string returns;
    for (const auto& [text_button, tas_button] : text_to_tas_button) {
        if ((buttons & static_cast<u64>(tas_button)) != 0) {
            returns += fmt::format("{};", text_button);
        }
    }
    return returns.empty() ? "NONE" : returns;
}

std::string Tas::WriteCommandAxis(TasAnalog analog) const {
    return fmt::format("{};{}", analog.x * 32767, analog.y * 32767);
}

void Tas::SetTasAxis(const PadIdentifier& identifier, TasAxis axis, f32 value) {
    SetAxis(identifier, static_cast<int>(axis), value);
}

void Tas::StartStop() {
    if (!Settings::values.tas_enable) {
        return;
    }
    if (is_running) {
        Stop();
    } else {
        is_running = true;
    }
}

void Tas::Stop() {
    is_running = false;
}

void Tas::Reset() {
    if (!Settings::values.tas_enable) {
        return;
    }
    needs_reset = true;
}

bool Tas::Record() {
    if (!Settings::values.tas_enable) {
        return true;
    }
    is_recording = !is_recording;
    return is_recording;
}

void Tas::SaveRecording(bool overwrite_file) {
    if (is_recording) {
        return;
    }
    if (record_commands.empty()) {
        return;
    }
    WriteTasFile(u8"record.txt");
    if (overwrite_file) {
        WriteTasFile(u8"script0-1.txt");
    }
    needs_reset = true;
    record_commands.clear();
}

} // namespace InputCommon::TasInput


code:
// SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <array>
#include <string>
#include <vector>

#include "common/common_types.h"
#include "input_common/input_engine.h"

/*
To play back TAS scripts on Yuzu, select the folder with scripts in the configuration menu below
Tools -> Configure TAS. The file itself has normal text format and has to be called script0-1.txt
for controller 1, script0-2.txt for controller 2 and so forth (with max. 8 players).

A script file has the same format as TAS-nx uses, so final files will look like this:

1 KEY_B 0;0 0;0
6 KEY_ZL 0;0 0;0
41 KEY_ZL;KEY_Y 0;0 0;0
43 KEY_X;KEY_A 32767;0 0;0
44 KEY_A 32767;0 0;0
45 KEY_A 32767;0 0;0
46 KEY_A 32767;0 0;0
47 KEY_A 32767;0 0;0

After placing the file at the correct location, it can be read into Yuzu with the (default) hotkey
CTRL+F6 (refresh). In the bottom left corner, it will display the amount of frames the script file
has. Playback can be started or stopped using CTRL+F5.

However, for playback to actually work, the correct input device has to be selected: In the Controls
menu, select TAS from the device list for the controller that the script should be played on.

Recording a new script file is really simple: Just make sure that the proper device (not TAS) is
connected on P1, and press CTRL+F7 to start recording. When done, just press the same keystroke
again (CTRL+F7). The new script will be saved at the location previously selected, as the filename
record.txt.

For debugging purposes, the common controller debugger can be used (View -> Debugging -> Controller
P1).
*/

namespace InputCommon::TasInput {

constexpr size_t PLAYER_NUMBER = 10;

enum class TasButton : u64 {
    BUTTON_A = 1U << 0,
    BUTTON_B = 1U << 1,
    BUTTON_X = 1U << 2,
    BUTTON_Y = 1U << 3,
    STICK_L = 1U << 4,
    STICK_R = 1U << 5,
    TRIGGER_L = 1U << 6,
    TRIGGER_R = 1U << 7,
    TRIGGER_ZL = 1U << 8,
    TRIGGER_ZR = 1U << 9,
    BUTTON_PLUS = 1U << 10,
    BUTTON_MINUS = 1U << 11,
    BUTTON_LEFT = 1U << 12,
    BUTTON_UP = 1U << 13,
    BUTTON_RIGHT = 1U << 14,
    BUTTON_DOWN = 1U << 15,
    BUTTON_SL = 1U << 16,
    BUTTON_SR = 1U << 17,
    BUTTON_HOME = 1U << 18,
    BUTTON_CAPTURE = 1U << 19,
};

struct TasAnalog {
    float x{};
    float y{};
};

enum class TasState {
    Running,
    Recording,
    Stopped,
};

class Tas final : public InputEngine {
public:
    explicit Tas(std::string input_engine_);
    ~Tas() override;

    /**
     * Changes the input status that will be stored in each frame
     * @param buttons    Bitfield with the status of the buttons
     * @param left_axis  Value of the left axis
     * @param right_axis Value of the right axis
     */
    void RecordInput(u64 buttons, TasAnalog left_axis, TasAnalog right_axis);

    // Main loop that records or executes input
    void UpdateThread();

    // Sets the flag to start or stop the TAS command execution and swaps controllers profiles
    void StartStop();

    // Stop the TAS and reverts any controller profile
    void Stop();

    // Sets the flag to reload the file and start from the beginning in the next update
    void Reset();

    /**
     * Sets the flag to enable or disable recording of inputs
     * @returns true if the current recording status is enabled
     */
    bool Record();

    /**
     * Saves contents of record_commands on a file
     * @param overwrite_file Indicates if player 1 should be overwritten
     */
    void SaveRecording(bool overwrite_file);

    /**
     * Returns the current status values of TAS playback/recording
     * @returns A Tuple of
     * TasState indicating the current state out of Running ;
     * Current playback progress ;
     * Total length of script file currently loaded or being recorded
     */
    std::tuple<TasState, size_t, std::array<size_t, PLAYER_NUMBER>> GetStatus() const;

private:
    enum class TasAxis : u8;

    struct TASCommand {
        u64 buttons{};
        TasAnalog l_axis{};
        TasAnalog r_axis{};
    };

    /// Loads TAS files from all players
    void LoadTasFiles();

    /**
     * Loads TAS file from the specified player
     * @param player_index Player number to save the script
     * @param file_index   Script number of the file
     */
    void LoadTasFile(size_t player_index, size_t file_index);

    /**
     * Writes a TAS file from the recorded commands
     * @param file_name Name of the file to be written
     */
    void WriteTasFile(std::u8string_view file_name);

    /**
     * Parses a string containing the axis values. X and Y have a range from -32767 to 32767
     * @param line String containing axis values with the following format "x;y"
     * @returns A TAS analog object with axis values with range from -1.0 to 1.0
     */
    TasAnalog ReadCommandAxis(const std::string& line) const;

    /**
     * Parses a string containing the button values. Each button is represented by it's text format
     * specified in text_to_tas_button array
     * @param line string containing button name with the following format "a;b;c;d..."
     * @returns A u64 with each bit representing the status of a button
     */
    u64 ReadCommandButtons(const std::string& line) const;

    /**
     * Reset state of all players
     */
    void ClearInput();

    /**
     * Converts an u64 containing the button status into the text equivalent
     * @param buttons Bitfield with the status of the buttons
     * @returns A string with the name of the buttons to be written to the file
     */
    std::string WriteCommandButtons(u64 buttons) const;

    /**
     * Converts an TAS analog object containing the axis status into the text equivalent
     * @param analog Value of the axis
     * @returns A string with the value of the axis to be written to the file
     */
    std::string WriteCommandAxis(TasAnalog analog) const;

    /// Sets an axis for a particular pad to the given value.
    void SetTasAxis(const PadIdentifier& identifier, TasAxis axis, f32 value);

    size_t script_length{0};
    bool is_recording{false};
    bool is_running{false};
    bool needs_reset{false};
    std::array<std::vector<TASCommand>, PLAYER_NUMBER> commands{};
    std::vector<TASCommand> record_commands{};
    size_t current_command{0};
    TASCommand last_input{}; // only used for recording
};
} // namespace InputCommon::TasInput


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/param_package.h"
#include "input_common/drivers/touch_screen.h"

namespace InputCommon {

constexpr PadIdentifier identifier = {
    .guid = Common::UUID{},
    .port = 0,
    .pad = 0,
};

TouchScreen::TouchScreen(std::string input_engine_) : InputEngine(std::move(input_engine_)) {
    PreSetController(identifier);
    ReleaseAllTouch();
}

void TouchScreen::TouchMoved(float x, float y, std::size_t finger_id) {
    const auto index = GetIndexFromFingerId(finger_id);
    if (!index) {
        // Touch doesn't exist handle it as a new one
        TouchPressed(x, y, finger_id);
        return;
    }
    const auto i = index.value();
    fingers[i].is_active = true;
    SetButton(identifier, static_cast<int>(i), true);
    SetAxis(identifier, static_cast<int>(i * 2), x);
    SetAxis(identifier, static_cast<int>(i * 2 + 1), y);
}

void TouchScreen::TouchPressed(float x, float y, std::size_t finger_id) {
    if (GetIndexFromFingerId(finger_id)) {
        // Touch already exist. Just update the data
        TouchMoved(x, y, finger_id);
        return;
    }
    const auto index = GetNextFreeIndex();
    if (!index) {
        // No free entries. Ignore input
        return;
    }
    const auto i = index.value();
    fingers[i].is_enabled = true;
    fingers[i].finger_id = finger_id;
    TouchMoved(x, y, finger_id);
}

void TouchScreen::TouchReleased(std::size_t finger_id) {
    const auto index = GetIndexFromFingerId(finger_id);
    if (!index) {
        return;
    }
    const auto i = index.value();
    fingers[i].is_enabled = false;
    SetButton(identifier, static_cast<int>(i), false);
    SetAxis(identifier, static_cast<int>(i * 2), 0.0f);
    SetAxis(identifier, static_cast<int>(i * 2 + 1), 0.0f);
}

std::optional<std::size_t> TouchScreen::GetIndexFromFingerId(std::size_t finger_id) const {
    for (std::size_t index = 0; index < MAX_FINGER_COUNT; ++index) {
        const auto& finger = fingers[index];
        if (!finger.is_enabled) {
            continue;
        }
        if (finger.finger_id == finger_id) {
            return index;
        }
    }
    return std::nullopt;
}

std::optional<std::size_t> TouchScreen::GetNextFreeIndex() const {
    for (std::size_t index = 0; index < MAX_FINGER_COUNT; ++index) {
        if (!fingers[index].is_enabled) {
            return index;
        }
    }
    return std::nullopt;
}

void TouchScreen::ClearActiveFlag() {
    for (auto& finger : fingers) {
        finger.is_active = false;
    }
}

void TouchScreen::ReleaseInactiveTouch() {
    for (const auto& finger : fingers) {
        if (!finger.is_active) {
            TouchReleased(finger.finger_id);
        }
    }
}

void TouchScreen::ReleaseAllTouch() {
    for (const auto& finger : fingers) {
        if (finger.is_enabled) {
            TouchReleased(finger.finger_id);
        }
    }
}

} // namespace InputCommon


code:
// SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#pragma once

#include <optional>

#include "input_common/input_engine.h"

namespace InputCommon {

/**
 * A touch device factory representing a touch screen. It receives touch events and forward them
 * to all touch devices it created.
 */
class TouchScreen final : public InputEngine {
public:
    explicit TouchScreen(std::string input_engine_);

    /**
     * Signals that touch has moved and marks this touch point as active
     * @param x new horizontal position
     * @param y new vertical position
     * @param finger_id of the touch point to be updated
     */
    void TouchMoved(float x, float y, std::size_t finger_id);

    /**
     * Signals and creates a new touch point with this finger id
     * @param x starting horizontal position
     * @param y starting vertical position
     * @param finger_id to be assigned to the new touch point
     */
    void TouchPressed(float x, float y, std::size_t finger_id);

    /**
     * Signals and resets the touch point related to the this finger id
     * @param finger_id to be released
     */
    void TouchReleased(std::size_t finger_id);

    /// Resets the active flag for each touch point
    void ClearActiveFlag();

    /// Releases all touch that haven't been marked as active
    void ReleaseInactiveTouch();

    /// Resets all inputs to their initial value
    void ReleaseAllTouch();

private:
    static constexpr std::size_t MAX_FINGER_COUNT = 16;

    struct TouchStatus {
        std::size_t finger_id{};
        bool is_enabled{};
        bool is_active{};
    };

    std::optional<std::size_t> GetIndexFromFingerId(std::size_t finger_id) const;

    std::optional<std::size_t> GetNextFreeIndex() const;

    std::array<TouchStatus, MAX_FINGER_COUNT> fingers{};
};

} // namespace InputCommon