aboutsummaryrefslogtreecommitdiff
path: root/src/input_common/sdl/sdl_impl.cpp
blob: 27a96c18b77660b3e27ec6c882146952af17e862 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
// Copyright 2018 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <functional>
#include <mutex>
#include <optional>
#include <sstream>
#include <string>
#include <thread>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#include <SDL.h>
#include "common/logging/log.h"
#include "common/param_package.h"
#include "common/threadsafe_queue.h"
#include "core/frontend/input.h"
#include "input_common/sdl/sdl_impl.h"
#include "input_common/settings.h"

namespace InputCommon::SDL {

namespace {
std::string GetGUID(SDL_Joystick* joystick) {
    const SDL_JoystickGUID guid = SDL_JoystickGetGUID(joystick);
    char guid_str[33];
    SDL_JoystickGetGUIDString(guid, guid_str, sizeof(guid_str));
    return guid_str;
}

/// Creates a ParamPackage from an SDL_Event that can directly be used to create a ButtonDevice
Common::ParamPackage SDLEventToButtonParamPackage(SDLState& state, const SDL_Event& event);
} // Anonymous namespace

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

    // Don't handle the event if we are configuring
    if (sdl_state->polling) {
        sdl_state->event_queue.Push(*event);
    } else {
        sdl_state->HandleGameControllerEvent(*event);
    }

    return 0;
}

class SDLJoystick {
public:
    SDLJoystick(std::string guid_, int port_, SDL_Joystick* joystick,
                SDL_GameController* gamecontroller)
        : guid{std::move(guid_)}, port{port_}, sdl_joystick{joystick, &SDL_JoystickClose},
          sdl_controller{gamecontroller, &SDL_GameControllerClose} {}

    void SetButton(int button, bool value) {
        std::lock_guard lock{mutex};
        state.buttons.insert_or_assign(button, value);
    }

    bool GetButton(int button) const {
        std::lock_guard lock{mutex};
        return state.buttons.at(button);
    }

    void SetAxis(int axis, Sint16 value) {
        std::lock_guard lock{mutex};
        state.axes.insert_or_assign(axis, value);
    }

    float GetAxis(int axis, float range) const {
        std::lock_guard lock{mutex};
        return state.axes.at(axis) / (32767.0f * range);
    }

    bool RumblePlay(f32 amp_low, f32 amp_high, int time) {
        const u16 raw_amp_low = static_cast<u16>(amp_low * 0xFFFF);
        const u16 raw_amp_high = static_cast<u16>(amp_high * 0xFFFF);
        // Lower drastically the number of state changes
        if (raw_amp_low >> 11 == last_state_rumble_low >> 11 &&
            raw_amp_high >> 11 == last_state_rumble_high >> 11) {
            if (raw_amp_low + raw_amp_high != 0 ||
                last_state_rumble_low + last_state_rumble_high == 0) {
                return false;
            }
        }
        // Don't change state if last vibration was < 20ms
        const auto now = std::chrono::system_clock::now();
        if (std::chrono::duration_cast<std::chrono::milliseconds>(now - last_vibration) <
            std::chrono::milliseconds(20)) {
            return raw_amp_low + raw_amp_high == 0;
        }

        last_vibration = now;
        last_state_rumble_low = raw_amp_low;
        last_state_rumble_high = raw_amp_high;
        if (sdl_joystick) {
            SDL_JoystickRumble(sdl_joystick.get(), raw_amp_low, raw_amp_high, time);
        }
        return false;
    }

    std::tuple<float, float> GetAnalog(int axis_x, int axis_y, float range) const {
        float x = GetAxis(axis_x, range);
        float y = GetAxis(axis_y, range);
        y = -y; // 3DS uses an y-axis inverse from SDL

        // Make sure the coordinates are in the unit circle,
        // otherwise normalize it.
        float r = x * x + y * y;
        if (r > 1.0f) {
            r = std::sqrt(r);
            x /= r;
            y /= r;
        }

        return std::make_tuple(x, y);
    }

    void SetHat(int hat, Uint8 direction) {
        std::lock_guard lock{mutex};
        state.hats.insert_or_assign(hat, direction);
    }

