SDL: Split the Windows joystick driver into DirectInput and XInput drivers

From 9906a4e3897bb29582be769b99d82d16522c0743 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Fri, 30 Oct 2026 06:10:02 -0700
Subject: [PATCH] Split the Windows joystick driver into DirectInput and XInput
 drivers

This reduces hotplug responsiveness for XInput, but I plan to create a unified Windows device hotplug thread that will take care of that.
---
 VisualC-GDK/SDL/SDL.vcxproj                  |   11 -
 VisualC-GDK/SDL/SDL.vcxproj.filters          |    4 +-
 VisualC/SDL/SDL.vcxproj                      |    2 -
 VisualC/SDL/SDL.vcxproj.filters              |    6 -
 src/haptic/windows/SDL_dinputhaptic.c        |    2 +-
 src/haptic/windows/SDL_windowshaptic.c       |    8 +-
 src/joystick/SDL_joystick.c                  |    8 +-
 src/joystick/SDL_sysjoystick.h               |    4 +-
 src/joystick/windows/SDL_dinputjoystick.c    | 1001 ++++++++++++------
 src/joystick/windows/SDL_dinputjoystick_c.h  |   64 +-
 src/joystick/windows/SDL_windowsjoystick.c   |  653 ------------
 src/joystick/windows/SDL_windowsjoystick_c.h |  107 --
 src/joystick/windows/SDL_xinputjoystick.c    |  446 +++++---
 src/joystick/windows/SDL_xinputjoystick_c.h  |   11 -
 14 files changed, 1051 insertions(+), 1276 deletions(-)
 delete mode 100644 src/joystick/windows/SDL_windowsjoystick.c
 delete mode 100644 src/joystick/windows/SDL_windowsjoystick_c.h

diff --git a/VisualC-GDK/SDL/SDL.vcxproj b/VisualC-GDK/SDL/SDL.vcxproj
index b15183702ce5c..007656b18c806 100644
--- a/VisualC-GDK/SDL/SDL.vcxproj
+++ b/VisualC-GDK/SDL/SDL.vcxproj
@@ -477,7 +477,6 @@
     <ClInclude Include="..\..\src\joystick\usb_ids.h" />
     <ClInclude Include="..\..\src\joystick\virtual\SDL_virtualjoystick_c.h" />
     <ClInclude Include="..\..\src\joystick\windows\SDL_dinputjoystick_c.h" />
-    <ClInclude Include="..\..\src\joystick\windows\SDL_windowsjoystick_c.h" />
     <ClInclude Include="..\..\src\joystick\windows\SDL_xinputjoystick_c.h" />
     <ClInclude Include="..\..\src\libm\math_libm.h" />
     <ClInclude Include="..\..\src\libm\math_private.h" />
@@ -755,16 +754,6 @@
     <ClCompile Include="..\..\src\joystick\SDL_steam_virtual_gamepad.c" />
     <ClCompile Include="..\..\src\joystick\virtual\SDL_virtualjoystick.c" />
     <ClCompile Include="..\..\src\joystick\windows\SDL_dinputjoystick.c" />
-    <ClCompile Include="..\..\src\joystick\windows\SDL_windowsjoystick.c">
-      <CompileAs Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Xbox.Scarlett.x64'">CompileAsCpp</CompileAs>
-      <CompileAs Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Xbox.XboxOne.x64'">CompileAsCpp</CompileAs>
-      <CompileAs Condition="'$(Configuration)|$(Platform)'=='Release|Gaming.Xbox.Scarlett.x64'">CompileAsCpp</CompileAs>
-      <CompileAs Condition="'$(Configuration)|$(Platform)'=='Release|Gaming.Xbox.XboxOne.x64'">CompileAsCpp</CompileAs>
-      <LanguageStandard Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Xbox.Scarlett.x64'">stdcpp17</LanguageStandard>
-      <LanguageStandard Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Xbox.XboxOne.x64'">stdcpp17</LanguageStandard>
-      <LanguageStandard Condition="'$(Configuration)|$(Platform)'=='Release|Gaming.Xbox.Scarlett.x64'">stdcpp17</LanguageStandard>
-      <LanguageStandard Condition="'$(Configuration)|$(Platform)'=='Release|Gaming.Xbox.XboxOne.x64'">stdcpp17</LanguageStandard>
-    </ClCompile>
     <ClCompile Include="..\..\src\joystick\windows\SDL_xinputjoystick.c">
       <LanguageStandard Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Xbox.Scarlett.x64'">stdcpp17</LanguageStandard>
       <LanguageStandard Condition="'$(Configuration)|$(Platform)'=='Debug|Gaming.Xbox.XboxOne.x64'">stdcpp17</LanguageStandard>
