Polling hid_enumerate() every 3 seconds causes freezes and stutters on some USB audio devices and mice.
authorSam Lantinga <slouken@libsdl.org>
Wed, 15 Aug 2018 19:53:22 -0700
changeset 1210900411ca61edb
parent 12108 eb2820ee52ee
child 12110 c52772e46ee2
Polling hid_enumerate() every 3 seconds causes freezes and stutters on some USB audio devices and mice.
We'll only enumerate devices when we get notification that the system devices have changed
src/joystick/hidapi/SDL_hidapijoystick.c
     1.1 --- a/src/joystick/hidapi/SDL_hidapijoystick.c	Fri Aug 10 15:22:02 2018 -0400
     1.2 +++ b/src/joystick/hidapi/SDL_hidapijoystick.c	Wed Aug 15 19:53:22 2018 -0700
     1.3 @@ -25,11 +25,29 @@
     1.4  #include "SDL_endian.h"
     1.5  #include "SDL_hints.h"
     1.6  #include "SDL_log.h"
     1.7 +#include "SDL_thread.h"
     1.8  #include "SDL_timer.h"
     1.9  #include "SDL_joystick.h"
    1.10  #include "../SDL_sysjoystick.h"
    1.11  #include "SDL_hidapijoystick_c.h"
    1.12  
    1.13 +#if defined(__WIN32__)
    1.14 +#include "../../core/windows/SDL_windows.h"
    1.15 +#endif
    1.16 +
    1.17 +#if defined(__MACOSX__)
    1.18 +#include <CoreFoundation/CoreFoundation.h>
    1.19 +#include <mach/mach.h>
    1.20 +#include <IOKit/IOKitLib.h>
    1.21 +#include <IOKit/usb/USBSpec.h>
    1.22 +#endif
    1.23 +
    1.24 +#if defined(__LINUX__)
    1.25 +#include "../../core/linux/SDL_udev.h"
    1.26 +#ifdef SDL_USE_LIBUDEV
    1.27 +#include <poll.h>
    1.28 +#endif
    1.29 +#endif
    1.30  
    1.31  struct joystick_hwdata
    1.32  {
    1.33 @@ -77,7 +95,282 @@
    1.34  };
    1.35  static SDL_HIDAPI_Device *SDL_HIDAPI_devices;
    1.36  static int SDL_HIDAPI_numjoysticks = 0;
    1.37 -static Uint32 SDL_HIDAPI_last_detect = 0;
    1.38 +
    1.39 +static struct
    1.40 +{
    1.41 +    SDL_bool m_bHaveDevicesChanged;
    1.42 +    SDL_bool m_bCanGetNotifications;
    1.43 +    Uint32 m_unLastDetect;
    1.44 +
    1.45 +#if defined(__WIN32__)
    1.46 +	SDL_threadID m_nThreadID;
    1.47 +    WNDCLASSEXA m_wndClass;
    1.48 +    HWND m_hwndMsg;
    1.49 +    HDEVNOTIFY m_hNotify;
    1.50 +    double m_flLastWin32MessageCheck;
    1.51 +#endif
    1.52 +
    1.53 +#if defined(__MACOSX__)
    1.54 +    IONotificationPortRef m_notificationPort;
    1.55 +    mach_port_t m_notificationMach;
    1.56 +#endif
    1.57 +
    1.58 +#if defined(SDL_USE_LIBUDEV)
    1.59 +    struct udev *m_pUdev;
    1.60 +    struct udev_monitor *m_pUdevMonitor;
    1.61 +    int m_nUdevFd;
    1.62 +#endif
    1.63 +} SDL_HIDAPI_discovery;
    1.64 +
    1.65 +
    1.66 +#ifdef __WIN32__
    1.67 +struct _DEV_BROADCAST_HDR
    1.68 +{
    1.69 +    DWORD       dbch_size;
    1.70 +    DWORD       dbch_devicetype;
    1.71 +    DWORD       dbch_reserved;
    1.72 +};
    1.73 +
    1.74 +typedef struct _DEV_BROADCAST_DEVICEINTERFACE_A
    1.75 +{
    1.76 +    DWORD       dbcc_size;
    1.77 +    DWORD       dbcc_devicetype;
    1.78 +    DWORD       dbcc_reserved;
    1.79 +    GUID        dbcc_classguid;
    1.80 +    char        dbcc_name[ 1 ];
    1.81 +} DEV_BROADCAST_DEVICEINTERFACE_A, *PDEV_BROADCAST_DEVICEINTERFACE_A;
    1.82 +
    1.83 +typedef struct  _DEV_BROADCAST_HDR      DEV_BROADCAST_HDR;
    1.84 +#define DBT_DEVICEARRIVAL               0x8000  /* system detected a new device */
    1.85 +#define DBT_DEVTYP_DEVICEINTERFACE      0x00000005  /* device interface class */
    1.86 +#define DBT_DEVNODES_CHANGED            0x0007
    1.87 +#define DBT_CONFIGCHANGED               0x0018
    1.88 +#define DBT_DEVICETYPESPECIFIC          0x8005  /* type specific event */
    1.89 +#define DBT_DEVINSTSTARTED               0x8008  /* device installed and started */
    1.90 +
    1.91 +#include <initguid.h>
    1.92 +DEFINE_GUID(GUID_DEVINTERFACE_USB_DEVICE, 0xA5DCBF10L, 0x6530, 0x11D2, 0x90, 0x1F, 0x00, 0xC0, 0x4F, 0xB9, 0x51, 0xED);
    1.93 +
    1.94 +static LRESULT CALLBACK ControllerWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
    1.95 +{
    1.96 +    switch (message) {
    1.97 +    case WM_DEVICECHANGE:
    1.98 +        switch (wParam) {
    1.99 +        case DBT_DEVICEARRIVAL:
   1.100 +            if (((DEV_BROADCAST_HDR*)lParam)->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) {
   1.101 +				SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
   1.102 +            }
   1.103 +            break;
   1.104 +        }
   1.105 +        return 0;
   1.106 +    }
   1.107 +
   1.108 +    return DefWindowProc(hwnd, message, wParam, lParam);
   1.109 +}
   1.110 +#endif /* __WIN32__ */
   1.111 +
   1.112 +
   1.113 +#if defined(__MACOSX__)
   1.114 +static void CallbackIOServiceFUNC(void *context, io_iterator_t portIterator)
   1.115 +{
   1.116 +    /* Must drain the iterator, or we won't receive new notifications */
   1.117 +    while ((io_object_t entry = IOIteratorNext(portIterator)) != NULL) {
   1.118 +        IOObjectRelease(entry);
   1.119 +        *(SDL_bool*)context = SDL_TRUE;
   1.120 +    }
   1.121 +}
   1.122 +#endif /* __MACOSX__ */
   1.123 +
   1.124 +static void
   1.125 +HIDAPI_InitializeDiscovery()
   1.126 +{
   1.127 +    SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
   1.128 +    SDL_HIDAPI_discovery.m_bCanGetNotifications = SDL_FALSE;
   1.129 +    SDL_HIDAPI_discovery.m_unLastDetect = 0;
   1.130 +
   1.131 +#if defined(__WIN32__)
   1.132 +    SDL_HIDAPI_discovery.m_nThreadID = SDL_ThreadID();
   1.133 +
   1.134 +    SDL_memset(&SDL_HIDAPI_discovery.m_wndClass, 0x0, sizeof(SDL_HIDAPI_discovery.m_wndClass));
   1.135 +    SDL_HIDAPI_discovery.m_wndClass.hInstance = GetModuleHandle(NULL);
   1.136 +    SDL_HIDAPI_discovery.m_wndClass.lpszClassName = "ControllerDetect";
   1.137 +    SDL_HIDAPI_discovery.m_wndClass.lpfnWndProc = ControllerWndProc;      /* This function is called by windows */
   1.138 +    SDL_HIDAPI_discovery.m_wndClass.cbSize = sizeof(WNDCLASSEX);
   1.139 +
   1.140 +    RegisterClassExA(&SDL_HIDAPI_discovery.m_wndClass);
   1.141 +    SDL_HIDAPI_discovery.m_hwndMsg = CreateWindowExA(0, "ControllerDetect", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
   1.142 +
   1.143 +	{
   1.144 +		DEV_BROADCAST_DEVICEINTERFACE_A devBroadcast;
   1.145 +		SDL_memset( &devBroadcast, 0x0, sizeof( devBroadcast ) );
   1.146 +
   1.147 +		devBroadcast.dbcc_size = sizeof( devBroadcast );
   1.148 +		devBroadcast.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
   1.149 +		devBroadcast.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE;
   1.150 +
   1.151 +		/* DEVICE_NOTIFY_ALL_INTERFACE_CLASSES is important, makes GUID_DEVINTERFACE_USB_DEVICE ignored,
   1.152 +		 * but that seems to be necessary to get a notice after each individual usb input device actually
   1.153 +		 * installs, rather than just as the composite device is seen.
   1.154 +		 */
   1.155 +		SDL_HIDAPI_discovery.m_hNotify = RegisterDeviceNotification( SDL_HIDAPI_discovery.m_hwndMsg, &devBroadcast, DEVICE_NOTIFY_WINDOW_HANDLE | DEVICE_NOTIFY_ALL_INTERFACE_CLASSES );
   1.156 +		SDL_HIDAPI_discovery.m_bCanGetNotifications = ( SDL_HIDAPI_discovery.m_hNotify != 0 );
   1.157 +	}
   1.158 +#endif /* __WIN32__ */
   1.159 +
   1.160 +#if defined(__MACOSX__)
   1.161 +    SDL_HIDAPI_discovery.m_notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
   1.162 +    if (SDL_HIDAPI_discovery.m_notificationPort) {
   1.163 +        {
   1.164 +            CFMutableDictionaryRef matchingDict = IOServiceMatching("IOUSBDevice");
   1.165 +
   1.166 +            /* Note: IOServiceAddMatchingNotification consumes the reference to matchingDict */
   1.167 +            io_iterator_t portIterator = 0;
   1.168 +            if (IOServiceAddMatchingNotification(SDL_HIDAPI_discovery.m_notificationPort, kIOMatchedNotification, matchingDict, CallbackIOServiceFunc, &SDL_HIDAPI_discovery.m_bHaveDevicesChanged, &portIterator) == 0) {
   1.169 +                /* Must drain the existing iterator, or we won't receive new notifications */
   1.170 +                while (io_object_t entry = IOIteratorNext(portIterator)) {
   1.171 +                    IOObjectRelease(entry);
   1.172 +                }
   1.173 +            } else {
   1.174 +                IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort);
   1.175 +                SDL_HIDAPI_discovery.m_notificationPort = nil;
   1.176 +            }
   1.177 +        }
   1.178 +        {
   1.179 +            CFMutableDictionaryRef matchingDict = IOServiceMatching("IOBluetoothDevice");
   1.180 +
   1.181 +            /* Note: IOServiceAddMatchingNotification consumes the reference to matchingDict */
   1.182 +            io_iterator_t portIterator = 0;
   1.183 +            if (IOServiceAddMatchingNotification(SDL_HIDAPI_discovery.m_notificationPort, kIOMatchedNotification, matchingDict, CallbackIOServiceFunc, &SDL_HIDAPI_discovery.m_bHaveDevicesChanged, &portIterator) == 0) {
   1.184 +                /* Must drain the existing iterator, or we won't receive new notifications */
   1.185 +                while (io_object_t entry = IOIteratorNext(portIterator)) {
   1.186 +                    IOObjectRelease(entry);
   1.187 +                }
   1.188 +            } else {
   1.189 +                IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort);
   1.190 +                SDL_HIDAPI_discovery.m_notificationPort = nil;
   1.191 +            }
   1.192 +        }
   1.193 +    }
   1.194 +
   1.195 +    SDL_HIDAPI_discovery.m_notificationMach = MACH_PORT_NULL;
   1.196 +    if (SDL_HIDAPI_discovery.m_notificationPort) {
   1.197 +        SDL_HIDAPI_discovery.m_notificationMach = IONotificationPortGetMachPort(SDL_HIDAPI_discovery.m_notificationPort);
   1.198 +    }
   1.199 +
   1.200 +    SDL_HIDAPI_discovery.m_bCanGetNotifications = (SDL_HIDAPI_discovery.m_notificationMach != MACH_PORT_NULL);
   1.201 +
   1.202 +#endif // __MACOSX__
   1.203 +
   1.204 +#if defined(SDL_USE_LIBUDEV)
   1.205 +    SDL_HIDAPI_discovery.m_pUdev = NULL;
   1.206 +    SDL_HIDAPI_discovery.m_pUdevMonitor = NULL;
   1.207 +    SDL_HIDAPI_discovery.m_nUdevFd = -1;
   1.208 +
   1.209 +    SDL_HIDAPI_discovery.m_pUdev = udev_new();
   1.210 +    if (SDL_HIDAPI_discovery.m_pUdev) {
   1.211 +        SDL_HIDAPI_discovery.m_pUdevMonitor = udev_monitor_new_from_netlink(SDL_HIDAPI_discovery.m_pUdev, "udev");
   1.212 +        if (SDL_HIDAPI_discovery.m_pUdevMonitor) {
   1.213 +            udev_monitor_enable_receiving(SDL_HIDAPI_discovery.m_pUdevMonitor);
   1.214 +            SDL_HIDAPI_discovery.m_nUdevFd = udev_monitor_get_fd(SDL_HIDAPI_discovery.m_pUdevMonitor);
   1.215 +            SDL_HIDAPI_discovery.m_bCanGetNotifications = true;
   1.216 +        }
   1.217 +    }
   1.218 +
   1.219 +#endif /* SDL_USE_LIBUDEV */
   1.220 +}
   1.221 +
   1.222 +static void
   1.223 +HIDAPI_UpdateDiscovery()
   1.224 +{
   1.225 +    if (!SDL_HIDAPI_discovery.m_bCanGetNotifications) {
   1.226 +        const Uint32 SDL_HIDAPI_DETECT_INTERVAL_MS = 3000;  /* Update every 3 seconds */
   1.227 +        Uint32 now = SDL_GetTicks();
   1.228 +        if (!SDL_HIDAPI_discovery.m_unLastDetect || SDL_TICKS_PASSED(now, SDL_HIDAPI_discovery.m_unLastDetect + SDL_HIDAPI_DETECT_INTERVAL_MS)) {
   1.229 +            SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_TRUE;
   1.230 +            SDL_HIDAPI_discovery.m_unLastDetect = now;
   1.231 +        }
   1.232 +        return;
   1.233 +    }
   1.234 +
   1.235 +#if defined(__WIN32__)
   1.236 +    /* We'll only get messages on the same thread that created the window */
   1.237 +    if (SDL_ThreadID() == SDL_HIDAPI_discovery.m_nThreadID) {
   1.238 +        MSG msg;
   1.239 +        while (PeekMessage(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0, PM_NOREMOVE)) {
   1.240 +            if (GetMessageA(&msg, SDL_HIDAPI_discovery.m_hwndMsg, 0, 0) != 0) {
   1.241 +                TranslateMessage(&msg);
   1.242 +                DispatchMessage(&msg);
   1.243 +            }
   1.244 +        }
   1.245 +    }
   1.246 +#endif
   1.247 +
   1.248 +#if defined(__MACOSX__)
   1.249 +    if (SDL_HIDAPI_discovery.m_notificationPort) {
   1.250 +        struct { mach_msg_header_t hdr; char payload[ 4096 ]; } msg;
   1.251 +        while (mach_msg(&msg.hdr, MACH_RCV_MSG | MACH_RCV_TIMEOUT, 0, sizeof(msg), SDL_HIDAPI_discovery.m_notificationMach, 0, MACH_PORT_NULL) == KERN_SUCCESS) {
   1.252 +            IODispatchCalloutFromMessage(NULL, &msg.hdr, SDL_HIDAPI_discovery.m_notificationPort);
   1.253 +        }
   1.254 +    }
   1.255 +#endif
   1.256 +
   1.257 +#if defined(SDL_USE_LIBUDEV)
   1.258 +    if (SDL_HIDAPI_discovery.m_nUdevFd >= 0) {
   1.259 +        /* Drain all notification events.
   1.260 +         * We don't expect a lot of device notifications so just
   1.261 +         * do a new discovery on any kind or number of notifications.
   1.262 +         * This could be made more restrictive if necessary.
   1.263 +         */
   1.264 +        for (;;) {
   1.265 +            struct pollfd PollUdev;
   1.266 +
   1.267 +            PollUdev.fd = SDL_HIDAPI_discovery.m_nUdevFd;
   1.268 +            PollUdev.events = POLLIN;
   1.269 +            if (poll(&PollUdev, 1, 0) != 1) {
   1.270 +                break;
   1.271 +            }
   1.272 +
   1.273 +            SDL_HIDAPI_discovery.m_bHaveDevicesChanged = true;
   1.274 +
   1.275 +            struct udev_device *pUdevDevice = udev_monitor_receive_device(SDL_HIDAPI_discovery.m_pUdevMonitor);
   1.276 +            if (pUdevDevice) {
   1.277 +                udev_device_unref(pUdevDevice);
   1.278 +            }
   1.279 +        }
   1.280 +    }
   1.281 +#endif
   1.282 +}
   1.283 +
   1.284 +static void
   1.285 +HIDAPI_ShutdownDiscovery()
   1.286 +{
   1.287 +#if defined(__WIN32__)
   1.288 +    if (SDL_HIDAPI_discovery.m_hNotify)
   1.289 +        UnregisterDeviceNotification(SDL_HIDAPI_discovery.m_hNotify);
   1.290 +
   1.291 +    if (SDL_HIDAPI_discovery.m_hwndMsg) {
   1.292 +        DestroyWindow(SDL_HIDAPI_discovery.m_hwndMsg);
   1.293 +    }
   1.294 +
   1.295 +    UnregisterClassA(SDL_HIDAPI_discovery.m_wndClass.lpszClassName, SDL_HIDAPI_discovery.m_wndClass.hInstance);
   1.296 +#endif
   1.297 +
   1.298 +#if defined(__MACOSX__)
   1.299 +    if (SDL_HIDAPI_discovery.m_notificationPort) {
   1.300 +        IONotificationPortDestroy(SDL_HIDAPI_discovery.m_notificationPort);
   1.301 +    }
   1.302 +#endif
   1.303 +
   1.304 +#if defined(SDL_USE_LIBUDEV)
   1.305 +    if (SDL_HIDAPI_discovery.m_pUdevMonitor) {
   1.306 +        udev_monitor_unref(SDL_HIDAPI_discovery.m_pUdevMonitor);
   1.307 +    }
   1.308 +    if (SDL_HIDAPI_discovery.m_pUdev) {
   1.309 +        udev_unref(SDL_HIDAPI_discovery.m_pUdev);
   1.310 +    }
   1.311 +#endif
   1.312 +}
   1.313 +
   1.314  
   1.315  static SDL_bool
   1.316  HIDAPI_IsDeviceSupported(Uint16 vendor_id, Uint16 product_id)
   1.317 @@ -205,7 +498,7 @@
   1.318      }
   1.319      SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI,
   1.320                          SDL_HIDAPIDriverHintChanged, NULL);
   1.321 -    SDL_HIDAPI_last_detect = 0;
   1.322 +    HIDAPI_InitializeDiscovery();
   1.323      HIDAPI_JoystickDetect();
   1.324      return 0;
   1.325  }
   1.326 @@ -423,11 +716,11 @@
   1.327  static void
   1.328  HIDAPI_JoystickDetect(void)
   1.329  {
   1.330 -    const Uint32 SDL_HIDAPI_DETECT_INTERVAL_MS = 3000;  /* Update every 3 seconds */
   1.331 -    Uint32 now = SDL_GetTicks();
   1.332 -    if (!SDL_HIDAPI_last_detect || SDL_TICKS_PASSED(now, SDL_HIDAPI_last_detect + SDL_HIDAPI_DETECT_INTERVAL_MS)) {
   1.333 +    HIDAPI_UpdateDiscovery();
   1.334 +    if (SDL_HIDAPI_discovery.m_bHaveDevicesChanged) {
   1.335 +        /* FIXME: We probably need to schedule an update in a few seconds as well */
   1.336          HIDAPI_UpdateDeviceList();
   1.337 -        SDL_HIDAPI_last_detect = now;
   1.338 +        SDL_HIDAPI_discovery.m_bHaveDevicesChanged = SDL_FALSE;
   1.339      }
   1.340  }
   1.341