    bool GetHatDirection(int hat, Uint8 direction) const {
        std::lock_guard lock{mutex};
        return (state.hats.at(hat) & direction) != 0;
    }
    /**
     * The guid of the joystick
     */
    const std::string& 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();
    }

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

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

private:
    struct State {
        std::unordered_map<int, bool> buttons;
        std::unordered_map<int, Sint16> axes;
        std::unordered_map<int, Uint8> hats;
    } state;
    std::string guid;
    int port;
    u16 last_state_rumble_high;
    u16 last_state_rumble_low;
    std::chrono::time_point<std::chrono::system_clock> last_vibration;
    std::unique_ptr<SDL_Joystick, decltype(&SDL_JoystickClose)> sdl_joystick;
    std::unique_ptr<SDL_GameController, decltype(&SDL_GameControllerClose)> sdl_controller;
    mutable std::mutex mutex;
};

std::shared_ptr<SDLJoystick> SDLState::GetSDLJoystickByGUID(const std::string& guid, int port) {
    std::lock_guard 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[port];
    }
    auto joystick = std::make_shared<SDLJoystick>(guid, 0, nullptr, nullptr);
    return joystick_map[guid].emplace_back(std::move(joystick));
}

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

    std::lock_guard lock{joystick_map_mutex};
    const auto map_it = joystick_map.find(guid);
    if (map_it != joystick_map.end()) {
        const auto vec_it =
            std::find_if(map_it->second.begin(), map_it->second.end(),
                         [&sdl_joystick](const std::shared_ptr<SDLJoystick>& joystick) {
                             return sdl_joystick == joystick->GetSDLJoystick();
                         });
        if (vec_it != map_it->second.end()) {
            // This is the common case: There is already an existing SDL_Joystick maped to a
            // SDLJoystick. return the SDLJoystick
            return *vec_it;
        }

        // Search for a SDLJoystick without a mapped SDL_Joystick...
        const auto nullptr_it = std::find_if(map_it->second.begin(), map_it->second.end(),
                                             [](const std::shared_ptr<SDLJoystick>& joystick) {
                                                 return !joystick->GetSDLJoystick();
                                             });
        if (nullptr_it != map_it->second.end()) {
            // ... and map it
            (*nullptr_it)->SetSDLJoystick(sdl_joystick, sdl_controller);
            return *nullptr_it;
        }

        // There is no SDLJoystick without a mapped SDL_Joystick
        // Create a new SDLJoystick
        const int port = static_cast<int>(map_it->second.size());
        auto joystick = std::make_shared<SDLJoystick>(guid, port, sdl_joystick, sdl_controller);
        return map_it->second.emplace_back(std::move(joystick));
    }

    auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick, sdl_controller);
    return joystick_map[guid].emplace_back(std::move(joystick));
}

void SDLState::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 std::string guid = GetGUID(sdl_joystick);

    std::lock_guard lock{joystick_map_mutex};
    if (joystick_map.find(guid) == joystick_map.end()) {
        auto joystick = std::make_shared<SDLJoystick>(guid, 0, sdl_joystick, sdl_gamecontroller);
        joystick_map[guid].emplace_back(std::move(joystick));
        return;
    }
    auto& joystick_guid_list = joystick_map[guid];
    const auto it = std::find_if(
        joystick_guid_list.begin(), joystick_guid_list.end(),
        [](const std::shared_ptr<SDLJoystick>& joystick) { return !joystick->GetSDLJoystick(); });
    if (it != joystick_guid_list.end()) {
        (*it)->SetSDLJoystick(sdl_joystick, sdl_gamecontroller);
        return;
    }
    const int port = static_cast<int>(joystick_guid_list.size());
    auto joystick = std::make_shared<SDLJoystick>(guid, port, sdl_joystick, sdl_gamecontroller);
    joystick_guid_list.emplace_back(std::move(joystick));
}

void SDLState::CloseJoystick(SDL_Joystick* sdl_joystick) {
    const std::string guid = GetGUID(sdl_joystick);

    std::shared_ptr<SDLJoystick> joystick;
    {
        std::lock_guard 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 std::shared_ptr<SDLJoystick>& joystick) {
                             return joystick->GetSDLJoystick() == sdl_joystick;
                         });
        joystick = *joystick_it;
    }

    // Destruct SDL_Joystick outside the lock guard because SDL can internally call the
    // event callback which locks the mutex again.
    joystick->SetSDLJoystick(nullptr, nullptr);
}