diff --git a/VisualC-GDK/SDL/SDL.vcxproj.filters b/VisualC-GDK/SDL/SDL.vcxproj.filters
index e4fa308ce7591..9c15e702ba6c8 100644
--- a/VisualC-GDK/SDL/SDL.vcxproj.filters
+++ b/VisualC-GDK/SDL/SDL.vcxproj.filters
@@ -103,7 +103,6 @@
     <ClCompile Include="..\..\src\joystick\SDL_steam_virtual_gamepad.c" />
     <ClCompile Include="..\..\src\joystick\virtual\SDL_virtualjoystick.c" />
     <ClCompile Include="..\..\src\joystick\windows\SDL_dinputjoystick.c" />
-    <ClCompile Include="..\..\src\joystick\windows\SDL_windowsjoystick.c" />
     <ClCompile Include="..\..\src\joystick\windows\SDL_xinputjoystick.c" />
     <ClCompile Include="..\..\src\libm\s_modf.c" />
     <ClCompile Include="..\..\src\loadso\windows\SDL_sysloadso.c" />
@@ -390,7 +389,6 @@
     <ClInclude Include="..\..\src\joystick\usb_ids.h" />
     <ClInclude Include="..\..\src\joystick\virtual\SDL_virtualjoystick_c.h" />
     <ClInclude Include="..\..\src\joystick\windows\SDL_dinputjoystick_c.h" />
-    <ClInclude Include="..\..\src\joystick\windows\SDL_windowsjoystick_c.h" />
     <ClInclude Include="..\..\src\joystick\windows\SDL_xinputjoystick_c.h" />
     <ClInclude Include="..\..\src\libm\math_libm.h" />
     <ClInclude Include="..\..\src\libm\math_private.h" />
@@ -517,4 +515,4 @@
   <ItemGroup>
     <ResourceCompile Include="..\..\src\core\windows\version.rc" />
   </ItemGroup>
-</Project>
\ No newline at end of file
+</Project>
diff --git a/VisualC/SDL/SDL.vcxproj b/VisualC/SDL/SDL.vcxproj
index 15a63c6c9a7c9..26c983f6e89fd 100644
--- a/VisualC/SDL/SDL.vcxproj
+++ b/VisualC/SDL/SDL.vcxproj
@@ -515,7 +515,6 @@
     <ClInclude Include="..\..\src\joystick\usb_ids.h" />
     <ClInclude Include="..\..\src\joystick\virtual\SDL_virtualjoystick_c.h" />
     <ClInclude Include="..\..\src\joystick\windows\SDL_dinputjoystick_c.h" />
-    <ClInclude Include="..\..\src\joystick\windows\SDL_windowsjoystick_c.h" />
     <ClInclude Include="..\..\src\joystick\windows\SDL_xinputjoystick_c.h" />
     <ClInclude Include="..\..\src\libm\math_libm.h" />
     <ClInclude Include="..\..\src\libm\math_private.h" />
@@ -859,7 +858,6 @@
     <ClCompile Include="..\..\src\joystick\SDL_steam_virtual_gamepad.c" />
     <ClCompile Include="..\..\src\joystick\virtual\SDL_virtualjoystick.c" />
     <ClCompile Include="..\..\src\joystick\windows\SDL_dinputjoystick.c" />
-    <ClCompile Include="..\..\src\joystick\windows\SDL_windowsjoystick.c" />
     <ClCompile Include="..\..\src\joystick\windows\SDL_xinputjoystick.c" />
     <ClCompile Include="..\..\src\libm\s_modf.c" />
     <ClCompile Include="..\..\src\loadso\windows\SDL_sysloadso.c" />
diff --git a/VisualC/SDL/SDL.vcxproj.filters b/VisualC/SDL/SDL.vcxproj.filters
index bc125d39a1c11..bcc2ea585011c 100644
--- a/VisualC/SDL/SDL.vcxproj.filters
+++ b/VisualC/SDL/SDL.vcxproj.filters
@@ -690,9 +690,6 @@
     <ClInclude Include="..\..\src\joystick\windows\SDL_dinputjoystick_c.h">
       <Filter>joystick\windows</Filter>
     </ClInclude>
-    <ClInclude Include="..\..\src\joystick\windows\SDL_windowsjoystick_c.h">
-      <Filter>joystick\windows</Filter>
-    </ClInclude>
     <ClInclude Include="..\..\src\joystick\windows\SDL_xinputjoystick_c.h">
       <Filter>joystick\windows</Filter>
     </ClInclude>
@@ -1672,9 +1669,6 @@
     <ClCompile Include="..\..\src\joystick\windows\SDL_dinputjoystick.c">
       <Filter>joystick\windows</Filter>
     </ClCompile>
-    <ClCompile Include="..\..\src\joystick\windows\SDL_windowsjoystick.c">
-      <Filter>joystick\windows</Filter>
-    </ClCompile>
     <ClCompile Include="..\..\src\joystick\windows\SDL_xinputjoystick.c">
       <Filter>joystick\windows</Filter>
     </ClCompile>