void SDLState::HandleGameControllerEvent(const SDL_Event& event) {
    switch (event.type) {
    case SDL_JOYBUTTONUP: {
        if (auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
            joystick->SetButton(event.jbutton.button, false);
        }
        break;
    }
    case SDL_JOYBUTTONDOWN: {
        if (auto joystick = GetSDLJoystickBySDLID(event.jbutton.which)) {
            joystick->SetButton(event.jbutton.button, true);
        }
        break;
    }
    case SDL_JOYHATMOTION: {
        if (auto joystick = GetSDLJoystickBySDLID(event.jhat.which)) {
            joystick->SetHat(event.jhat.hat, event.jhat.value);
        }
        break;
    }
    case SDL_JOYAXISMOTION: {
        if (auto joystick = GetSDLJoystickBySDLID(event.jaxis.which)) {
            joystick->SetAxis(event.jaxis.axis, event.jaxis.value);
        }
        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 SDLState::CloseJoysticks() {
    std::lock_guard lock{joystick_map_mutex};
    joystick_map.clear();
}

class SDLButton final : public Input::ButtonDevice {
public:
    explicit SDLButton(std::shared_ptr<SDLJoystick> joystick_, int button_)
        : joystick(std::move(joystick_)), button(button_) {}

    bool GetStatus() const override {
        return joystick->GetButton(button);
    }

    bool SetRumblePlay(f32 amp_high, f32 amp_low, f32 freq_high, f32 freq_low) const override {
        const f32 new_amp_low = pow(amp_low, 0.5f) * (3.0f - 2.0f * pow(amp_low, 0.15f));
        const f32 new_amp_high = pow(amp_high, 0.5f) * (3.0f - 2.0f * pow(amp_high, 0.15f));
        return joystick->RumblePlay(new_amp_low, new_amp_high, 250);
    }

private:
    std::shared_ptr<SDLJoystick> joystick;
    int button;
};

class SDLDirectionButton final : public Input::ButtonDevice {
public:
    explicit SDLDirectionButton(std::shared_ptr<SDLJoystick> joystick_, int hat_, Uint8 direction_)
        : joystick(std::move(joystick_)), hat(hat_), direction(direction_) {}

    bool GetStatus() const override {
        return joystick->GetHatDirection(hat, direction);
    }

private:
    std::shared_ptr<SDLJoystick> joystick;
    int hat;
    Uint8 direction;
};

class SDLAxisButton final : public Input::ButtonDevice {
public:
    explicit SDLAxisButton(std::shared_ptr<SDLJoystick> joystick_, int axis_, float threshold_,
                           bool trigger_if_greater_)
        : joystick(std::move(joystick_)), axis(axis_), threshold(threshold_),
          trigger_if_greater(trigger_if_greater_) {}

    bool GetStatus() const override {
        const float axis_value = joystick->GetAxis(axis, 1.0f);
        if (trigger_if_greater) {
            return axis_value > threshold;
        }
        return axis_value < threshold;
    }

private:
    std::shared_ptr<SDLJoystick> joystick;
    int axis;
    float threshold;
    bool trigger_if_greater;
};

class SDLAnalog final : public Input::AnalogDevice {
public:
    SDLAnalog(std::shared_ptr<SDLJoystick> joystick_, int axis_x_, int axis_y_, float deadzone_,
              float range_)
        : joystick(std::move(joystick_)), axis_x(axis_x_), axis_y(axis_y_), deadzone(deadzone_),
          range(range_) {}

    std::tuple<float, float> GetStatus() const override {
        const auto [x, y] = joystick->GetAnalog(axis_x, axis_y, range);
        const float r = std::sqrt((x * x) + (y * y));
        if (r > deadzone) {
            return std::make_tuple(x / r * (r - deadzone) / (1 - deadzone),
                                   y / r * (r - deadzone) / (1 - deadzone));
        }
        return {};
    }

    bool GetAnalogDirectionStatus(Input::AnalogDirection direction) const override {
        const auto [x, y] = GetStatus();
        const float directional_deadzone = 0.5f;
        switch (direction) {
        case Input::AnalogDirection::RIGHT:
            return x > directional_deadzone;
        case Input::AnalogDirection::LEFT:
            return x < -directional_deadzone;
        case Input::AnalogDirection::UP:
            return y > directional_deadzone;
        case Input::AnalogDirection::DOWN:
            return y < -directional_deadzone;
        }
        return false;
    }

private:
    std::shared_ptr<SDLJoystick> joystick;
    const int axis_x;
    const int axis_y;
    const float deadzone;
    const float range;
};

/// A button device factory that creates button devices from SDL joystick
class SDLButtonFactory final : public Input::Factory<Input::ButtonDevice> {
public:
    explicit SDLButtonFactory(SDLState& state_) : state(state_) {}

    /**
     * Creates a button device from a joystick button
     * @param params contains parameters for creating the device:
     *     - "guid": the guid of the joystick to bind
     *     - "port": the nth joystick of the same type to bind
     *     - "button"(optional): the index of the button to bind
     *     - "hat"(optional): the index of the hat to bind as direction buttons
     *     - "axis"(optional): the index of the axis to bind
     *     - "direction"(only used for hat): the direction name of the hat to bind. Can be "up",
     *         "down", "left" or "right"
     *     - "threshold"(only used for axis): a float value in (-1.0, 1.0) which the button is
     *         triggered if the axis value crosses
     *     - "direction"(only used for axis): "+" means the button is triggered when the axis
     * value is greater than the threshold; "-" means the button is triggered when the axis
     * value is smaller than the threshold
     */
    std::unique_ptr<Input::ButtonDevice> Create(const Common::ParamPackage& params) override {
        const std::string guid = params.Get("guid", "0");
        const int port = params.Get("port", 0);

        auto joystick = state.GetSDLJoystickByGUID(guid, port);

        if (params.Has("hat")) {
            const int hat = params.Get("hat", 0);
            const std::string direction_name = params.Get("direction", "");
            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;
            }
            // This is necessary so accessing GetHat with hat won't crash
            joystick->SetHat(hat, SDL_HAT_CENTERED);
            return std::make_unique<SDLDirectionButton>(joystick, hat, direction);
        }

        if (params.Has("axis")) {
            const int axis = params.Get("axis", 0);
            const float threshold = params.Get("threshold", 0.5f);
            const std::string direction_name = params.Get("direction", "");
            bool trigger_if_greater;
            if (direction_name == "+") {
                trigger_if_greater = true;
            } else if (direction_name == "-") {
                trigger_if_greater = false;
            } else {
                trigger_if_greater = true;
                LOG_ERROR(Input, "Unknown direction {}", direction_name);
            }
            // This is necessary so accessing GetAxis with axis won't crash
            joystick->SetAxis(axis, 0);
            return std::make_unique<SDLAxisButton>(joystick, axis, threshold, trigger_if_greater);
        }

        const int button = params.Get("button", 0);
        // This is necessary so accessing GetButton with button won't crash
        joystick->SetButton(button, false);
        return std::make_unique<SDLButton>(joystick, button);
    }

private:
    SDLState& state;
};

/// An analog device factory that creates analog devices from SDL joystick
class SDLAnalogFactory final : public Input::Factory<Input::AnalogDevice> {
public:
    explicit SDLAnalogFactory(SDLState& state_) : state(state_) {}
    /**
     * Creates analog device from joystick axes
     * @param params contains parameters for creating the device:
     *     - "guid": the guid of the joystick to bind
     *     - "port": the nth joystick of the same type
     *     - "axis_x": the index of the axis to be bind as x-axis
     *     - "axis_y": the index of the axis to be bind as y-axis
     */
    std::unique_ptr<Input::AnalogDevice> Create(const Common::ParamPackage& params) override {
        const std::string guid = params.Get("guid", "0");
        const int port = params.Get("port", 0);
        const int axis_x = params.Get("axis_x", 0);
        const int axis_y = params.Get("axis_y", 1);
        const float deadzone = std::clamp(params.Get("deadzone", 0.0f), 0.0f, 1.0f);
        const float range = std::clamp(params.Get("range", 1.0f), 0.50f, 1.50f);
        auto joystick = state.GetSDLJoystickByGUID(guid, port);

        // This is necessary so accessing GetAxis with axis_x and axis_y won't crash
        joystick->SetAxis(axis_x, 0);
        joystick->SetAxis(axis_y, 0);
        return std::make_unique<SDLAnalog>(joystick, axis_x, axis_y, deadzone, range);
    }

private:
    SDLState& state;
};

SDLState::SDLState() {
    using namespace Input;
    analog_factory = std::make_shared<SDLAnalogFactory>(*this);
    button_factory = std::make_shared<SDLButtonFactory>(*this);
    RegisterFactory<AnalogDevice>("sdl", analog_factory);
    RegisterFactory<ButtonDevice>("sdl", button_factory);

    // If the frontend is going to manage the event loop, then we dont start one here
    start_thread = !SDL_WasInit(SDL_INIT_JOYSTICK);
    if (start_thread && SDL_Init(SDL_INIT_JOYSTICK) < 0) {
        LOG_CRITICAL(Input, "SDL_Init(SDL_INIT_JOYSTICK) failed with: {}", SDL_GetError());
        return;
    }
    has_gamecontroller = SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);
    if (SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1") == SDL_FALSE) {
        LOG_ERROR(Input, "Failed to set hint for background events with: {}", SDL_GetError());
    }

    SDL_AddEventWatch(&SDLEventWatcher, this);

    initialized = true;
    if (start_thread) {
        poll_thread = std::thread([this] {
            using namespace std::chrono_literals;
            while (initialized) {
                SDL_PumpEvents();
                std::this_thread::sleep_for(5ms);
            }
        });
    }
    // 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);
    }
}

SDLState::~SDLState() {
    using namespace Input;
    UnregisterFactory<ButtonDevice>("sdl");
    UnregisterFactory<AnalogDevice>("sdl");

    CloseJoysticks();
    SDL_DelEventWatch(&SDLEventWatcher, this);

    initialized = false;
    if (start_thread) {
        poll_thread.join();
        SDL_QuitSubSystem(SDL_INIT_JOYSTICK);
    }
}

std::vector<Common::ParamPackage> SDLState::GetInputDevices() {
    std::scoped_lock lock(joystick_map_mutex);
    std::vector<Common::ParamPackage> devices;
    for (const auto& [key, value] : joystick_map) {
        for (const auto& joystick : value) {
            auto joy = joystick->GetSDLJoystick();
            if (auto controller = joystick->GetSDLGameController()) {
                std::string name =
                    fmt::format("{} {}", SDL_GameControllerName(controller), joystick->GetPort());
                devices.emplace_back(Common::ParamPackage{
                    {"class", "sdl"},
                    {"display", std::move(name)},
                    {"guid", joystick->GetGUID()},
                    {"port", std::to_string(joystick->GetPort())},
                });
            } else if (joy) {
                std::string name = fmt::format("{} {}", SDL_JoystickName(joy), joystick->GetPort());
                devices.emplace_back(Common::ParamPackage{
                    {"class", "sdl"},
                    {"display", std::move(name)},
                    {"guid", joystick->GetGUID()},
                    {"port", std::to_string(joystick->GetPort())},
                });
            }
        }
    }
    return devices;
}