diff --git a/src/haptic/windows/SDL_dinputhaptic.c b/src/haptic/windows/SDL_dinputhaptic.c
index ce0bd30969f62..5f82471336f3d 100644
--- a/src/haptic/windows/SDL_dinputhaptic.c
+++ b/src/haptic/windows/SDL_dinputhaptic.c
@@ -26,7 +26,7 @@
 
 #include "SDL_windowshaptic_c.h"
 #include "SDL_dinputhaptic_c.h"
-#include "../../joystick/windows/SDL_windowsjoystick_c.h"
+#include "../../joystick/windows/SDL_dinputjoystick_c.h"
 
 /*
  * External stuff.
diff --git a/src/haptic/windows/SDL_windowshaptic.c b/src/haptic/windows/SDL_windowshaptic.c
index e58faad410fce..15689b9657bc9 100644
--- a/src/haptic/windows/SDL_windowshaptic.c
+++ b/src/haptic/windows/SDL_windowshaptic.c
@@ -24,7 +24,7 @@
 
 #include "../SDL_syshaptic.h"
 #include "../../joystick/SDL_sysjoystick.h"               // For the real SDL_Joystick
-#include "../../joystick/windows/SDL_windowsjoystick_c.h" // For joystick hwdata
+#include "../../joystick/windows/SDL_dinputjoystick_c.h" // For joystick hwdata
 #include "../../joystick/windows/SDL_xinputjoystick_c.h"  // For xinput rumble
 
 #include "SDL_windowshaptic_c.h"
@@ -182,7 +182,7 @@ int SDL_SYS_HapticMouse(void)
  */
 bool SDL_SYS_JoystickIsHaptic(SDL_Joystick *joystick)
 {
-    if (joystick->driver != &SDL_WINDOWS_JoystickDriver) {
+    if (joystick->driver != &SDL_DINPUT_JoystickDriver) {
         return false;
     }
     if (joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) {
@@ -196,7 +196,7 @@ bool SDL_SYS_JoystickIsHaptic(SDL_Joystick *joystick)
  */
 bool SDL_SYS_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick)
 {
-    if (joystick->driver != &SDL_WINDOWS_JoystickDriver) {
+    if (joystick->driver != &SDL_DINPUT_JoystickDriver) {
         return false;
     }
     return SDL_DINPUT_JoystickSameHaptic(haptic, joystick);
@@ -207,7 +207,7 @@ bool SDL_SYS_JoystickSameHaptic(SDL_Haptic *haptic, SDL_Joystick *joystick)
  */
 bool SDL_SYS_HapticOpenFromJoystick(SDL_Haptic *haptic, SDL_Joystick *joystick)
 {
-    SDL_assert(joystick->driver == &SDL_WINDOWS_JoystickDriver);
+    SDL_assert(joystick->driver == &SDL_DINPUT_JoystickDriver);
 
     return SDL_DINPUT_HapticOpenFromJoystick(haptic, joystick);
 }
diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c
index 1a0a11adf778f..884d3468230e6 100644
--- a/src/joystick/SDL_joystick.c
+++ b/src/joystick/SDL_joystick.c
@@ -58,11 +58,11 @@ static SDL_JoystickDriver *SDL_joystick_drivers[] = {
 #ifdef SDL_JOYSTICK_GAMEINPUT // Higher priority than other Windows drivers
     &SDL_GAMEINPUT_JoystickDriver,
 #endif
-#if defined(SDL_JOYSTICK_DINPUT) || defined(SDL_JOYSTICK_XINPUT)
-    &SDL_WINDOWS_JoystickDriver,
+#if defined(SDL_JOYSTICK_XINPUT)
+    &SDL_XINPUT_JoystickDriver,
 #endif
-#ifdef SDL_JOYSTICK_WINMM
-    &SDL_WINMM_JoystickDriver,
+#if defined(SDL_JOYSTICK_DINPUT)
+    &SDL_DINPUT_JoystickDriver,
 #endif
 #ifdef SDL_JOYSTICK_LINUX
     &SDL_LINUX_JoystickDriver,
diff --git a/src/joystick/SDL_sysjoystick.h b/src/joystick/SDL_sysjoystick.h
index 7adcc9408e2c3..763e754cdef05 100644
--- a/src/joystick/SDL_sysjoystick.h
+++ b/src/joystick/SDL_sysjoystick.h
@@ -264,8 +264,8 @@ extern SDL_JoystickDriver SDL_HIDAPI_JoystickDriver;
 extern SDL_JoystickDriver SDL_IOS_JoystickDriver;
 extern SDL_JoystickDriver SDL_LINUX_JoystickDriver;
 extern SDL_JoystickDriver SDL_VIRTUAL_JoystickDriver;
-extern SDL_JoystickDriver SDL_WINDOWS_JoystickDriver;
-extern SDL_JoystickDriver SDL_WINMM_JoystickDriver;
+extern SDL_JoystickDriver SDL_XINPUT_JoystickDriver;
+extern SDL_JoystickDriver SDL_DINPUT_JoystickDriver;
 extern SDL_JoystickDriver SDL_PS2_JoystickDriver;
 extern SDL_JoystickDriver SDL_PSP_JoystickDriver;
 extern SDL_JoystickDriver SDL_VITA_JoystickDriver;
diff --git a/src/joystick/windows/SDL_dinputjoystick.c b/src/joystick/windows/SDL_dinputjoystick.c
index ce3e5965c7323..c50297bbbb1b1 100644
--- a/src/joystick/windows/SDL_dinputjoystick.c
+++ b/src/joystick/windows/SDL_dinputjoystick.c
@@ -20,32 +20,61 @@
 */
 #include "SDL_internal.h"
 
-#include "../SDL_sysjoystick.h"
+/* DirectInput joystick driver; written by Glenn Maynard, based on Andrei de
+ * A. Formiga's WINMM driver.
+ *
+ * Hats and sliders are completely untested; the app I'm writing this for mostly
+ * doesn't use them and I don't own any joysticks with them.
+ *
+ * We don't bother to use event notification here.  It doesn't seem to work
+ * with polled devices, and it's fine to call IDirectInputDevice8_GetDeviceData and
+ * let it return 0 events. */
 
 #ifdef SDL_JOYSTICK_DINPUT
 
-#include "SDL_windowsjoystick_c.h"
-#include "SDL_dinputjoystick_c.h"
-#include "SDL_xinputjoystick_c.h"
 #include "../../core/windows/SDL_gameinput.h"
 #include "../hidapi/SDL_hidapijoystick_c.h"
+#include "../../thread/SDL_systhread.h"
+#include "../../core/windows/SDL_windows.h"
+#include "../../core/windows/SDL_hid.h"
+#include <dbt.h>
+
+#define INITGUID // Only set here, if set twice will cause mingw32 to break.
+#include "SDL_dinputjoystick_c.h"
+#include "SDL_xinputjoystick_c.h"
+
+#include "../../haptic/windows/SDL_dinputhaptic_c.h" // For haptic hot plugging
+
+#ifndef DEVICE_NOTIFY_WINDOW_HANDLE
+#define DEVICE_NOTIFY_WINDOW_HANDLE 0x00000000
+#endif
 
 #ifndef DIDFT_OPTIONAL
 #define DIDFT_OPTIONAL 0x80000000
 #endif
 
-#define INPUT_QSIZE        128                                                         // Buffer up to 128 input messages
+#define INPUT_QSIZE 128 // Buffer up to 128 input messages
 #define JOY_AXIS_THRESHOLD (((SDL_JOYSTICK_AXIS_MAX) - (SDL_JOYSTICK_AXIS_MIN)) / 100) // 1% motion
 
-#define CONVERT_MAGNITUDE(x) (((x)*10000) / 0x7FFF)
-
-// external variables referenced.
-extern HWND SDL_HelperWindow;
+#define CONVERT_MAGNITUDE(x) (((x) * 10000) / 0x7FFF)
 
 // local variables
+static bool s_bJoystickThread = false;
+static SDL_Condition *s_condJoystickThread = NULL;
+static SDL_Mutex *s_mutexJoyStickEnum = NULL;
+static SDL_Thread *s_joystickThread = NULL;
+static bool s_bJoystickThreadQuit = false;
+static Uint64 s_lastDeviceChange = 0;
+static GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2L, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } };
+static bool notification_initialized = true;
 static bool coinitialized = false;
 static LPDIRECTINPUT8 dinput = NULL;
 
+JoyStick_DeviceData *SYS_Joystick; // array to hold joystick ID values
+
+// external variables referenced.
+extern HWND SDL_HelperWindow;
+
 // Taken from Wine - Thanks!
 static DIOBJECTDATAFORMAT dfDIJoystick2[] = {
     { &GUID_XAxis, DIJOFS_X, DIDFT_OPTIONAL | DIDFT_AXIS | DIDFT_ANYINSTANCE, DIDOI_ASPECTPOSITION },
@@ -226,6 +255,9 @@ const DIDATAFORMAT SDL_c_dfDIJoystick2 = {
     dfDIJoystick2
 };
 
+static void DINPUT_JoystickDetect(void);
+static void DINPUT_JoystickQuit(void);
+
 // Convert a DirectInput return code to a text message
 static bool SetDIerror(const char *function, HRESULT code)
 {
@@ -340,7 +372,7 @@ static bool QueryDeviceInfo(LPDIRECTINPUTDEVICE8 device, Uint16 *vendor_id, Uint
     return true;
 }
 
-void FreeRumbleEffectData(DIEFFECT *effect)
+static void FreeRumbleEffectData(DIEFFECT *effect)
 {
     if (!effect) {
         return;
@@ -351,7 +383,7 @@ void FreeRumbleEffectData(DIEFFECT *effect)
     SDL_free(effect);
 }
 
-DIEFFECT *CreateRumbleEffectData(Sint16 magnitude)
+static DIEFFECT *CreateRumbleEffectData(Sint16 magnitude)
 {
     DIEFFECT *effect;
     DIPERIODIC *periodic;
@@ -395,48 +427,6 @@ DIEFFECT *CreateRumbleEffectData(Sint16 magnitude)
     return effect;
 }
 
-bool SDL_DINPUT_JoystickInit(void)
-{
-    HRESULT result;
-    HINSTANCE instance;
-
-    if (!SDL_GetHintBoolean(SDL_HINT_JOYSTICK_DIRECTINPUT, true)) {
-        // In some environments, IDirectInput8_Initialize / _EnumDevices can take a minute even with no controllers.
-        dinput = NULL;
-        return true;
-    }
-
-    result = WIN_CoInitialize();
-    if (FAILED(result)) {
-        return SetDIerror("CoInitialize", result);
-    }
-
-    coinitialized = true;
-
-    result = CoCreateInstance(&CLSID_DirectInput8, NULL, CLSCTX_INPROC_SERVER,
-                              &IID_IDirectInput8, (LPVOID *)&dinput);
-
-    if (FAILED(result)) {
-        return SetDIerror("CoCreateInstance", result);
-    }
-
-    // Because we used CoCreateInstance, we need to Initialize it, first.
-    instance = GetModuleHandle(NULL);
-    if (!instance) {
-        IDirectInput8_Release(dinput);
-        dinput = NULL;
-        return SDL_SetError("GetModuleHandle() failed with error code %" SDL_PRIuULONG ".", GetLastError());
-    }
-    result = IDirectInput8_Initialize(dinput, instance, DIRECTINPUT_VERSION);
-
-    if (FAILED(result)) {
-        IDirectInput8_Release(dinput);
-        dinput = NULL;
-        return SetDIerror("IDirectInput::Initialize", result);
-    }
-    return true;
-}
-
 static int GetSteamVirtualGamepadSlot(Uint16 vendor_id, Uint16 product_id, const char *device_path)
 {
     int slot = -1;
@@ -476,7 +466,7 @@ static BOOL CALLBACK EnumJoystickDetectCallback(LPCDIDEVICEINSTANCE pDeviceInsta
 
     CHECK(!SDL_IsXInputDevice(vendor, product, hidPath));
     CHECK(!SDL_ShouldIgnoreJoystick(vendor, product, version, product_string));
-    CHECK(!SDL_JoystickHandledByAnotherDriver(&SDL_WINDOWS_JoystickDriver, vendor, product, version, product_string));
+    CHECK(!SDL_JoystickHandledByAnotherDriver(&SDL_DINPUT_JoystickDriver, vendor, product, version, product_string));
 
     pNewJoystick = *(JoyStick_DeviceData **)pContext;
     while (pNewJoystick) {
@@ -519,7 +509,10 @@ static BOOL CALLBACK EnumJoystickDetectCallback(LPCDIDEVICEINSTANCE pDeviceInsta
         pNewJoystick->guid = SDL_CreateJoystickGUID(SDL_HARDWARE_BUS_BLUETOOTH, vendor, product, version, manufacturer_string, product_string, 0, 0);
     }
 
-    WINDOWS_AddJoystickDevice(pNewJoystick);
+    pNewJoystick->send_add_event = true;
+    pNewJoystick->nInstanceID = SDL_GetNextObjectID();
+    pNewJoystick->pNext = SYS_Joystick;
+    SYS_Joystick = pNewJoystick;
     pNewJoystick = NULL;
 
 err:
@@ -540,15 +533,6 @@ static BOOL CALLBACK EnumJoystickDetectCallback(LPCDIDEVICEINSTANCE pDeviceInsta
 #undef CHECK
 }
 
-void SDL_DINPUT_JoystickDetect(JoyStick_DeviceData **pContext)
-{
-    if (!dinput) {
-        return;
-    }
-
-    IDirectInput8_EnumDevices(dinput, DI8DEVCLASS_GAMECTRL, EnumJoystickDetectCallback, pContext, DIEDFL_ATTACHEDONLY);
-}
-
 // helper function for direct input, gets called for each connected joystick
 typedef struct
 {
@@ -590,21 +574,6 @@ static BOOL CALLBACK EnumJoystickPresentCallback(LPCDIDEVICEINSTANCE pDeviceInst
 #undef CHECK
 }
 
-bool SDL_DINPUT_JoystickPresent(Uint16 vendor_id, Uint16 product_id, Uint16 version_number)
-{
-    Joystick_PresentData data;
-
-    if (!dinput) {
-        return false;
-    }
-
-    data.vendor = vendor_id;
-    data.product = product_id;
-    data.present = false;
-    IDirectInput8_EnumDevices(dinput, DI8DEVCLASS_GAMECTRL, EnumJoystickPresentCallback, &data, DIEDFL_ATTACHEDONLY);
-    return data.present;
-}
-
 static BOOL CALLBACK EnumDevObjectsCallback(LPCDIDEVICEOBJECTINSTANCE pDeviceObject, LPVOID pContext)
 {
     SDL_Joystick *joystick = (SDL_Joystick *)pContext;
@@ -740,137 +709,7 @@ static void SortDevObjects(SDL_Joystick *joystick)
     }
 }
 
-bool SDL_DINPUT_JoystickOpen(SDL_Joystick *joystick, JoyStick_DeviceData *joystickdevice)
-{
-    HRESULT result;
-    DIPROPDWORD dipdw;
-
-    joystick->hwdata->buffered = true;
-    joystick->hwdata->Capabilities.dwSize = sizeof(DIDEVCAPS);
-
-    SDL_zero(dipdw);
-    dipdw.diph.dwSize = sizeof(DIPROPDWORD);
-    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
-
-    result =
-        IDirectInput8_CreateDevice(dinput,
-                                   &joystickdevice->dxdevice.guidInstance,
-                                   &joystick->hwdata->InputDevice,
-                                   NULL);
-    if (FAILED(result)) {
-        return SetDIerror("IDirectInput::CreateDevice", result);
-    }
-
-    /* Acquire shared access. Exclusive access is required for forces,
-     * though. */
-    result =
-        IDirectInputDevice8_SetCooperativeLevel(joystick->hwdata->InputDevice, SDL_HelperWindow,
-                                                DISCL_EXCLUSIVE |
-                                                    DISCL_BACKGROUND);
-    if (FAILED(result)) {
-        return SetDIerror("IDirectInputDevice8::SetCooperativeLevel", result);
-    }
-
-    // Use the extended data structure: DIJOYSTATE2.
-    result =
-        IDirectInputDevice8_SetDataFormat(joystick->hwdata->InputDevice,
-                                          &SDL_c_dfDIJoystick2);
-    if (FAILED(result)) {
-        return SetDIerror("IDirectInputDevice8::SetDataFormat", result);
-    }
-
-    if (!WIN_HasBrokenEZFRD64DLL()) {
-        // Get device capabilities to see if we are force feedback capable
-        result =
-            IDirectInputDevice8_GetCapabilities(joystick->hwdata->InputDevice,
-                                                &joystick->hwdata->Capabilities);
-        if (FAILED(result)) {
-            return SetDIerror("IDirectInputDevice8::GetCapabilities", result);
-        }
-    }
-
-    // Force capable?
-    if (joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK) {
-        result = IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice);
-        if (FAILED(result)) {
-            return SetDIerror("IDirectInputDevice8::Acquire", result);
-        }
-
-        // reset all actuators.
-        result =
-            IDirectInputDevice8_SendForceFeedbackCommand(joystick->hwdata->InputDevice,
-                                                         DISFFC_RESET);
-
-        /* Not necessarily supported, ignore if not supported.
-        if (FAILED(result)) {
-        return SetDIerror("IDirectInputDevice8::SendForceFeedbackCommand", result);
-        }
-        */
-
-        result = IDirectInputDevice8_Unacquire(joystick->hwdata->InputDevice);
-
-        if (FAILED(result)) {
-            return SetDIerror("IDirectInputDevice8::Unacquire", result);
-        }
-
-        /* Turn on auto-centering for a ForceFeedback device (until told
-         * otherwise). */
-        dipdw.diph.dwObj = 0;
-        dipdw.diph.dwHow = DIPH_DEVICE;
-        dipdw.dwData = DIPROPAUTOCENTER_ON;
-
-        result =
-            IDirectInputDevice8_SetProperty(joystick->hwdata->InputDevice,
-                                            DIPROP_AUTOCENTER, &dipdw.diph);
-
-        /* Not necessarily supported, ignore if not supported.
-        if (FAILED(result)) {
-        return SetDIerror("IDirectInputDevice8::SetProperty", result);
-        }
-        */
-
-        SDL_SetBooleanProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CAP_RUMBLE_BOOLEAN, true);
-    }
-
-    // What buttons and axes does it have?
-    IDirectInputDevice8_EnumObjects(joystick->hwdata->InputDevice,
-                                    EnumDevObjectsCallback, joystick,
-                                    DIDFT_BUTTON | DIDFT_AXIS | DIDFT_POV);
-
-    /* Reorder the input objects. Some devices do not report the X axis as
-     * the first axis, for example. */
-    SortDevObjects(joystick);
-
-    dipdw.diph.dwObj = 0;
-    dipdw.diph.dwHow = DIPH_DEVICE;
-    dipdw.dwData = INPUT_QSIZE;
-
-    // Set the buffer size
-    result =
-        IDirectInputDevice8_SetProperty(joystick->hwdata->InputDevice,
-                                        DIPROP_BUFFERSIZE, &dipdw.diph);
-
-    if (result == DI_POLLEDDEVICE) {
-        /* This device doesn't support buffering, so we're forced
-         * to use less reliable polling. */
-        joystick->hwdata->buffered = false;
-    } else if (FAILED(result)) {
-        return SetDIerror("IDirectInputDevice8::SetProperty", result);
-    }
-    joystick->hwdata->first_update = true;
-
-    // Poll and wait for initial device state to be populated
-    result = IDirectInputDevice8_Poll(joystick->hwdata->InputDevice);
-    if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
-        IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice);
-        IDirectInputDevice8_Poll(joystick->hwdata->InputDevice);
-    }
-    SDL_Delay(50);
-
-    return true;
-}
-
-static bool SDL_DINPUT_JoystickInitRumble(SDL_Joystick *joystick, Sint16 magnitude)
+static bool DINPUT_JoystickInitRumble(SDL_Joystick *joystick, Sint16 magnitude)
 {
     HRESULT result;
 
@@ -905,51 +744,6 @@ static bool SDL_DINPUT_JoystickInitRumble(SDL_Joystick *joystick, Sint16 magnitu
     return true;
 }
 
-bool SDL_DINPUT_JoystickRumble(SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
-{
-    HRESULT result;
-
-    // Scale and average the two rumble strengths
-    Sint16 magnitude = (Sint16)(((low_frequency_rumble / 2) + (high_frequency_rumble / 2)) / 2);
-
-    if (!(joystick->hwdata->Capabilities.dwFlags & DIDC_FORCEFEEDBACK)) {
-        return SDL_Unsupported();
-    }
-
-    if (joystick->hwdata->ff_initialized) {
-        DIPERIODIC *periodic = ((DIPERIODIC *)joystick->hwdata->ffeffect->lpvTypeSpecificParams);
-        periodic->dwMagnitude = CONVERT_MAGNITUDE(magnitude);
-
-        result = IDirectInputEffect_SetParameters(joystick->hwdata->ffeffect_ref, joystick->hwdata->ffeffect, (DIEP_DURATION | DIEP_TYPESPECIFICPARAMS));
-        if (result == DIERR_INPUTLOST) {
-            result = IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice);
-            if (SUCCEEDED(result)) {
-                result = IDirectInputEffect_SetParameters(joystick->hwdata->ffeffect_ref, joystick->hwdata->ffeffect, (DIEP_DURATION | DIEP_TYPESPECIFICPARAMS));
-            }
-        }
-        if (FAILED(result)) {
-            return SetDIerror("IDirectInputDevice8::SetParameters", result);
-        }
-    } else {
-        if (!SDL_DINPUT_JoystickInitRumble(joystick, magnitude)) {
-            return false;
-        }
-        joystick->hwdata->ff_initialized = true;
-    }
-
-    result = IDirectInputEffect_Start(joystick->hwdata->ffeffect_ref, 1, 0);
-    if (result == DIERR_INPUTLOST || result == DIERR_NOTEXCLUSIVEACQUIRED) {
-        result = IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice);
-        if (SUCCEEDED(result)) {
-            result = IDirectInputEffect_Start(joystick->hwdata->ffeffect_ref, 1, 0);
-        }
-    }
-    if (FAILED(result)) {
-        return SetDIerror("IDirectInputDevice8::Start", result);
-    }
-    return true;
-}
-
 static Uint8 TranslatePOV(DWORD value)
 {
     const Uint8 HAT_VALS[] = {
@@ -1114,96 +908,697 @@ static void UpdateDINPUTJoystickState_Buffered(SDL_Joystick *joystick)
     }
 }
 
-void SDL_DINPUT_JoystickUpdate(SDL_Joystick *joystick)
+static bool WindowsDeviceChanged(void)
 {
-    HRESULT result;
-
-    result = IDirectInputDevice8_Poll(joystick->hwdata->InputDevice);
-    if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED) {
-        IDirectInputDevice8_Acquire(joystick->hwdata->InputDevice);
-        IDirectInputDevice8_Poll(joystick->hwdata->InputDevice);
-    }
+    return (s_lastDeviceChange != WIN_GetLastDeviceNotification());
+}
 
-    if (joystick->hwdata->first_update) {
-        // Poll to get the initial state of the joystick
-        UpdateDINPUTJoystickState_Polled(joystick);
-        joystick->hwdata->first_update = false;
-        return;
-    }
+static void SetWindowsDeviceChanged(void)
+{
+    s_lastDeviceChange = 0;
+}
 
-    if (joystick->hwdata->buffered ) {
-        UpdateDINPUTJoystickState_Buffered(joystick);
-    } else {
-        UpdateDINPUTJoystickState_Polled(joystick);
+typedef struct
+{
+    HRESULT coinitialized;
+    WNDCLASSEX wincl;
+    HWND messageWindow;
+    HDEVNOTIFY hNotify;
+} SDL_DeviceNotificationData;
+
+#define IDT_SDL_DEVICE_CHANGE_TIMER_1 1200
+#define IDT_SDL_DEVICE_CHANGE_TIMER_2 1201
+
+// windowproc for our joystick detect thread message only window, to detect any USB device addition/removal
+static LRESULT CALLBACK SDL_PrivateJoystickDetectProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
+{
+    switch (msg) {
+    case WM_DEVICECHANGE:
+        switch (wParam) {
+        case DBT_DEVICEARRIVAL:
+        case DBT_DEVICEREMOVECOMPLETE:
+            if (((DEV_BROADCAST_HDR *)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
+                // notify 300ms and 2 seconds later to ensure all APIs have updated status
+                SetTimer(hwnd, IDT_SDL_DEVICE_CHANGE_TIMER_1, 300, NULL);
+                SetTimer(hwnd, IDT_SDL_DEVICE_CHANGE_TIMER_2, 2000, NULL);
+            }
+            break;
+        }
+        return true;
+    case WM_TIMER:
+        if (wParam == IDT_SDL_DEVICE_CHANGE_TIMER_1 ||
+            wParam == IDT_SDL_DEVICE_CHANGE_TIMER_2) {
+            KillTimer(hwnd, wParam);
+            SetWindowsDeviceChanged();
+            return true;
+        }
+        break;
     }
+
+    return CallWindowProc(DefWindowProc, hwnd, msg, wParam, lParam);
 }
 
-void SDL_DINPUT_JoystickClose(SDL_Joystick *joystick)
+static void SDL_CleanupDeviceNotification(SDL_DeviceNotificationData *data)
 {
-    if (joystick->hwdata->ffeffect_ref) {
-        IDirectInputEffect_Unload(joystick->hwdata->ffeffect_ref);
-        joystick->hwdata->ffeffect_ref = NULL;
+    if (data->hNotify) {
+        UnregisterDeviceNotification(data->hNotify);
     }
-    if (joystick->hwdata->ffeffect) {
-        FreeRumbleEffectData(joystick->hwdata->ffeffect);
-        joystick->hwdata->ffeffect = NULL;
+
+    if (data->messageWindow) {
+        DestroyWindow(data->messageWindow);
     }
-    IDirectInputDevice8_Unacquire(joystick->hwdata->InputDevice);
-    IDirectInputDevice8_Release(joystick->hwdata->InputDevice);
-    joystick->hwdata->ff_initialized = false;
+
+    UnregisterClass(data->wincl.lpszClassName, data->wincl.hInstance);
+
+    if (data->coinitialized == S_OK) {
+        WIN_CoUninitialize();
+    }
+
+    SDL_zerop(data);
 }
 
-void SDL_DINPUT_JoystickQuit(void)
+static bool SDL_CreateDeviceNotification(SDL_DeviceNotificationData *data)
 {
-    if (dinput != NULL) {
-        IDirectInput8_Release(dinput);
-        dinput = NULL;
+    DEV_BROADCAST_DEVICEINTERFACE dbh;
+
+    SDL_zerop(data);
+
+    data->coinitialized = WIN_CoInitialize();
+
+    data->wincl.hInstance = GetModuleHandle(NULL);
+    data->wincl.lpszClassName = TEXT("Message");
+    data->wincl.lpfnWndProc = SDL_PrivateJoystickDetectProc; // This function is called by windows
+    data->wincl.cbSize = sizeof(WNDCLASSEX);
+
+    if (!RegisterClassEx(&data->wincl)) {
+        WIN_SetError("Failed to create register class for joystick autodetect");
+        SDL_CleanupDeviceNotification(data);
+        return false;
     }
 
-    if (coinitialized) {
-        WIN_CoUninitialize();
-        coinitialized = false;
+    data->messageWindow = CreateWindowEx(0, TEXT("Message"), NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
+    if (!data->messageWindow) {
+        WIN_SetError("Failed to create message window for joystick autodetect");
+        SDL_CleanupDeviceNotification(data);
+        return false;
+    }
+
+    SDL_zero(dbh);
+    dbh.dbcc_size = sizeof(dbh);
+    dbh.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
+    dbh.dbcc_classguid = GUID_DEVINTERFACE_HID;
+
+    data->hNotify = RegisterDeviceNotification(data->messageWindow, &dbh, DEVICE_NOTIFY_WINDOW_HANDLE);
+    if (!data->hNotify) {
+        WIN_SetError("Failed to create notify device for joystick autodetect");
+        SDL_CleanupDeviceNotification(data);
+        return false;
     }
+
+    return true;
 }
 
-#else // !SDL_JOYSTICK_DINPUT
+static bool SDL_WaitForDeviceNotification(SDL_DeviceNotificationData *data, SDL_Mutex *mutex)
+{
+    MSG msg;
+    int lastret = 1;
 
-typedef struct JoyStick_DeviceData JoyStick_DeviceData;
+    if (!data->messageWindow) {
+        return false; // device notifications require a window
+    }
 
-bool SDL_DINPUT_JoystickInit(void)
+    SDL_UnlockMutex(mutex);
+    // Pump messages until we're told to quit. Device changes are picked up by DINPUT_JoystickDetect(),
+    // so returning while one is pending would just spin until the next detect.
+    while (lastret > 0) {
+        lastret = GetMessage(&msg, NULL, 0, 0); // WM_QUIT causes return value of 0
+        if (lastret > 0) {
+    

(Patch may be truncated, please check the link at the top of this post.)