namespace {
Common::ParamPackage BuildAnalogParamPackageForButton(int port, std::string guid, u8 axis,
                                                      float value = 0.1f) {
    Common::ParamPackage params({{"engine", "sdl"}});
    params.Set("port", port);
    params.Set("guid", std::move(guid));
    params.Set("axis", axis);
    if (value > 0) {
        params.Set("direction", "+");
        params.Set("threshold", "0.5");
    } else {
        params.Set("direction", "-");
        params.Set("threshold", "-0.5");
    }
    return params;
}

Common::ParamPackage BuildButtonParamPackageForButton(int port, std::string guid, u8 button) {
    Common::ParamPackage params({{"engine", "sdl"}});
    params.Set("port", port);
    params.Set("guid", std::move(guid));
    params.Set("button", button);
    return params;
}

Common::ParamPackage BuildHatParamPackageForButton(int port, std::string guid, u8 hat, u8 value) {
    Common::ParamPackage params({{"engine", "sdl"}});

    params.Set("port", port);
    params.Set("guid", std::move(guid));
    params.Set("hat", hat);
    switch (value) {
    case SDL_HAT_UP:
        params.Set("direction", "up");
        break;
    case SDL_HAT_DOWN:
        params.Set("direction", "down");
        break;
    case SDL_HAT_LEFT:
        params.Set("direction", "left");
        break;
    case SDL_HAT_RIGHT:
        params.Set("direction", "right");
        break;
    default:
        return {};
    }
    return params;
}

Common::ParamPackage SDLEventToButtonParamPackage(SDLState& state, const SDL_Event& event) {
    switch (event.type) {
    case SDL_JOYAXISMOTION: {
        const auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
        return BuildAnalogParamPackageForButton(joystick->GetPort(), joystick->GetGUID(),
                                                event.jaxis.axis, event.jaxis.value);
    }
    case SDL_JOYBUTTONUP: {
        const auto joystick = state.GetSDLJoystickBySDLID(event.jbutton.which);
        return BuildButtonParamPackageForButton(joystick->GetPort(), joystick->GetGUID(),
                                                event.jbutton.button);
    }
    case SDL_JOYHATMOTION: {
        const auto joystick = state.GetSDLJoystickBySDLID(event.jhat.which);
        return BuildHatParamPackageForButton(joystick->GetPort(), joystick->GetGUID(),
                                             event.jhat.hat, event.jhat.value);
    }
    }
    return {};
}

Common::ParamPackage BuildParamPackageForBinding(int port, const std::string& guid,
                                                 const SDL_GameControllerButtonBind& binding) {
    switch (binding.bindType) {
    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,
                                             binding.value.hat.hat_mask);
    }
    return {};
}

Common::ParamPackage BuildParamPackageForAnalog(int port, const std::string& guid, int axis_x,
                                                int axis_y) {
    Common::ParamPackage params;
    params.Set("engine", "sdl");
    params.Set("port", port);
    params.Set("guid", guid);
    params.Set("axis_x", axis_x);
    params.Set("axis_y", axis_y);
    return params;
}
} // Anonymous namespace

ButtonMapping SDLState::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
    // This list also excludes Screenshot since theres not really a mapping for that
    using ButtonBindings =
        std::array<std::pair<Settings::NativeButton::Values, SDL_GameControllerButton>, 17>;
    static constexpr ButtonBindings switch_to_sdl_button{{
        {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::SL, SDL_CONTROLLER_BUTTON_LEFTSHOULDER},
        {Settings::NativeButton::SR, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER},
        {Settings::NativeButton::Home, SDL_CONTROLLER_BUTTON_GUIDE},
    }};

    // Add the missing bindings for ZL/ZR
    using ZBindings =
        std::array<std::pair<Settings::NativeButton::Values, SDL_GameControllerAxis>, 2>;
    static constexpr ZBindings switch_to_sdl_axis{{
        {Settings::NativeButton::ZL, SDL_CONTROLLER_AXIS_TRIGGERLEFT},
        {Settings::NativeButton::ZR, SDL_CONTROLLER_AXIS_TRIGGERRIGHT},
    }};

    ButtonMapping mapping;
    mapping.reserve(switch_to_sdl_button.size() + switch_to_sdl_axis.size());

    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;
}

AnalogMapping SDLState::GetAnalogMappingForDevice(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 {};
    }

    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);
    mapping.insert_or_assign(Settings::NativeAnalog::LStick,
                             BuildParamPackageForAnalog(joystick->GetPort(), joystick->GetGUID(),
                                                        binding_left_x.value.axis,
                                                        binding_left_y.value.axis));
    const auto& binding_right_x =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX);
    const auto& binding_right_y =
        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY);
    mapping.insert_or_assign(Settings::NativeAnalog::RStick,
                             BuildParamPackageForAnalog(joystick->GetPort(), joystick->GetGUID(),
                                                        binding_right_x.value.axis,
                                                        binding_right_y.value.axis));
    return mapping;
}

namespace Polling {
class SDLPoller : public InputCommon::Polling::DevicePoller {
public:
    explicit SDLPoller(SDLState& state_) : state(state_) {}

    void Start(const std::string& device_id) override {
        state.event_queue.Clear();
        state.polling = true;
    }

    void Stop() override {
        state.polling = false;
    }

protected:
    SDLState& state;
};

class SDLButtonPoller final : public SDLPoller {
public:
    explicit SDLButtonPoller(SDLState& state_) : SDLPoller(state_) {}

    Common::ParamPackage GetNextInput() override {
        SDL_Event event;
        while (state.event_queue.Pop(event)) {
            const auto package = FromEvent(event);
            if (package) {
                return *package;
            }
        }
        return {};
    }
    [[nodiscard]] std::optional<Common::ParamPackage> FromEvent(const SDL_Event& event) const {
        switch (event.type) {
        case SDL_JOYAXISMOTION:
            if (std::abs(event.jaxis.value / 32767.0) < 0.5) {
                break;
            }
            [[fallthrough]];
        case SDL_JOYBUTTONUP:
        case SDL_JOYHATMOTION:
            return {SDLEventToButtonParamPackage(state, event)};
        }
        return std::nullopt;
    }
};

/**
 * Attempts to match the press to a controller joy axis (left/right stick) and if a match
 * isn't found, checks if the event matches anything from SDLButtonPoller and uses that
 * instead
 */
class SDLAnalogPreferredPoller final : public SDLPoller {
public:
    explicit SDLAnalogPreferredPoller(SDLState& state_)
        : SDLPoller(state_), button_poller(state_) {}

    void Start(const std::string& device_id) override {
        SDLPoller::Start(device_id);
        // Load the game controller
        // Reset stored axes
        analog_x_axis = -1;
        analog_y_axis = -1;
    }

    Common::ParamPackage GetNextInput() override {
        SDL_Event event;
        while (state.event_queue.Pop(event)) {
            // Filter out axis events that are below a threshold
            if (event.type == SDL_JOYAXISMOTION && std::abs(event.jaxis.value / 32767.0) < 0.5) {
                continue;
            }
            // Simplify controller config by testing if game controller support is enabled.
            if (event.type == SDL_JOYAXISMOTION) {
                const auto axis = event.jaxis.axis;
                const auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
                const auto controller = joystick->GetSDLGameController();
                if (controller) {
                    const auto axis_left_x =
                        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTX)
                            .value.axis;
                    const auto axis_left_y =
                        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_LEFTY)
                            .value.axis;
                    const auto axis_right_x =
                        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTX)
                            .value.axis;
                    const auto axis_right_y =
                        SDL_GameControllerGetBindForAxis(controller, SDL_CONTROLLER_AXIS_RIGHTY)
                            .value.axis;

                    if (axis == axis_left_x || axis == axis_left_y) {
                        analog_x_axis = axis_left_x;
                        analog_y_axis = axis_left_y;
                        break;
                    } else if (axis == axis_right_x || axis == axis_right_y) {
                        analog_x_axis = axis_right_x;
                        analog_y_axis = axis_right_y;
                        break;
                    }
                }
            }

            // If the press wasn't accepted as a joy axis, check for a button press
            auto button_press = button_poller.FromEvent(event);
            if (button_press) {
                return *button_press;
            }
        }

        if (analog_x_axis != -1 && analog_y_axis != -1) {
            const auto joystick = state.GetSDLJoystickBySDLID(event.jaxis.which);
            auto params = BuildParamPackageForAnalog(joystick->GetPort(), joystick->GetGUID(),
                                                     analog_x_axis, analog_y_axis);
            analog_x_axis = -1;
            analog_y_axis = -1;
            return params;
        }
        return {};
    }

private:
    int analog_x_axis = -1;
    int analog_y_axis = -1;
    SDLButtonPoller button_poller;
};
} // namespace Polling

SDLState::Pollers SDLState::GetPollers(InputCommon::Polling::DeviceType type) {
    Pollers pollers;

    switch (type) {
    case InputCommon::Polling::DeviceType::AnalogPreferred:
        pollers.emplace_back(std::make_unique<Polling::SDLAnalogPreferredPoller>(*this));
        break;
    case InputCommon::Polling::DeviceType::Button:
        pollers.emplace_back(std::make_unique<Polling::SDLButtonPoller>(*this));
        break;
    }

    return pollers;
}

} // namespace InputCommon::SDL