diff --git a/3rdparty/ViGEm/Client.h b/3rdparty/ViGEm/Client.h index 722f3f4..f58a4b5 100644 --- a/3rdparty/ViGEm/Client.h +++ b/3rdparty/ViGEm/Client.h @@ -42,453 +42,580 @@ extern "C" { #define VIGEM_API #endif - /** - * \typedef enum _VIGEM_ERRORS - * - * \brief Defines an alias representing the ViGEm errors. - */ - typedef enum _VIGEM_ERRORS - { - VIGEM_ERROR_NONE = 0x20000000, - VIGEM_ERROR_BUS_NOT_FOUND = 0xE0000001, - VIGEM_ERROR_NO_FREE_SLOT = 0xE0000002, - VIGEM_ERROR_INVALID_TARGET = 0xE0000003, - VIGEM_ERROR_REMOVAL_FAILED = 0xE0000004, - VIGEM_ERROR_ALREADY_CONNECTED = 0xE0000005, - VIGEM_ERROR_TARGET_UNINITIALIZED = 0xE0000006, - VIGEM_ERROR_TARGET_NOT_PLUGGED_IN = 0xE0000007, - VIGEM_ERROR_BUS_VERSION_MISMATCH = 0xE0000008, - VIGEM_ERROR_BUS_ACCESS_FAILED = 0xE0000009, - VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED = 0xE0000010, - VIGEM_ERROR_CALLBACK_NOT_FOUND = 0xE0000011, - VIGEM_ERROR_BUS_ALREADY_CONNECTED = 0xE0000012, - VIGEM_ERROR_BUS_INVALID_HANDLE = 0xE0000013, - VIGEM_ERROR_XUSB_USERINDEX_OUT_OF_RANGE = 0xE0000014, - VIGEM_ERROR_INVALID_PARAMETER = 0xE0000015 - - } VIGEM_ERROR; - - /** - * \def VIGEM_SUCCESS(_val_) (_val_ == VIGEM_ERROR_NONE); - * - * \brief A macro that defines success. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param _val_ The VIGEM_ERROR value. - */ +#if defined(_MSC_VER) +#define VIGEM_DEPRECATED __declspec(deprecated) +#elif defined(__GNUC__) +#define VIGEM_DEPRECATED __attribute__ ((deprecated)) +#endif + + /** Values that represent ViGEm errors */ + using VIGEM_ERROR = enum _VIGEM_ERRORS + { + // + // API succeeded. + // + VIGEM_ERROR_NONE = 0x20000000, + // + // A compatible bus driver wasn't found on the system. + // + VIGEM_ERROR_BUS_NOT_FOUND = 0xE0000001, + // + // All device slots are occupied, no new device can be spawned. + // + VIGEM_ERROR_NO_FREE_SLOT = 0xE0000002, + VIGEM_ERROR_INVALID_TARGET = 0xE0000003, + VIGEM_ERROR_REMOVAL_FAILED = 0xE0000004, + // + // An attempt has been made to plug in an already connected device. + // + VIGEM_ERROR_ALREADY_CONNECTED = 0xE0000005, + // + // The target device is not initialized. + // + VIGEM_ERROR_TARGET_UNINITIALIZED = 0xE0000006, + // + // The target device is not plugged in. + // + VIGEM_ERROR_TARGET_NOT_PLUGGED_IN = 0xE0000007, + // + // It's been attempted to communicate with an incompatible driver version. + // + VIGEM_ERROR_BUS_VERSION_MISMATCH = 0xE0000008, + // + // Bus driver found but failed to open a handle. + // + VIGEM_ERROR_BUS_ACCESS_FAILED = 0xE0000009, + VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED = 0xE0000010, + VIGEM_ERROR_CALLBACK_NOT_FOUND = 0xE0000011, + VIGEM_ERROR_BUS_ALREADY_CONNECTED = 0xE0000012, + VIGEM_ERROR_BUS_INVALID_HANDLE = 0xE0000013, + VIGEM_ERROR_XUSB_USERINDEX_OUT_OF_RANGE = 0xE0000014, + VIGEM_ERROR_INVALID_PARAMETER = 0xE0000015, + // + // The API is not supported by the driver. + // + VIGEM_ERROR_NOT_SUPPORTED = 0xE0000016, + // + // An unexpected Win32 API error occurred. Call GetLastError() for details. + // + VIGEM_ERROR_WINAPI = 0xE0000017, + // + // The specified timeout has been reached. + // + VIGEM_ERROR_TIMED_OUT = 0xE0000018, + }; + + /** + * A macro that defines if the API succeeded + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 01.09.2020 + * + * @param _val_ The error value. + */ #define VIGEM_SUCCESS(_val_) (_val_ == VIGEM_ERROR_NONE) - /** - * \typedef struct _VIGEM_CLIENT_T *PVIGEM_CLIENT - * - * \brief Defines an alias representing a driver connection object. - */ - typedef struct _VIGEM_CLIENT_T *PVIGEM_CLIENT; - - /** - * \typedef struct _VIGEM_TARGET_T *PVIGEM_TARGET - * - * \brief Defines an alias representing a target device object. - */ - typedef struct _VIGEM_TARGET_T *PVIGEM_TARGET; - - typedef - _Function_class_(EVT_VIGEM_TARGET_ADD_RESULT) - VOID CALLBACK - EVT_VIGEM_TARGET_ADD_RESULT( - PVIGEM_CLIENT Client, - PVIGEM_TARGET Target, - VIGEM_ERROR Result - ); - - typedef EVT_VIGEM_TARGET_ADD_RESULT *PFN_VIGEM_TARGET_ADD_RESULT; - - typedef - _Function_class_(EVT_VIGEM_X360_NOTIFICATION) - VOID CALLBACK - EVT_VIGEM_X360_NOTIFICATION( - PVIGEM_CLIENT Client, - PVIGEM_TARGET Target, - UCHAR LargeMotor, - UCHAR SmallMotor, - UCHAR LedNumber - ); - - typedef EVT_VIGEM_X360_NOTIFICATION *PFN_VIGEM_X360_NOTIFICATION; - - typedef - _Function_class_(EVT_VIGEM_DS4_NOTIFICATION) - VOID CALLBACK - EVT_VIGEM_DS4_NOTIFICATION( - PVIGEM_CLIENT Client, - PVIGEM_TARGET Target, - UCHAR LargeMotor, - UCHAR SmallMotor, - DS4_LIGHTBAR_COLOR LightbarColor - ); - - typedef EVT_VIGEM_DS4_NOTIFICATION *PFN_VIGEM_DS4_NOTIFICATION; - - /** - * \fn PVIGEM_CLIENT vigem_alloc(void); - * - * \brief Allocates an object representing a driver connection. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \return A new driver connection object. - */ - VIGEM_API PVIGEM_CLIENT vigem_alloc(void); - - /** - * \fn void vigem_free(PVIGEM_CLIENT vigem); - * - * \brief Frees up memory used by the driver connection object. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - */ - VIGEM_API void vigem_free(PVIGEM_CLIENT vigem); - - /** - * \fn VIGEM_ERROR vigem_connect(PVIGEM_CLIENT vigem); - * - * \brief Initializes the driver object and establishes a connection to the emulation bus - * driver. Returns an error if no compatible bus device has been found. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_connect(PVIGEM_CLIENT vigem); - - /** - * \fn void vigem_disconnect(PVIGEM_CLIENT vigem); - * - * \brief Disconnects from the bus device and resets the driver object state. The driver object - * may be reused again after calling this function. When called, all targets which may - * still be connected will be destroyed automatically. Be aware, that allocated target - * objects won't be automatically freed, this has to be taken care of by the caller. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - */ - VIGEM_API void vigem_disconnect(PVIGEM_CLIENT vigem); - - /** - * \fn PVIGEM_TARGET vigem_target_x360_alloc(void); - * - * \brief Allocates an object representing an Xbox 360 Controller device. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \return A PVIGEM_TARGET representing an Xbox 360 Controller device. - */ - VIGEM_API PVIGEM_TARGET vigem_target_x360_alloc(void); - - /** - * \fn PVIGEM_TARGET vigem_target_ds4_alloc(void); - * - * \brief Allocates an object representing a DualShock 4 Controller device. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \return A PVIGEM_TARGET representing a DualShock 4 Controller device. - */ - VIGEM_API PVIGEM_TARGET vigem_target_ds4_alloc(void); - - /** - * \fn void vigem_target_free(PVIGEM_TARGET target); - * - * \brief Frees up memory used by the target device object. This does not automatically remove - * the associated device from the bus, if present. If the target device doesn't get - * removed before this call, the device becomes orphaned until the owning process is - * terminated. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - */ - VIGEM_API void vigem_target_free(PVIGEM_TARGET target); - - /** - * \fn VIGEM_ERROR vigem_target_add(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); - * - * \brief Adds a provided target device to the bus driver, which is equal to a device plug-in - * event of a physical hardware device. This function blocks until the target device is - * in full operational mode. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * \param target The target device object. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_add(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); - - /** - * \fn VIGEM_ERROR vigem_target_add_async(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_TARGET_ADD_RESULT result); - * - * \brief Adds a provided target device to the bus driver, which is equal to a device plug-in - * event of a physical hardware device. This function immediately returns. An optional - * callback may be registered which gets called on error or if the target device has - * become fully operational. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * \param target The target device object. - * \param result An optional function getting called when the target device becomes available. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_add_async(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PFN_VIGEM_TARGET_ADD_RESULT result); - - /** - * \fn VIGEM_ERROR vigem_target_remove(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); - * - * \brief Removes a provided target device from the bus driver, which is equal to a device - * unplug event of a physical hardware device. The target device object may be reused - * after this function is called. If this function is never called on target device - * objects, they will be removed from the bus when the owning process terminates. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * \param target The target device object. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_remove(PVIGEM_CLIENT vigem, PVIGEM_TARGET target); - - /** - * \fn VIGEM_ERROR vigem_target_x360_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_X360_NOTIFICATION notification); - * - * \brief Registers a function which gets called, when LED index or vibration state changes - * occur on the provided target device. This function fails if the provided target - * device isn't fully operational or in an erroneous state. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * \param target The target device object. - * \param notification The notification callback. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_x360_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PFN_VIGEM_X360_NOTIFICATION notification); - - /** - * \fn VIGEM_ERROR vigem_target_ds4_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PVIGEM_DS4_NOTIFICATION notification); - * - * \brief Registers a function which gets called, when LightBar or vibration state changes - * occur on the provided target device. This function fails if the provided target - * device isn't fully operational or in an erroneous state. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * \param target The target device object. - * \param notification The notification callback. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_ds4_register_notification(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PFN_VIGEM_DS4_NOTIFICATION notification); - - /** - * \fn void vigem_target_x360_unregister_notification(PVIGEM_TARGET target); - * - * \brief Removes a previously registered callback function from the provided target object. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - */ - VIGEM_API void vigem_target_x360_unregister_notification(PVIGEM_TARGET target); - - /** - * \fn void vigem_target_ds4_unregister_notification(PVIGEM_TARGET target); - * - * \brief Removes a previously registered callback function from the provided target object. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - */ - VIGEM_API void vigem_target_ds4_unregister_notification(PVIGEM_TARGET target); - - /** - * \fn void vigem_target_set_vid(PVIGEM_TARGET target, USHORT vid); - * - * \brief Overrides the default Vendor ID value with the provided one. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - * \param vid The Vendor ID to set. - */ - VIGEM_API void vigem_target_set_vid(PVIGEM_TARGET target, USHORT vid); - - /** - * \fn void vigem_target_set_pid(PVIGEM_TARGET target, USHORT pid); - * - * \brief Overrides the default Product ID value with the provided one. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - * \param pid The Product ID to set. - */ - VIGEM_API void vigem_target_set_pid(PVIGEM_TARGET target, USHORT pid); - - /** - * \fn USHORT vigem_target_get_vid(PVIGEM_TARGET target); - * - * \brief Returns the Vendor ID of the provided target device object. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - * - * \return The Vendor ID. - */ - VIGEM_API USHORT vigem_target_get_vid(PVIGEM_TARGET target); - - /** - * \fn USHORT vigem_target_get_pid(PVIGEM_TARGET target); - * - * \brief Returns the Product ID of the provided target device object. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - * - * \return The Product ID. - */ - VIGEM_API USHORT vigem_target_get_pid(PVIGEM_TARGET target); - - /** - * \fn VIGEM_ERROR vigem_target_x360_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, XUSB_REPORT report); - * - * \brief Sends a state report to the provided target device. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * \param target The target device object. - * \param report The report to send to the target device. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_x360_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, XUSB_REPORT report); - - /** - * \fn VIGEM_ERROR vigem_target_ds4_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, DS4_REPORT report); - * - * \brief Sends a state report to the provided target device. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param vigem The driver connection object. - * \param target The target device object. - * \param report The report to send to the target device. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_ds4_update(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, DS4_REPORT report); - - /** - * \fn ULONG vigem_target_get_index(PVIGEM_TARGET target); - * - * \brief Returns the internal index (serial number) the bus driver assigned to the provided - * target device object. Note that this value is specific to the inner workings of the - * bus driver, it does not reflect related values like player index or device arrival - * order experienced by other APIs. It may be used to identify the target device object - * for its lifetime. This value becomes invalid once the target device is removed from - * the bus and may change on the next addition of the device. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - * - * \return The internally used index of the target device. - */ - VIGEM_API ULONG vigem_target_get_index(PVIGEM_TARGET target); - - /** - * \fn VIGEM_TARGET_TYPE vigem_target_get_type(PVIGEM_TARGET target); - * - * \brief Returns the type of the provided target device object. - * - * \author Benjamin "Nefarius" Höglinger - * \date 28.08.2017 - * - * \param target The target device object. - * - * \return A VIGEM_TARGET_TYPE. - */ - VIGEM_API VIGEM_TARGET_TYPE vigem_target_get_type(PVIGEM_TARGET target); - - /** - * \fn BOOL vigem_target_is_attached(PVIGEM_TARGET target); - * - * \brief Returns TRUE if the provided target device object is currently attached to the bus, - * FALSE otherwise. - * - * \author Benjamin "Nefarius" Höglinger - * \date 30.08.2017 - * - * \param target The target device object. - * - * \return TRUE if device is attached to the bus, FALSE otherwise. - */ - VIGEM_API BOOL vigem_target_is_attached(PVIGEM_TARGET target); - - /** - * \fn VIGEM_API VIGEM_ERROR vigem_target_x360_get_user_index(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PULONG index); - * - * \brief Returns the user index of the emulated Xenon device. This value correspondents to the - * (zero-based) index number representing the player number via LED present on a - * physical controller and is compatible to the dwUserIndex propery of the XInput* APIs. - * - * \author Benjamin "Nefarius" Höglinger - * \date 10.05.2018 - * - * \param vigem The driver connection object. - * \param target The target device object. - * \param index The (zero-based) user index of the Xenon device. - * - * \return A VIGEM_ERROR. - */ - VIGEM_API VIGEM_ERROR vigem_target_x360_get_user_index(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PULONG index); + /** Defines an alias representing a driver connection object */ + using PVIGEM_CLIENT = struct _VIGEM_CLIENT_T*; + + /** Defines an alias representing a target device object */ + using PVIGEM_TARGET = struct _VIGEM_TARGET_T*; + + using EVT_VIGEM_TARGET_ADD_RESULT = _Function_class_(EVT_VIGEM_TARGET_ADD_RESULT) + VOID CALLBACK( + PVIGEM_CLIENT Client, + PVIGEM_TARGET Target, + VIGEM_ERROR Result + ); + + using PFN_VIGEM_TARGET_ADD_RESULT = EVT_VIGEM_TARGET_ADD_RESULT*; + + using EVT_VIGEM_X360_NOTIFICATION = _Function_class_(EVT_VIGEM_X360_NOTIFICATION) + VOID CALLBACK( + PVIGEM_CLIENT Client, + PVIGEM_TARGET Target, + UCHAR LargeMotor, + UCHAR SmallMotor, + UCHAR LedNumber, + LPVOID UserData + ); + + using PFN_VIGEM_X360_NOTIFICATION = EVT_VIGEM_X360_NOTIFICATION*; + + using EVT_VIGEM_DS4_NOTIFICATION = _Function_class_(EVT_VIGEM_DS4_NOTIFICATION) + VOID CALLBACK( + PVIGEM_CLIENT Client, + PVIGEM_TARGET Target, + UCHAR LargeMotor, + UCHAR SmallMotor, + DS4_LIGHTBAR_COLOR LightbarColor, + LPVOID UserData + ); + + using PFN_VIGEM_DS4_NOTIFICATION = EVT_VIGEM_DS4_NOTIFICATION*; + + /** + * Allocates an object representing a driver connection + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @returns A PVIGEM_CLIENT object. + */ + VIGEM_API PVIGEM_CLIENT vigem_alloc(void); + + /** + * Frees up memory used by the driver connection object + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @param vigem The PVIGEM_CLIENT object. + */ + VIGEM_API void vigem_free( + PVIGEM_CLIENT vigem + ); + + /** + * Initializes the driver object and establishes a connection to the emulation bus + * driver. Returns an error if no compatible bus device has been found. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @param vigem The PVIGEM_CLIENT object. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_connect( + PVIGEM_CLIENT vigem + ); + + /** + * Disconnects from the bus device and resets the driver object state. The driver object + * may be reused again after calling this function. When called, all targets which may + * still be connected will be destroyed automatically. Be aware, that allocated target + * objects won't be automatically freed, this has to be taken care of by the caller. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @param vigem The PVIGEM_CLIENT object. + */ + VIGEM_API void vigem_disconnect( + PVIGEM_CLIENT vigem + ); + + /** + * A useful utility function to check if pre 1.17 driver, meant to be replaced in the future by + * more robust version checks, only able to be checked after at least one device has been + * successfully plugged in. + * + * @author Jason "megadrago88" Hart + * @date 17.08.2021 + * + * @param target The PVIGEM_TARGET to check against. + * + * @returns A BOOLEAN, true if the device wait ready ioctl is supported (1.17+) or false if not ( =< 1.16) + */ + VIGEM_API BOOLEAN vigem_target_is_waitable_add_supported( + PVIGEM_TARGET target + ); + + /** + * Allocates an object representing an Xbox 360 Controller device. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @returns A PVIGEM_TARGET representing an Xbox 360 Controller device. + */ + VIGEM_API PVIGEM_TARGET vigem_target_x360_alloc(void); + + /** + * Allocates an object representing a DualShock 4 Controller device. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @returns A PVIGEM_TARGET representing a DualShock 4 Controller device. + */ + VIGEM_API PVIGEM_TARGET vigem_target_ds4_alloc(void); + + /** + * Frees up memory used by the target device object. This does not automatically remove + * the associated device from the bus, if present. If the target device doesn't get + * removed before this call, the device becomes orphaned until the owning process is + * terminated. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @param target The target device object. + */ + VIGEM_API void vigem_target_free( + PVIGEM_TARGET target + ); + + /** + * Adds a provided target device to the bus driver, which is equal to a device plug-in + * event of a physical hardware device. This function blocks until the target device is + * in full operational mode. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @param vigem The driver connection object. + * @param target The target device object. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_add( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target + ); + + /** + * Adds a provided target device to the bus driver, which is equal to a device plug-in + * event of a physical hardware device. This function immediately returns. An optional + * callback may be registered which gets called on error or if the target device has + * become fully operational. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 28.08.2017 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param result An optional function getting called when the target device becomes available. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_add_async( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PFN_VIGEM_TARGET_ADD_RESULT result + ); + + /** + * Removes a provided target device from the bus driver, which is equal to a device + * unplug event of a physical hardware device. The target device object may be reused + * after this function is called. If this function is never called on target device + * objects, they will be removed from the bus when the owning process terminates. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param vigem The driver connection object. + * @param target The target device object. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_remove( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target + ); + + /** + * Registers a function which gets called, when LED index or vibration state changes + * occur on the provided target device. This function fails if the provided + * target device isn't fully operational or in an erroneous state. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param notification The notification callback. + * @param userData The user data passed to the notification callback. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_x360_register_notification( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PFN_VIGEM_X360_NOTIFICATION notification, + LPVOID userData + ); + + /** + * This function is deprecated, use vigem_target_ds4_await_output_report or + * vigem_target_ds4_await_output_report_timeout instead. Registers a function which gets called, + * when LightBar or vibration state changes occur on the provided target device. This function + * fails if the provided target device isn't fully operational or in an erroneous state. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param notification The notification callback. + * @param userData The user data passed to the notification callback. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_DEPRECATED VIGEM_ERROR vigem_target_ds4_register_notification( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PFN_VIGEM_DS4_NOTIFICATION notification, + LPVOID userData + ); + + /** + * Removes a previously registered callback function from the provided target object. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + */ + VIGEM_API void vigem_target_x360_unregister_notification( + PVIGEM_TARGET target + ); + + /** + * Removes a previously registered callback function from the provided target object. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + */ + VIGEM_API VIGEM_DEPRECATED void vigem_target_ds4_unregister_notification( + PVIGEM_TARGET target + ); + + /** + * Overrides the default Vendor ID value with the provided one. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + * @param vid The Vendor ID to set. + */ + VIGEM_API void vigem_target_set_vid( + PVIGEM_TARGET target, + USHORT vid + ); + + /** + * Overrides the default Product ID value with the provided one. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + * @param pid The Product ID to set. + */ + VIGEM_API void vigem_target_set_pid( + PVIGEM_TARGET target, + USHORT pid + ); + + /** + * Returns the Vendor ID of the provided target device object. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + * + * @returns The Vendor ID. + */ + VIGEM_API USHORT vigem_target_get_vid( + PVIGEM_TARGET target + ); + + /** + * Returns the Product ID of the provided target device object. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + * + * @returns The Product ID. + */ + VIGEM_API USHORT vigem_target_get_pid( + PVIGEM_TARGET target + ); + + /** + * Sends a state report to the provided target device. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param report The report to send to the target device. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_x360_update( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + XUSB_REPORT report + ); + + /** + * DEPRECATED. Sends a state report to the provided target device. It's recommended to use + * vigem_target_ds4_update_ex instead to utilize all DS4 features like touch, gyro etc. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param report The report to send to the target device. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_ds4_update( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + DS4_REPORT report + ); + + /** + * Sends a full size state report to the provided target device. It's recommended to use this + * function over vigem_target_ds4_update. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 07.09.2020 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param report The report buffer. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_ds4_update_ex( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + DS4_REPORT_EX report + ); + + /** + * Returns the internal index (serial number) the bus driver assigned to the provided + * target device object. Note that this value is specific to the inner workings of + * the bus driver, it does not reflect related values like player index or device + * arrival order experienced by other APIs. It may be used to identify the target + * device object for its lifetime. This value becomes invalid once the target + * device is removed from the bus and may change on the next addition of the + * device. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + * + * @returns The internally used index of the target device. + */ + VIGEM_API ULONG vigem_target_get_index( + PVIGEM_TARGET target + ); + + /** + * Returns the type of the provided target device object. + * + * @author Benjamin "Nefarius" Höglinger + * @date 28.08.2017 + * + * @param target The target device object. + * + * @returns A VIGEM_TARGET_TYPE. + */ + VIGEM_API VIGEM_TARGET_TYPE vigem_target_get_type( + PVIGEM_TARGET target + ); + + /** + * Returns TRUE if the provided target device object is currently attached to the bus, + * FALSE otherwise. + * + * @author Benjamin "Nefarius" Höglinger + * @date 30.08.2017 + * + * @param target The target device object. + * + * @returns TRUE if device is attached to the bus, FALSE otherwise. + */ + VIGEM_API BOOL vigem_target_is_attached( + PVIGEM_TARGET target + ); + + /** + * Returns the user index of the emulated Xenon device. This value correspondents to the + * (zero-based) index number representing the player number via LED present on a + * physical controller and is compatible to the dwUserIndex property of the + * XInput* APIs. + * + * @author Benjamin "Nefarius" Höglinger + * @date 10.05.2018 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param index The (zero-based) user index of the Xenon device. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_x360_get_user_index( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PULONG index + ); + + /** + * Waits until there's one or more pending raw output reports available to consume. This + * function blocks until data becomes available or the device gets disconnected. The waiting is + * event-based, meaning that as soon as a data packet is pending, this call returns a copy of + * the entire buffer. Each call returns a packet in the exact order it arrived in the driver. It + * is recommended to repeatedly call this function in a thread. The call aborts with an error + * code if the target gets unplugged in parallel. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 06.08.2022 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param buffer The fixed-size 64-bytes output report buffer that gets written to. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_ds4_await_output_report( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PDS4_OUTPUT_BUFFER buffer + ); + + /** + * Waits until there's one or more pending raw output reports available to consume. This + * function blocks until data becomes available, the provided timeout has been reached or the + * device gets disconnected. The waiting is event-based, meaning that as soon as a data packet + * is pending, this call returns a copy of the entire buffer. Each call returns a packet in the + * exact order it arrived in the driver. It is recommended to repeatedly call this function in a + * thread. A timeout of a few hundred milliseconds can be used to break out of the loop without + * excessive CPU consumption. The call aborts with an error code if the target gets unplugged in + * parallel. If a timeout of INFINITE is specified, the function basically behaves identical to + * vigem_target_ds4_await_output_report. + * + * @author Benjamin "Nefarius" Höglinger-Stelzer + * @date 12.08.2022 + * + * @param vigem The driver connection object. + * @param target The target device object. + * @param milliseconds The timeout in milliseconds. + * @param buffer The fixed-size 64-bytes output report buffer that gets written to. + * + * @returns A VIGEM_ERROR. + */ + VIGEM_API VIGEM_ERROR vigem_target_ds4_await_output_report_timeout( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + DWORD milliseconds, + PDS4_OUTPUT_BUFFER buffer + ); #ifdef __cplusplus } diff --git a/3rdparty/ViGEm/Common.h b/3rdparty/ViGEm/Common.h index fde8e30..9f9a0a2 100644 --- a/3rdparty/ViGEm/Common.h +++ b/3rdparty/ViGEm/Common.h @@ -33,15 +33,11 @@ typedef enum _VIGEM_TARGET_TYPE // // Microsoft Xbox 360 Controller (wired) // - Xbox360Wired, - // - // Microsoft Xbox One Controller (wired) - // - XboxOneWired, + Xbox360Wired = 0, // // Sony DualShock 4 (wired) // - DualShock4Wired + DualShock4Wired = 2 // NOTE: 1 skipped on purpose to maintain compatibility } VIGEM_TARGET_TYPE, *PVIGEM_TARGET_TYPE; @@ -204,3 +200,66 @@ VOID FORCEINLINE DS4_REPORT_INIT( DS4_SET_DPAD(Report, DS4_BUTTON_DPAD_NONE); } +#include // pack structs tightly +// +// DualShock 4 HID Touchpad structure +// +typedef struct _DS4_TOUCH +{ + BYTE bPacketCounter; // timestamp / packet counter associated with touch event + BYTE bIsUpTrackingNum1; // 0 means down; active low + // unique to each finger down, so for a lift and repress the value is incremented + BYTE bTouchData1[3]; // Two 12 bits values (for X and Y) + // middle byte holds last 4 bits of X and the starting 4 bits of Y + BYTE bIsUpTrackingNum2; // second touch data immediately follows data of first touch + BYTE bTouchData2[3]; // resolution is 1920x943 +} DS4_TOUCH, * PDS4_TOUCH; + +// +// DualShock 4 v1 complete HID Input report +// +typedef struct _DS4_REPORT_EX +{ + union + { + struct + { + BYTE bThumbLX; + BYTE bThumbLY; + BYTE bThumbRX; + BYTE bThumbRY; + USHORT wButtons; + BYTE bSpecial; + BYTE bTriggerL; + BYTE bTriggerR; + USHORT wTimestamp; + BYTE bBatteryLvl; + SHORT wGyroX; + SHORT wGyroY; + SHORT wGyroZ; + SHORT wAccelX; + SHORT wAccelY; + SHORT wAccelZ; + BYTE _bUnknown1[5]; + BYTE bBatteryLvlSpecial; + // really should have a enum to show everything that this can represent (USB charging, battery level; EXT, headset, microphone connected) + BYTE _bUnknown2[2]; + BYTE bTouchPacketsN; // 0x00 to 0x03 (USB max) + DS4_TOUCH sCurrentTouch; + DS4_TOUCH sPreviousTouch[2]; + } Report; + + UCHAR ReportBuffer[63]; + }; +} DS4_REPORT_EX, *PDS4_REPORT_EX; + +typedef struct _DS4_OUTPUT_BUFFER +{ + // + // The output report buffer + // + _Out_ UCHAR Buffer[64]; + +} DS4_OUTPUT_BUFFER, *PDS4_OUTPUT_BUFFER; + +#include diff --git a/3rdparty/ViGEm/km/BusShared.h b/3rdparty/ViGEm/km/BusShared.h index 9a1a69c..e87225b 100644 --- a/3rdparty/ViGEm/km/BusShared.h +++ b/3rdparty/ViGEm/km/BusShared.h @@ -59,17 +59,19 @@ DEFINE_GUID(GUID_DEVINTERFACE_BUSENUM_VIGEM, // // IO control codes // -#define IOCTL_VIGEM_PLUGIN_TARGET BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x000) -#define IOCTL_VIGEM_UNPLUG_TARGET BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x001) -#define IOCTL_VIGEM_CHECK_VERSION BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x002) +#define IOCTL_VIGEM_PLUGIN_TARGET BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x000) +#define IOCTL_VIGEM_UNPLUG_TARGET BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x001) +#define IOCTL_VIGEM_CHECK_VERSION BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x002) +#define IOCTL_VIGEM_WAIT_DEVICE_READY BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x003) -#define IOCTL_XUSB_REQUEST_NOTIFICATION BUSENUM_RW_IOCTL(IOCTL_VIGEM_BASE + 0x200) -#define IOCTL_XUSB_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x201) -#define IOCTL_DS4_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x202) -#define IOCTL_DS4_REQUEST_NOTIFICATION BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x203) -#define IOCTL_XGIP_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x204) -#define IOCTL_XGIP_SUBMIT_INTERRUPT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x205) -#define IOCTL_XUSB_GET_USER_INDEX BUSENUM_RW_IOCTL(IOCTL_VIGEM_BASE + 0x206) +#define IOCTL_XUSB_REQUEST_NOTIFICATION BUSENUM_RW_IOCTL(IOCTL_VIGEM_BASE + 0x200) +#define IOCTL_XUSB_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x201) +#define IOCTL_DS4_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x202) +#define IOCTL_DS4_REQUEST_NOTIFICATION BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x203) +//#define IOCTL_XGIP_SUBMIT_REPORT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x204) +//#define IOCTL_XGIP_SUBMIT_INTERRUPT BUSENUM_W_IOCTL (IOCTL_VIGEM_BASE + 0x205) +#define IOCTL_XUSB_GET_USER_INDEX BUSENUM_RW_IOCTL(IOCTL_VIGEM_BASE + 0x206) +#define IOCTL_DS4_AWAIT_OUTPUT_AVAILABLE BUSENUM_RW_IOCTL(IOCTL_VIGEM_BASE + 0x207) // @@ -184,6 +186,29 @@ VOID FORCEINLINE VIGEM_CHECK_VERSION_INIT( CheckVersion->Version = Version; } +#pragma endregion + +#pragma region Wait device ready + +typedef struct _VIGEM_WAIT_DEVICE_READY +{ + IN ULONG Size; + + IN ULONG SerialNo; + +} VIGEM_WAIT_DEVICE_READY, * PVIGEM_WAIT_DEVICE_READY; + +VOID FORCEINLINE VIGEM_WAIT_DEVICE_READY_INIT( + _Out_ PVIGEM_WAIT_DEVICE_READY WaitReady, + _In_ ULONG SerialNo +) +{ + RtlZeroMemory(WaitReady, sizeof(VIGEM_WAIT_DEVICE_READY)); + + WaitReady->Size = sizeof(VIGEM_WAIT_DEVICE_READY); + WaitReady->SerialNo = SerialNo; +} + #pragma endregion #pragma region XUSB (aka Xbox 360 device) section @@ -400,99 +425,82 @@ VOID FORCEINLINE DS4_SUBMIT_REPORT_INIT( DS4_REPORT_INIT(&Report->Report); } -#pragma endregion - -#pragma region XGIP (aka Xbox One device) section - EXPERIMENTAL - -typedef struct _XGIP_REPORT -{ - UCHAR Buttons1; - UCHAR Buttons2; - SHORT LeftTrigger; - SHORT RightTrigger; - SHORT ThumbLX; - SHORT ThumbLY; - SHORT ThumbRX; - SHORT ThumbRY; - -} XGIP_REPORT, *PXGIP_REPORT; +#include // -// Xbox One request data +// DualShock 4 extended report request // -typedef struct _XGIP_SUBMIT_REPORT +typedef struct _DS4_SUBMIT_REPORT_EX { // - // sizeof(struct _XGIP_SUBMIT_REPORT) - // - ULONG Size; + // sizeof(struct _DS4_SUBMIT_REPORT_EX) + // + _In_ ULONG Size; // // Serial number of target device. // - ULONG SerialNo; + _In_ ULONG SerialNo; // - // HID Input report + // Full size HID report excluding fixed Report ID. // - XGIP_REPORT Report; + _In_ DS4_REPORT_EX Report; + +} DS4_SUBMIT_REPORT_EX, * PDS4_SUBMIT_REPORT_EX; -} XGIP_SUBMIT_REPORT, *PXGIP_SUBMIT_REPORT; +#include // -// Initializes an Xbox One report. +// Initializes a DualShock 4 extended report. // -VOID FORCEINLINE XGIP_SUBMIT_REPORT_INIT( - _Out_ PXGIP_SUBMIT_REPORT Report, +VOID FORCEINLINE DS4_SUBMIT_REPORT_EX_INIT( + _Out_ PDS4_SUBMIT_REPORT_EX Report, _In_ ULONG SerialNo ) { - RtlZeroMemory(Report, sizeof(XGIP_SUBMIT_REPORT)); + RtlZeroMemory(Report, sizeof(DS4_SUBMIT_REPORT_EX)); - Report->Size = sizeof(XGIP_SUBMIT_REPORT); + Report->Size = sizeof(DS4_SUBMIT_REPORT_EX); Report->SerialNo = SerialNo; } -// -// Xbox One interrupt data -// -typedef struct _XGIP_SUBMIT_INTERRUPT -{ - // - // sizeof(struct _XGIP_SUBMIT_INTERRUPT) - // - ULONG Size; +#pragma endregion - // - // Serial number of target device. - // - ULONG SerialNo; +#pragma region DS4 Await Output - // - // Interrupt buffer. - // - UCHAR Interrupt[64]; +#include + +typedef struct _DS4_AWAIT_OUTPUT +{ + // + // sizeof(struct _DS4_AWAIT_OUTPUT) + // + _In_ ULONG Size; + + // + // Serial number of target device. + // + _Inout_ ULONG SerialNo; // - // Length of interrupt buffer. + // The payload // - ULONG InterruptLength; + _Out_ DS4_OUTPUT_BUFFER Report; + +} DS4_AWAIT_OUTPUT, * PDS4_AWAIT_OUTPUT; -} XGIP_SUBMIT_INTERRUPT, *PXGIP_SUBMIT_INTERRUPT; +#include -// -// Initializes an Xbox One interrupt. -// -VOID FORCEINLINE XGIP_SUBMIT_INTERRUPT_INIT( - _Out_ PXGIP_SUBMIT_INTERRUPT Report, +VOID FORCEINLINE DS4_AWAIT_OUTPUT_INIT( + _Out_ PDS4_AWAIT_OUTPUT Output, _In_ ULONG SerialNo ) { - RtlZeroMemory(Report, sizeof(XGIP_SUBMIT_INTERRUPT)); + RtlZeroMemory(Output, sizeof(DS4_AWAIT_OUTPUT)); - Report->Size = sizeof(XGIP_SUBMIT_INTERRUPT); - Report->SerialNo = SerialNo; + Output->Size = sizeof(DS4_AWAIT_OUTPUT); + Output->SerialNo = SerialNo; } #pragma endregion - diff --git a/3rdparty/libusb-1.0/MS32/libusb-1.0.dll b/3rdparty/libusb-1.0/MS32/libusb-1.0.dll index 4eda7fa..52ad17b 100644 Binary files a/3rdparty/libusb-1.0/MS32/libusb-1.0.dll and b/3rdparty/libusb-1.0/MS32/libusb-1.0.dll differ diff --git a/3rdparty/libusb-1.0/MS32/libusb-1.0.lib b/3rdparty/libusb-1.0/MS32/libusb-1.0.lib index a33f195..b606db8 100644 Binary files a/3rdparty/libusb-1.0/MS32/libusb-1.0.lib and b/3rdparty/libusb-1.0/MS32/libusb-1.0.lib differ diff --git a/3rdparty/libusb-1.0/MS32/libusb-1.0.pdb b/3rdparty/libusb-1.0/MS32/libusb-1.0.pdb index dad20ae..e245239 100644 Binary files a/3rdparty/libusb-1.0/MS32/libusb-1.0.pdb and b/3rdparty/libusb-1.0/MS32/libusb-1.0.pdb differ diff --git a/3rdparty/libusb-1.0/MS64/libusb-1.0.dll b/3rdparty/libusb-1.0/MS64/libusb-1.0.dll index b6d3aa2..137897c 100644 Binary files a/3rdparty/libusb-1.0/MS64/libusb-1.0.dll and b/3rdparty/libusb-1.0/MS64/libusb-1.0.dll differ diff --git a/3rdparty/libusb-1.0/MS64/libusb-1.0.lib b/3rdparty/libusb-1.0/MS64/libusb-1.0.lib index 80f7a7a..40465ee 100644 Binary files a/3rdparty/libusb-1.0/MS64/libusb-1.0.lib and b/3rdparty/libusb-1.0/MS64/libusb-1.0.lib differ diff --git a/3rdparty/libusb-1.0/MS64/libusb-1.0.pdb b/3rdparty/libusb-1.0/MS64/libusb-1.0.pdb index 810b505..049a58b 100644 Binary files a/3rdparty/libusb-1.0/MS64/libusb-1.0.pdb and b/3rdparty/libusb-1.0/MS64/libusb-1.0.pdb differ diff --git a/3rdparty/libusb-1.0/libusb.h b/3rdparty/libusb-1.0/libusb.h index 430136b..2592ea7 100644 --- a/3rdparty/libusb-1.0/libusb.h +++ b/3rdparty/libusb-1.0/libusb.h @@ -3,7 +3,8 @@ * Copyright © 2001 Johannes Erdfelt * Copyright © 2007-2008 Daniel Drake * Copyright © 2012 Pete Batard - * Copyright © 2012 Nathan Hjelm + * Copyright © 2012-2018 Nathan Hjelm + * Copyright © 2014-2020 Chris Dickens * For more information, please visit: http://libusb.info * * This library is free software; you can redistribute it and/or @@ -24,55 +25,42 @@ #ifndef LIBUSB_H #define LIBUSB_H -#ifdef _MSC_VER +#if defined(_MSC_VER) +#pragma warning(push) +/* Disable: warning C4200: nonstandard extension used : zero-sized array in struct/union */ +#pragma warning(disable:4200) /* on MS environments, the inline keyword is available in C++ only */ #if !defined(__cplusplus) #define inline __inline #endif -/* ssize_t is also not available (copy/paste from MinGW) */ +/* ssize_t is also not available */ #ifndef _SSIZE_T_DEFINED #define _SSIZE_T_DEFINED -#undef ssize_t -#ifdef _WIN64 - typedef __int64 ssize_t; -#else - typedef int ssize_t; -#endif /* _WIN64 */ +#include +typedef SSIZE_T ssize_t; #endif /* _SSIZE_T_DEFINED */ #endif /* _MSC_VER */ -/* stdint.h is not available on older MSVC */ -#if defined(_MSC_VER) && (_MSC_VER < 1600) && (!defined(_STDINT)) && (!defined(_STDINT_H)) -typedef unsigned __int8 uint8_t; -typedef unsigned __int16 uint16_t; -typedef unsigned __int32 uint32_t; -#else +#include #include -#endif - -#if !defined(_WIN32_WCE) #include -#endif - -#if defined(__linux__) || defined(__APPLE__) || defined(__CYGWIN__) || defined(__HAIKU__) +#if !defined(_MSC_VER) #include #endif - #include -#include #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) #define ZERO_SIZED_ARRAY /* [] - valid C99 code */ #else #define ZERO_SIZED_ARRAY 0 /* [0] - non-standard, but usually working code */ -#endif +#endif /* __STDC_VERSION__ */ /* 'interface' might be defined as a macro on Windows, so we need to * undefine it so as not to break the current libusb API, because * libusb_config_descriptor has an 'interface' member * As this can be problematic if you include windows.h after libusb.h * in your sources, we force windows.h to be included first. */ -#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(__CYGWIN__) #include #if defined(interface) #undef interface @@ -80,17 +68,22 @@ typedef unsigned __int32 uint32_t; #if !defined(__CYGWIN__) #include #endif -#endif +#endif /* _WIN32 || __CYGWIN__ */ -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) -#define LIBUSB_DEPRECATED_FOR(f) \ - __attribute__((deprecated("Use " #f " instead"))) -#elif __GNUC__ >= 3 -#define LIBUSB_DEPRECATED_FOR(f) __attribute__((deprecated)) +#if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) +#define LIBUSB_DEPRECATED_FOR(f) __attribute__ ((deprecated ("Use " #f " instead"))) +#elif defined(__GNUC__) && (__GNUC__ >= 3) +#define LIBUSB_DEPRECATED_FOR(f) __attribute__ ((deprecated)) #else #define LIBUSB_DEPRECATED_FOR(f) #endif /* __GNUC__ */ +#if defined(__GNUC__) +#define LIBUSB_PACKED __attribute__ ((packed)) +#else +#define LIBUSB_PACKED +#endif /* __GNUC__ */ + /** \def LIBUSB_CALL * \ingroup libusb_misc * libusb's Windows calling convention. @@ -123,11 +116,11 @@ typedef unsigned __int32 uint32_t; * return type, before the function name. See internal documentation for * API_EXPORTED. */ -#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) +#if defined(_WIN32) || defined(__CYGWIN__) #define LIBUSB_CALL WINAPI #else #define LIBUSB_CALL -#endif +#endif /* _WIN32 || __CYGWIN__ */ /** \def LIBUSB_API_VERSION * \ingroup libusb_misc @@ -149,12 +142,12 @@ typedef unsigned __int32 uint32_t; * Internally, LIBUSB_API_VERSION is defined as follows: * (libusb major << 24) | (libusb minor << 16) | (16 bit incremental) */ -#define LIBUSB_API_VERSION 0x01000106 +#define LIBUSB_API_VERSION 0x01000109 /* The following is kept for compatibility, but will be deprecated in the future */ #define LIBUSBX_API_VERSION LIBUSB_API_VERSION -#ifdef __cplusplus +#if defined(__cplusplus) extern "C" { #endif @@ -196,35 +189,35 @@ enum libusb_class_code { * this bDeviceClass value indicates that each interface specifies its * own class information and all interfaces operate independently. */ - LIBUSB_CLASS_PER_INTERFACE = 0, + LIBUSB_CLASS_PER_INTERFACE = 0x00, /** Audio class */ - LIBUSB_CLASS_AUDIO = 1, + LIBUSB_CLASS_AUDIO = 0x01, /** Communications class */ - LIBUSB_CLASS_COMM = 2, + LIBUSB_CLASS_COMM = 0x02, /** Human Interface Device class */ - LIBUSB_CLASS_HID = 3, + LIBUSB_CLASS_HID = 0x03, /** Physical */ - LIBUSB_CLASS_PHYSICAL = 5, - - /** Printer class */ - LIBUSB_CLASS_PRINTER = 7, + LIBUSB_CLASS_PHYSICAL = 0x05, /** Image class */ - LIBUSB_CLASS_PTP = 6, /* legacy name from libusb-0.1 usb.h */ - LIBUSB_CLASS_IMAGE = 6, + LIBUSB_CLASS_IMAGE = 0x06, + LIBUSB_CLASS_PTP = 0x06, /* legacy name from libusb-0.1 usb.h */ + + /** Printer class */ + LIBUSB_CLASS_PRINTER = 0x07, /** Mass storage class */ - LIBUSB_CLASS_MASS_STORAGE = 8, + LIBUSB_CLASS_MASS_STORAGE = 0x08, /** Hub class */ - LIBUSB_CLASS_HUB = 9, + LIBUSB_CLASS_HUB = 0x09, /** Data class */ - LIBUSB_CLASS_DATA = 10, + LIBUSB_CLASS_DATA = 0x0a, /** Smart Card */ LIBUSB_CLASS_SMART_CARD = 0x0b, @@ -244,6 +237,9 @@ enum libusb_class_code { /** Wireless class */ LIBUSB_CLASS_WIRELESS = 0xe0, + /** Miscellaneous class */ + LIBUSB_CLASS_MISCELLANEOUS = 0xef, + /** Application class */ LIBUSB_CLASS_APPLICATION = 0xfe, @@ -311,12 +307,13 @@ enum libusb_descriptor_type { #define LIBUSB_BT_CONTAINER_ID_SIZE 20 /* We unwrap the BOS => define its max size */ -#define LIBUSB_DT_BOS_MAX_SIZE ((LIBUSB_DT_BOS_SIZE) +\ - (LIBUSB_BT_USB_2_0_EXTENSION_SIZE) +\ - (LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE) +\ - (LIBUSB_BT_CONTAINER_ID_SIZE)) +#define LIBUSB_DT_BOS_MAX_SIZE \ + (LIBUSB_DT_BOS_SIZE + \ + LIBUSB_BT_USB_2_0_EXTENSION_SIZE + \ + LIBUSB_BT_SS_USB_DEVICE_CAPABILITY_SIZE + \ + LIBUSB_BT_CONTAINER_ID_SIZE) -#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */ +#define LIBUSB_ENDPOINT_ADDRESS_MASK 0x0f /* in bEndpointAddress */ #define LIBUSB_ENDPOINT_DIR_MASK 0x80 /** \ingroup libusb_desc @@ -324,34 +321,31 @@ enum libusb_descriptor_type { * \ref libusb_endpoint_descriptor::bEndpointAddress "endpoint address" scheme. */ enum libusb_endpoint_direction { - /** In: device-to-host */ - LIBUSB_ENDPOINT_IN = 0x80, - /** Out: host-to-device */ - LIBUSB_ENDPOINT_OUT = 0x00 + LIBUSB_ENDPOINT_OUT = 0x00, + + /** In: device-to-host */ + LIBUSB_ENDPOINT_IN = 0x80 }; -#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */ +#define LIBUSB_TRANSFER_TYPE_MASK 0x03 /* in bmAttributes */ /** \ingroup libusb_desc * Endpoint transfer type. Values for bits 0:1 of the * \ref libusb_endpoint_descriptor::bmAttributes "endpoint attributes" field. */ -enum libusb_transfer_type { +enum libusb_endpoint_transfer_type { /** Control endpoint */ - LIBUSB_TRANSFER_TYPE_CONTROL = 0, + LIBUSB_ENDPOINT_TRANSFER_TYPE_CONTROL = 0x0, /** Isochronous endpoint */ - LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1, + LIBUSB_ENDPOINT_TRANSFER_TYPE_ISOCHRONOUS = 0x1, /** Bulk endpoint */ - LIBUSB_TRANSFER_TYPE_BULK = 2, + LIBUSB_ENDPOINT_TRANSFER_TYPE_BULK = 0x2, /** Interrupt endpoint */ - LIBUSB_TRANSFER_TYPE_INTERRUPT = 3, - - /** Stream endpoint */ - LIBUSB_TRANSFER_TYPE_BULK_STREAM = 4, + LIBUSB_ENDPOINT_TRANSFER_TYPE_INTERRUPT = 0x3 }; /** \ingroup libusb_misc @@ -386,20 +380,20 @@ enum libusb_standard_request { LIBUSB_REQUEST_SET_CONFIGURATION = 0x09, /** Return the selected alternate setting for the specified interface */ - LIBUSB_REQUEST_GET_INTERFACE = 0x0A, + LIBUSB_REQUEST_GET_INTERFACE = 0x0a, /** Select an alternate interface for the specified interface */ - LIBUSB_REQUEST_SET_INTERFACE = 0x0B, + LIBUSB_REQUEST_SET_INTERFACE = 0x0b, /** Set then report an endpoint's synchronization frame */ - LIBUSB_REQUEST_SYNCH_FRAME = 0x0C, + LIBUSB_REQUEST_SYNCH_FRAME = 0x0c, /** Sets both the U1 and U2 Exit Latency */ LIBUSB_REQUEST_SET_SEL = 0x30, /** Delay from the time a host transmits a packet to the time it is * received by the device. */ - LIBUSB_SET_ISOCH_DELAY = 0x31, + LIBUSB_SET_ISOCH_DELAY = 0x31 }; /** \ingroup libusb_misc @@ -435,10 +429,10 @@ enum libusb_request_recipient { LIBUSB_RECIPIENT_ENDPOINT = 0x02, /** Other */ - LIBUSB_RECIPIENT_OTHER = 0x03, + LIBUSB_RECIPIENT_OTHER = 0x03 }; -#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0C +#define LIBUSB_ISO_SYNC_TYPE_MASK 0x0c /** \ingroup libusb_desc * Synchronization type for isochronous endpoints. Values for bits 2:3 of the @@ -447,19 +441,19 @@ enum libusb_request_recipient { */ enum libusb_iso_sync_type { /** No synchronization */ - LIBUSB_ISO_SYNC_TYPE_NONE = 0, + LIBUSB_ISO_SYNC_TYPE_NONE = 0x0, /** Asynchronous */ - LIBUSB_ISO_SYNC_TYPE_ASYNC = 1, + LIBUSB_ISO_SYNC_TYPE_ASYNC = 0x1, /** Adaptive */ - LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 2, + LIBUSB_ISO_SYNC_TYPE_ADAPTIVE = 0x2, /** Synchronous */ - LIBUSB_ISO_SYNC_TYPE_SYNC = 3 + LIBUSB_ISO_SYNC_TYPE_SYNC = 0x3 }; -#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30 +#define LIBUSB_ISO_USAGE_TYPE_MASK 0x30 /** \ingroup libusb_desc * Usage type for isochronous endpoints. Values for bits 4:5 of the @@ -468,13 +462,68 @@ enum libusb_iso_sync_type { */ enum libusb_iso_usage_type { /** Data endpoint */ - LIBUSB_ISO_USAGE_TYPE_DATA = 0, + LIBUSB_ISO_USAGE_TYPE_DATA = 0x0, /** Feedback endpoint */ - LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 1, + LIBUSB_ISO_USAGE_TYPE_FEEDBACK = 0x1, /** Implicit feedback Data endpoint */ - LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 2, + LIBUSB_ISO_USAGE_TYPE_IMPLICIT = 0x2 +}; + +/** \ingroup libusb_desc + * Supported speeds (wSpeedSupported) bitfield. Indicates what + * speeds the device supports. + */ +enum libusb_supported_speed { + /** Low speed operation supported (1.5MBit/s). */ + LIBUSB_LOW_SPEED_OPERATION = (1 << 0), + + /** Full speed operation supported (12MBit/s). */ + LIBUSB_FULL_SPEED_OPERATION = (1 << 1), + + /** High speed operation supported (480MBit/s). */ + LIBUSB_HIGH_SPEED_OPERATION = (1 << 2), + + /** Superspeed operation supported (5000MBit/s). */ + LIBUSB_SUPER_SPEED_OPERATION = (1 << 3) +}; + +/** \ingroup libusb_desc + * Masks for the bits of the + * \ref libusb_usb_2_0_extension_descriptor::bmAttributes "bmAttributes" field + * of the USB 2.0 Extension descriptor. + */ +enum libusb_usb_2_0_extension_attributes { + /** Supports Link Power Management (LPM) */ + LIBUSB_BM_LPM_SUPPORT = (1 << 1) +}; + +/** \ingroup libusb_desc + * Masks for the bits of the + * \ref libusb_ss_usb_device_capability_descriptor::bmAttributes "bmAttributes" field + * field of the SuperSpeed USB Device Capability descriptor. + */ +enum libusb_ss_usb_device_capability_attributes { + /** Supports Latency Tolerance Messages (LTM) */ + LIBUSB_BM_LTM_SUPPORT = (1 << 1) +}; + +/** \ingroup libusb_desc + * USB capability types + */ +enum libusb_bos_type { + /** Wireless USB device capability */ + LIBUSB_BT_WIRELESS_USB_DEVICE_CAPABILITY = 0x01, + + /** USB 2.0 extensions */ + LIBUSB_BT_USB_2_0_EXTENSION = 0x02, + + /** SuperSpeed USB device capability */ + LIBUSB_BT_SS_USB_DEVICE_CAPABILITY = 0x03, + + /** Container ID type */ + LIBUSB_BT_CONTAINER_ID = 0x04 }; /** \ingroup libusb_desc @@ -547,17 +596,15 @@ struct libusb_endpoint_descriptor { /** The address of the endpoint described by this descriptor. Bits 0:3 are * the endpoint number. Bits 4:6 are reserved. Bit 7 indicates direction, - * see \ref libusb_endpoint_direction. - */ + * see \ref libusb_endpoint_direction. */ uint8_t bEndpointAddress; /** Attributes which apply to the endpoint when it is configured using * the bConfigurationValue. Bits 0:1 determine the transfer type and - * correspond to \ref libusb_transfer_type. Bits 2:3 are only used for - * isochronous endpoints and correspond to \ref libusb_iso_sync_type. + * correspond to \ref libusb_endpoint_transfer_type. Bits 2:3 are only used + * for isochronous endpoints and correspond to \ref libusb_iso_sync_type. * Bits 4:5 are also only used for isochronous endpoints and correspond to - * \ref libusb_iso_usage_type. Bits 6:7 are reserved. - */ + * \ref libusb_iso_usage_type. Bits 6:7 are reserved. */ uint8_t bmAttributes; /** Maximum packet size this endpoint is capable of sending/receiving. */ @@ -577,7 +624,7 @@ struct libusb_endpoint_descriptor { * it will store them here, should you wish to parse them. */ const unsigned char *extra; - /** Length of the extra descriptors, in bytes. */ + /** Length of the extra descriptors, in bytes. Must be non-negative. */ int extra_length; }; @@ -627,7 +674,7 @@ struct libusb_interface_descriptor { * it will store them here, should you wish to parse them. */ const unsigned char *extra; - /** Length of the extra descriptors, in bytes. */ + /** Length of the extra descriptors, in bytes. Must be non-negative. */ int extra_length; }; @@ -639,7 +686,8 @@ struct libusb_interface { * by the num_altsetting field. */ const struct libusb_interface_descriptor *altsetting; - /** The number of alternate settings that belong to this interface */ + /** The number of alternate settings that belong to this interface. + * Must be non-negative. */ int num_altsetting; }; @@ -686,7 +734,7 @@ struct libusb_config_descriptor { * descriptors, it will store them here, should you wish to parse them. */ const unsigned char *extra; - /** Length of the extra descriptors, in bytes. */ + /** Length of the extra descriptors, in bytes. Must be non-negative. */ int extra_length; }; @@ -697,7 +745,6 @@ struct libusb_config_descriptor { * host-endian format. */ struct libusb_ss_endpoint_companion_descriptor { - /** Size of this descriptor (in bytes) */ uint8_t bLength; @@ -706,19 +753,18 @@ struct libusb_ss_endpoint_companion_descriptor { * this context. */ uint8_t bDescriptorType; - /** The maximum number of packets the endpoint can send or * receive as part of a burst. */ uint8_t bMaxBurst; - /** In bulk EP: bits 4:0 represents the maximum number of - * streams the EP supports. In isochronous EP: bits 1:0 - * represents the Mult - a zero based value that determines - * the maximum number of packets within a service interval */ + /** In bulk EP: bits 4:0 represents the maximum number of + * streams the EP supports. In isochronous EP: bits 1:0 + * represents the Mult - a zero based value that determines + * the maximum number of packets within a service interval */ uint8_t bmAttributes; - /** The total number of bytes this EP will transfer every - * service interval. valid only for periodic EPs. */ + /** The total number of bytes this EP will transfer every + * service interval. Valid only for periodic EPs. */ uint16_t wBytesPerInterval; }; @@ -729,15 +775,18 @@ struct libusb_ss_endpoint_companion_descriptor { */ struct libusb_bos_dev_capability_descriptor { /** Size of this descriptor (in bytes) */ - uint8_t bLength; + uint8_t bLength; + /** Descriptor type. Will have value * \ref libusb_descriptor_type::LIBUSB_DT_DEVICE_CAPABILITY * LIBUSB_DT_DEVICE_CAPABILITY in this context. */ - uint8_t bDescriptorType; + uint8_t bDescriptorType; + /** Device Capability type */ - uint8_t bDevCapabilityType; + uint8_t bDevCapabilityType; + /** Device Capability data (bLength - 3 bytes) */ - uint8_t dev_capability_data[ZERO_SIZED_ARRAY]; + uint8_t dev_capability_data[ZERO_SIZED_ARRAY]; }; /** \ingroup libusb_desc @@ -788,7 +837,7 @@ struct libusb_usb_2_0_extension_descriptor { * A value of one in a bit location indicates a feature is * supported; a value of zero indicates it is not supported. * See \ref libusb_usb_2_0_extension_attributes. */ - uint32_t bmAttributes; + uint32_t bmAttributes; }; /** \ingroup libusb_desc @@ -853,7 +902,7 @@ struct libusb_container_id_descriptor { uint8_t bDevCapabilityType; /** Reserved field */ - uint8_t bReserved; + uint8_t bReserved; /** 128 bit UUID */ uint8_t ContainerID[16]; @@ -861,6 +910,9 @@ struct libusb_container_id_descriptor { /** \ingroup libusb_asyncio * Setup packet for control transfers. */ +#if defined(_MSC_VER) || defined(__WATCOMC__) +#pragma pack(push, 1) +#endif struct libusb_control_setup { /** Request type. Bits 0:4 determine recipient, see * \ref libusb_request_recipient. Bits 5:6 determine type, see @@ -885,7 +937,10 @@ struct libusb_control_setup { /** Number of bytes to transfer */ uint16_t wLength; -}; +} LIBUSB_PACKED; +#if defined(_MSC_VER) || defined(__WATCOMC__) +#pragma pack(pop) +#endif #define LIBUSB_CONTROL_SETUP_SIZE (sizeof(struct libusb_control_setup)) @@ -915,7 +970,7 @@ struct libusb_version { const char *rc; /** For ABI compatibility only. */ - const char* describe; + const char *describe; }; /** \ingroup libusb_lib @@ -930,8 +985,9 @@ struct libusb_version { * Sessions are created by libusb_init() and destroyed through libusb_exit(). * If your application is guaranteed to only ever include a single libusb * user (i.e. you), you do not have to worry about contexts: pass NULL in - * every function call where a context is required. The default context - * will be used. + * every function call where a context is required, and the default context + * will be used. Note that libusb_set_option(NULL, ...) is special, and adds + * an option to a list of default options for new contexts. * * For more information, see \ref libusb_contexts. */ @@ -940,7 +996,7 @@ typedef struct libusb_context libusb_context; /** \ingroup libusb_dev * Structure representing a USB device detected on the system. This is an * opaque type for which you are only ever provided with a pointer, usually - * originating from libusb_get_device_list(). + * originating from libusb_get_device_list() or libusb_hotplug_register_callback(). * * Certain operations can be performed on a device, but in order to do any * I/O you will have to first obtain a device handle using libusb_open(). @@ -985,62 +1041,7 @@ enum libusb_speed { LIBUSB_SPEED_SUPER = 4, /** The device is operating at super speed plus (10000MBit/s). */ - LIBUSB_SPEED_SUPER_PLUS = 5, -}; - -/** \ingroup libusb_dev - * Supported speeds (wSpeedSupported) bitfield. Indicates what - * speeds the device supports. - */ -enum libusb_supported_speed { - /** Low speed operation supported (1.5MBit/s). */ - LIBUSB_LOW_SPEED_OPERATION = 1, - - /** Full speed operation supported (12MBit/s). */ - LIBUSB_FULL_SPEED_OPERATION = 2, - - /** High speed operation supported (480MBit/s). */ - LIBUSB_HIGH_SPEED_OPERATION = 4, - - /** Superspeed operation supported (5000MBit/s). */ - LIBUSB_SUPER_SPEED_OPERATION = 8, -}; - -/** \ingroup libusb_dev - * Masks for the bits of the - * \ref libusb_usb_2_0_extension_descriptor::bmAttributes "bmAttributes" field - * of the USB 2.0 Extension descriptor. - */ -enum libusb_usb_2_0_extension_attributes { - /** Supports Link Power Management (LPM) */ - LIBUSB_BM_LPM_SUPPORT = 2, -}; - -/** \ingroup libusb_dev - * Masks for the bits of the - * \ref libusb_ss_usb_device_capability_descriptor::bmAttributes "bmAttributes" field - * field of the SuperSpeed USB Device Capability descriptor. - */ -enum libusb_ss_usb_device_capability_attributes { - /** Supports Latency Tolerance Messages (LTM) */ - LIBUSB_BM_LTM_SUPPORT = 2, -}; - -/** \ingroup libusb_dev - * USB capability types - */ -enum libusb_bos_type { - /** Wireless USB device capability */ - LIBUSB_BT_WIRELESS_USB_DEVICE_CAPABILITY = 1, - - /** USB 2.0 extensions */ - LIBUSB_BT_USB_2_0_EXTENSION = 2, - - /** SuperSpeed USB device capability */ - LIBUSB_BT_SS_USB_DEVICE_CAPABILITY = 3, - - /** Container ID type */ - LIBUSB_BT_CONTAINER_ID = 4, + LIBUSB_SPEED_SUPER_PLUS = 5 }; /** \ingroup libusb_misc @@ -1094,12 +1095,31 @@ enum libusb_error { message strings in strerror.c when adding new error codes here. */ /** Other error */ - LIBUSB_ERROR_OTHER = -99, + LIBUSB_ERROR_OTHER = -99 }; /* Total number of error codes in enum libusb_error */ #define LIBUSB_ERROR_COUNT 14 +/** \ingroup libusb_asyncio + * Transfer type */ +enum libusb_transfer_type { + /** Control transfer */ + LIBUSB_TRANSFER_TYPE_CONTROL = 0U, + + /** Isochronous transfer */ + LIBUSB_TRANSFER_TYPE_ISOCHRONOUS = 1U, + + /** Bulk transfer */ + LIBUSB_TRANSFER_TYPE_BULK = 2U, + + /** Interrupt transfer */ + LIBUSB_TRANSFER_TYPE_INTERRUPT = 3U, + + /** Bulk stream transfer */ + LIBUSB_TRANSFER_TYPE_BULK_STREAM = 4U +}; + /** \ingroup libusb_asyncio * Transfer status codes */ enum libusb_transfer_status { @@ -1124,7 +1144,7 @@ enum libusb_transfer_status { LIBUSB_TRANSFER_NO_DEVICE, /** Device sent more data than requested */ - LIBUSB_TRANSFER_OVERFLOW, + LIBUSB_TRANSFER_OVERFLOW /* NB! Remember to update libusb_error_name() when adding new status codes here. */ @@ -1134,19 +1154,19 @@ enum libusb_transfer_status { * libusb_transfer.flags values */ enum libusb_transfer_flags { /** Report short frames as errors */ - LIBUSB_TRANSFER_SHORT_NOT_OK = 1<<0, + LIBUSB_TRANSFER_SHORT_NOT_OK = (1U << 0), /** Automatically free() transfer buffer during libusb_free_transfer(). * Note that buffers allocated with libusb_dev_mem_alloc() should not * be attempted freed in this way, since free() is not an appropriate * way to release such memory. */ - LIBUSB_TRANSFER_FREE_BUFFER = 1<<1, + LIBUSB_TRANSFER_FREE_BUFFER = (1U << 1), /** Automatically call libusb_free_transfer() after callback returns. * If this flag is set, it is illegal to call libusb_free_transfer() * from your transfer callback, as this will result in a double-free * when this flag is acted upon. */ - LIBUSB_TRANSFER_FREE_TRANSFER = 1<<2, + LIBUSB_TRANSFER_FREE_TRANSFER = (1U << 2), /** Terminate transfers that are a multiple of the endpoint's * wMaxPacketSize with an extra zero length packet. This is useful @@ -1171,7 +1191,7 @@ enum libusb_transfer_flags { * * Available since libusb-1.0.9. */ - LIBUSB_TRANSFER_ADD_ZERO_PACKET = 1 << 3, + LIBUSB_TRANSFER_ADD_ZERO_PACKET = (1U << 3) }; /** \ingroup libusb_asyncio @@ -1216,7 +1236,7 @@ struct libusb_transfer { /** Address of the endpoint where this transfer will be sent. */ unsigned char endpoint; - /** Type of the endpoint from \ref libusb_transfer_type */ + /** Type of the transfer from \ref libusb_transfer_type */ unsigned char type; /** Timeout for this transfer in milliseconds. A value of 0 indicates no @@ -1232,7 +1252,7 @@ struct libusb_transfer { * to determine if errors occurred. */ enum libusb_transfer_status status; - /** Length of the data buffer */ + /** Length of the data buffer. Must be non-negative. */ int length; /** Actual length of data that was transferred. Read-only, and only for @@ -1244,14 +1264,23 @@ struct libusb_transfer { * fails, or is cancelled. */ libusb_transfer_cb_fn callback; - /** User context data to pass to the callback function. */ + /** User context data. Useful for associating specific data to a transfer + * that can be accessed from within the callback function. + * + * This field may be set manually or is taken as the `user_data` parameter + * of the following functions: + * - libusb_fill_bulk_transfer() + * - libusb_fill_bulk_stream_transfer() + * - libusb_fill_control_transfer() + * - libusb_fill_interrupt_transfer() + * - libusb_fill_iso_transfer() */ void *user_data; /** Data buffer */ unsigned char *buffer; /** Number of isochronous packets. Only used for I/O with isochronous - * endpoints. */ + * endpoints. Must be non-negative. */ int num_iso_packets; /** Isochronous packet descriptors, for isochronous transfers only. */ @@ -1265,44 +1294,81 @@ struct libusb_transfer { */ enum libusb_capability { /** The libusb_has_capability() API is available. */ - LIBUSB_CAP_HAS_CAPABILITY = 0x0000, + LIBUSB_CAP_HAS_CAPABILITY = 0x0000U, + /** Hotplug support is available on this platform. */ - LIBUSB_CAP_HAS_HOTPLUG = 0x0001, + LIBUSB_CAP_HAS_HOTPLUG = 0x0001U, + /** The library can access HID devices without requiring user intervention. * Note that before being able to actually access an HID device, you may * still have to call additional libusb functions such as * \ref libusb_detach_kernel_driver(). */ - LIBUSB_CAP_HAS_HID_ACCESS = 0x0100, - /** The library supports detaching of the default USB driver, using + LIBUSB_CAP_HAS_HID_ACCESS = 0x0100U, + + /** The library supports detaching of the default USB driver, using * \ref libusb_detach_kernel_driver(), if one is set by the OS kernel */ - LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101 + LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER = 0x0101U }; /** \ingroup libusb_lib * Log message levels. - * - LIBUSB_LOG_LEVEL_NONE (0) : no messages ever printed by the library (default) - * - LIBUSB_LOG_LEVEL_ERROR (1) : error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_WARNING (2) : warning and error messages are printed to stderr - * - LIBUSB_LOG_LEVEL_INFO (3) : informational messages are printed to stderr - * - LIBUSB_LOG_LEVEL_DEBUG (4) : debug and informational messages are printed to stderr */ enum libusb_log_level { + /** (0) : No messages ever emitted by the library (default) */ LIBUSB_LOG_LEVEL_NONE = 0, + + /** (1) : Error messages are emitted */ LIBUSB_LOG_LEVEL_ERROR = 1, + + /** (2) : Warning and error messages are emitted */ LIBUSB_LOG_LEVEL_WARNING = 2, + + /** (3) : Informational, warning and error messages are emitted */ LIBUSB_LOG_LEVEL_INFO = 3, - LIBUSB_LOG_LEVEL_DEBUG = 4, + + /** (4) : All messages are emitted */ + LIBUSB_LOG_LEVEL_DEBUG = 4 }; +/** \ingroup libusb_lib + * Log callback mode. + * + * Since version 1.0.23, \ref LIBUSB_API_VERSION >= 0x01000107 + * + * \see libusb_set_log_cb() + */ +enum libusb_log_cb_mode { + /** Callback function handling all log messages. */ + LIBUSB_LOG_CB_GLOBAL = (1 << 0), + + /** Callback function handling context related log messages. */ + LIBUSB_LOG_CB_CONTEXT = (1 << 1) +}; + +/** \ingroup libusb_lib + * Callback function for handling log messages. + * \param ctx the context which is related to the log message, or NULL if it + * is a global log message + * \param level the log level, see \ref libusb_log_level for a description + * \param str the log message + * + * Since version 1.0.23, \ref LIBUSB_API_VERSION >= 0x01000107 + * + * \see libusb_set_log_cb() + */ +typedef void (LIBUSB_CALL *libusb_log_cb)(libusb_context *ctx, + enum libusb_log_level level, const char *str); + int LIBUSB_CALL libusb_init(libusb_context **ctx); void LIBUSB_CALL libusb_exit(libusb_context *ctx); LIBUSB_DEPRECATED_FOR(libusb_set_option) void LIBUSB_CALL libusb_set_debug(libusb_context *ctx, int level); +void LIBUSB_CALL libusb_set_log_cb(libusb_context *ctx, libusb_log_cb cb, int mode); const struct libusb_version * LIBUSB_CALL libusb_get_version(void); int LIBUSB_CALL libusb_has_capability(uint32_t capability); const char * LIBUSB_CALL libusb_error_name(int errcode); int LIBUSB_CALL libusb_setlocale(const char *locale); -const char * LIBUSB_CALL libusb_strerror(enum libusb_error errcode); +const char * LIBUSB_CALL libusb_strerror(int errcode); ssize_t LIBUSB_CALL libusb_get_device_list(libusb_context *ctx, libusb_device ***list); @@ -1324,7 +1390,7 @@ int LIBUSB_CALL libusb_get_config_descriptor_by_value(libusb_device *dev, void LIBUSB_CALL libusb_free_config_descriptor( struct libusb_config_descriptor *config); int LIBUSB_CALL libusb_get_ss_endpoint_companion_descriptor( - struct libusb_context *ctx, + libusb_context *ctx, const struct libusb_endpoint_descriptor *endpoint, struct libusb_ss_endpoint_companion_descriptor **ep_comp); void LIBUSB_CALL libusb_free_ss_endpoint_companion_descriptor( @@ -1333,27 +1399,27 @@ int LIBUSB_CALL libusb_get_bos_descriptor(libusb_device_handle *dev_handle, struct libusb_bos_descriptor **bos); void LIBUSB_CALL libusb_free_bos_descriptor(struct libusb_bos_descriptor *bos); int LIBUSB_CALL libusb_get_usb_2_0_extension_descriptor( - struct libusb_context *ctx, + libusb_context *ctx, struct libusb_bos_dev_capability_descriptor *dev_cap, struct libusb_usb_2_0_extension_descriptor **usb_2_0_extension); void LIBUSB_CALL libusb_free_usb_2_0_extension_descriptor( struct libusb_usb_2_0_extension_descriptor *usb_2_0_extension); int LIBUSB_CALL libusb_get_ss_usb_device_capability_descriptor( - struct libusb_context *ctx, + libusb_context *ctx, struct libusb_bos_dev_capability_descriptor *dev_cap, struct libusb_ss_usb_device_capability_descriptor **ss_usb_device_cap); void LIBUSB_CALL libusb_free_ss_usb_device_capability_descriptor( struct libusb_ss_usb_device_capability_descriptor *ss_usb_device_cap); -int LIBUSB_CALL libusb_get_container_id_descriptor(struct libusb_context *ctx, +int LIBUSB_CALL libusb_get_container_id_descriptor(libusb_context *ctx, struct libusb_bos_dev_capability_descriptor *dev_cap, struct libusb_container_id_descriptor **container_id); void LIBUSB_CALL libusb_free_container_id_descriptor( struct libusb_container_id_descriptor *container_id); uint8_t LIBUSB_CALL libusb_get_bus_number(libusb_device *dev); uint8_t LIBUSB_CALL libusb_get_port_number(libusb_device *dev); -int LIBUSB_CALL libusb_get_port_numbers(libusb_device *dev, uint8_t* port_numbers, int port_numbers_len); +int LIBUSB_CALL libusb_get_port_numbers(libusb_device *dev, uint8_t *port_numbers, int port_numbers_len); LIBUSB_DEPRECATED_FOR(libusb_get_port_numbers) -int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t* path, uint8_t path_length); +int LIBUSB_CALL libusb_get_port_path(libusb_context *ctx, libusb_device *dev, uint8_t *path, uint8_t path_length); libusb_device * LIBUSB_CALL libusb_get_parent(libusb_device *dev); uint8_t LIBUSB_CALL libusb_get_device_address(libusb_device *dev); int LIBUSB_CALL libusb_get_device_speed(libusb_device *dev); @@ -1362,6 +1428,7 @@ int LIBUSB_CALL libusb_get_max_packet_size(libusb_device *dev, int LIBUSB_CALL libusb_get_max_iso_packet_size(libusb_device *dev, unsigned char endpoint); +int LIBUSB_CALL libusb_wrap_sys_device(libusb_context *ctx, intptr_t sys_dev, libusb_device_handle **dev_handle); int LIBUSB_CALL libusb_open(libusb_device *dev, libusb_device_handle **dev_handle); void LIBUSB_CALL libusb_close(libusb_device_handle *dev_handle); libusb_device * LIBUSB_CALL libusb_get_device(libusb_device_handle *dev_handle); @@ -1436,7 +1503,7 @@ static inline unsigned char *libusb_control_transfer_get_data( static inline struct libusb_control_setup *libusb_control_transfer_get_setup( struct libusb_transfer *transfer) { - return (struct libusb_control_setup *)(void *) transfer->buffer; + return (struct libusb_control_setup *)(void *)transfer->buffer; } /** \ingroup libusb_asyncio @@ -1466,7 +1533,7 @@ static inline void libusb_fill_control_setup(unsigned char *buffer, uint8_t bmRequestType, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, uint16_t wLength) { - struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer; + struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *)buffer; setup->bmRequestType = bmRequestType; setup->bRequest = bRequest; setup->wValue = libusb_cpu_to_le16(wValue); @@ -1516,7 +1583,7 @@ static inline void libusb_fill_control_transfer( unsigned char *buffer, libusb_transfer_cb_fn callback, void *user_data, unsigned int timeout) { - struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *) buffer; + struct libusb_control_setup *setup = (struct libusb_control_setup *)(void *)buffer; transfer->dev_handle = dev_handle; transfer->endpoint = 0; transfer->type = LIBUSB_TRANSFER_TYPE_CONTROL; @@ -1655,6 +1722,7 @@ static inline void libusb_set_iso_packet_lengths( struct libusb_transfer *transfer, unsigned int length) { int i; + for (i = 0; i < transfer->num_iso_packets; i++) transfer->iso_packet_desc[i].length = length; } @@ -1869,7 +1937,7 @@ void LIBUSB_CALL libusb_set_pollfd_notifiers(libusb_context *ctx, * Callbacks handles are generated by libusb_hotplug_register_callback() * and can be used to deregister callbacks. Callback handles are unique * per libusb_context and it is safe to call libusb_hotplug_deregister_callback() - * on an already deregisted callback. + * on an already deregistered callback. * * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 * @@ -1881,29 +1949,30 @@ typedef int libusb_hotplug_callback_handle; * * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 * - * Flags for hotplug events */ + * Hotplug events */ typedef enum { - /** Default value when not using any flags. */ - LIBUSB_HOTPLUG_NO_FLAGS = 0, + /** A device has been plugged in and is ready to use */ + LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED = (1 << 0), - /** Arm the callback and fire it for all matching currently attached devices. */ - LIBUSB_HOTPLUG_ENUMERATE = 1<<0, -} libusb_hotplug_flag; + /** A device has left and is no longer available. + * It is the user's responsibility to call libusb_close on any handle associated with a disconnected device. + * It is safe to call libusb_get_device_descriptor on a device that has left */ + LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT = (1 << 1) +} libusb_hotplug_event; /** \ingroup libusb_hotplug * * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 * - * Hotplug events */ + * Hotplug flags */ typedef enum { - /** A device has been plugged in and is ready to use */ - LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED = 0x01, + /** Arm the callback and fire it for all matching currently attached devices. */ + LIBUSB_HOTPLUG_ENUMERATE = (1 << 0) +} libusb_hotplug_flag; - /** A device has left and is no longer available. - * It is the user's responsibility to call libusb_close on any handle associated with a disconnected device. - * It is safe to call libusb_get_device_descriptor on a device that has left */ - LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT = 0x02, -} libusb_hotplug_event; +/** \ingroup libusb_hotplug + * Convenience macro when not using any flags */ +#define LIBUSB_HOTPLUG_NO_FLAGS 0 /** \ingroup libusb_hotplug * Wildcard matching for hotplug events */ @@ -1932,9 +2001,7 @@ typedef enum { * returning 1 will cause this callback to be deregistered */ typedef int (LIBUSB_CALL *libusb_hotplug_callback_fn)(libusb_context *ctx, - libusb_device *device, - libusb_hotplug_event event, - void *user_data); + libusb_device *device, libusb_hotplug_event event, void *user_data); /** \ingroup libusb_hotplug * Register a hotplug callback function @@ -1959,9 +2026,10 @@ typedef int (LIBUSB_CALL *libusb_hotplug_callback_fn)(libusb_context *ctx, * Since version 1.0.16, \ref LIBUSB_API_VERSION >= 0x01000102 * * \param[in] ctx context to register this callback with - * \param[in] events bitwise or of events that will trigger this callback. See \ref - * libusb_hotplug_event - * \param[in] flags hotplug callback flags. See \ref libusb_hotplug_flag + * \param[in] events bitwise or of hotplug events that will trigger this callback. + * See \ref libusb_hotplug_event + * \param[in] flags bitwise or of hotplug flags that affect registration. + * See \ref libusb_hotplug_flag * \param[in] vendor_id the vendor id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY * \param[in] product_id the product id to match or \ref LIBUSB_HOTPLUG_MATCH_ANY * \param[in] dev_class the device class to match or \ref LIBUSB_HOTPLUG_MATCH_ANY @@ -1971,13 +2039,10 @@ typedef int (LIBUSB_CALL *libusb_hotplug_callback_fn)(libusb_context *ctx, * \returns LIBUSB_SUCCESS on success LIBUSB_ERROR code on failure */ int LIBUSB_CALL libusb_hotplug_register_callback(libusb_context *ctx, - libusb_hotplug_event events, - libusb_hotplug_flag flags, - int vendor_id, int product_id, - int dev_class, - libusb_hotplug_callback_fn cb_fn, - void *user_data, - libusb_hotplug_callback_handle *callback_handle); + int events, int flags, + int vendor_id, int product_id, int dev_class, + libusb_hotplug_callback_fn cb_fn, void *user_data, + libusb_hotplug_callback_handle *callback_handle); /** \ingroup libusb_hotplug * Deregisters a hotplug callback. @@ -1991,7 +2056,18 @@ int LIBUSB_CALL libusb_hotplug_register_callback(libusb_context *ctx, * \param[in] callback_handle the handle of the callback to deregister */ void LIBUSB_CALL libusb_hotplug_deregister_callback(libusb_context *ctx, - libusb_hotplug_callback_handle callback_handle); + libusb_hotplug_callback_handle callback_handle); + +/** \ingroup libusb_hotplug + * Gets the user_data associated with a hotplug callback. + * + * Since version v1.0.24 \ref LIBUSB_API_VERSION >= 0x01000108 + * + * \param[in] ctx context this callback is registered with + * \param[in] callback_handle the handle of the callback to get the user_data of + */ +void * LIBUSB_CALL libusb_hotplug_get_user_data(libusb_context *ctx, + libusb_hotplug_callback_handle callback_handle); /** \ingroup libusb_lib * Available option values for libusb_set_option(). @@ -2018,7 +2094,7 @@ enum libusb_option { * If libusb was compiled with verbose debug message logging, this function * does nothing: you'll always get messages from all levels. */ - LIBUSB_OPTION_LOG_LEVEL, + LIBUSB_OPTION_LOG_LEVEL = 0, /** Use the UsbDk backend for a specific context, if available. * @@ -2027,12 +2103,39 @@ enum libusb_option { * * Only valid on Windows. */ - LIBUSB_OPTION_USE_USBDK, + LIBUSB_OPTION_USE_USBDK = 1, + + /** Do not scan for devices + * + * With this option set, libusb will skip scanning devices in + * libusb_init(). Must be set before calling libusb_init(). + * + * Hotplug functionality will also be deactivated. + * + * The option is useful in combination with libusb_wrap_sys_device(), + * which can access a device directly without prior device scanning. + * + * This is typically needed on Android, where access to USB devices + * is limited. + * + * For LIBUSB_API_VERSION 0x01000108 it was called LIBUSB_OPTION_WEAK_AUTHORITY + * + * Only valid on Linux. + */ + LIBUSB_OPTION_NO_DEVICE_DISCOVERY = 2, + +#define LIBUSB_OPTION_WEAK_AUTHORITY LIBUSB_OPTION_NO_DEVICE_DISCOVERY + + LIBUSB_OPTION_MAX = 3 }; int LIBUSB_CALL libusb_set_option(libusb_context *ctx, enum libusb_option option, ...); -#ifdef __cplusplus +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#if defined(__cplusplus) } #endif diff --git a/Xb2XInput/Internal.h b/Xb2XInput/Internal.h index d8f52ea..81cf528 100644 --- a/Xb2XInput/Internal.h +++ b/Xb2XInput/Internal.h @@ -37,13 +37,15 @@ SOFTWARE. typedef struct _VIGEM_CLIENT_T { HANDLE hBusDevice; - + HANDLE hDS4OutputReportPickupThread; + HANDLE hDS4OutputReportPickupThreadAbortEvent; + PVIGEM_TARGET pTargetsList[VIGEM_TARGETS_MAX]; } VIGEM_CLIENT; // // Represents the (connection) state of a target device object. // -typedef enum _VIGEM_TARGET_STATE +typedef enum { VIGEM_TARGET_NEW, VIGEM_TARGET_INITIALIZED, @@ -51,8 +53,6 @@ typedef enum _VIGEM_TARGET_STATE VIGEM_TARGET_DISCONNECTED } VIGEM_TARGET_STATE, *PVIGEM_TARGET_STATE; - - // // Represents a virtual gamepad object. // @@ -65,8 +65,18 @@ typedef struct _VIGEM_TARGET_T USHORT ProductId; VIGEM_TARGET_TYPE Type; FARPROC Notification; - - bool closingNotificationThreads; - HANDLE cancelNotificationThreadEvent; - std::unique_ptr> notificationThreadList; + LPVOID NotificationUserData; + BOOLEAN IsWaitReadyUnsupported; + HANDLE CancelNotificationThreadEvent; + DS4_OUTPUT_BUFFER Ds4CachedOutputReport; + HANDLE Ds4CachedOutputReportUpdateAvailable; } VIGEM_TARGET; + +#define DEVICE_IO_CONTROL_BEGIN \ + DWORD transferred = 0; \ + OVERLAPPED lOverlapped = { 0 }; \ + lOverlapped.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL) + +#define DEVICE_IO_CONTROL_END \ + if (lOverlapped.hEvent) \ + CloseHandle(lOverlapped.hEvent) diff --git a/Xb2XInput/ViGEmClient.cpp b/Xb2XInput/ViGEmClient.cpp index e4d0b88..88ae7db 100644 --- a/Xb2XInput/ViGEmClient.cpp +++ b/Xb2XInput/ViGEmClient.cpp @@ -29,7 +29,7 @@ SOFTWARE. #include #include #include -#include +#include // // Driver shared @@ -43,8 +43,6 @@ SOFTWARE. // #include #include -#include -#include #include #include @@ -53,720 +51,812 @@ SOFTWARE. // #include "Internal.h" +//#define VIGEM_VERBOSE_LOGGING_ENABLED -typedef BOOL(WINAPI *MINIDUMPWRITEDUMP)( - HANDLE hProcess, - DWORD dwPid, - HANDLE hFile, - MINIDUMP_TYPE DumpType, - CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, - CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, - CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam - ); -LONG WINAPI vigem_internal_exception_handler(struct _EXCEPTION_POINTERS* apExceptionInfo); +#pragma region Diagnostics +#ifdef _DEBUG +#define DBGPRINT(kwszDebugFormatString, ...) _DBGPRINT(__FUNCTIONW__, __LINE__, kwszDebugFormatString, __VA_ARGS__) +#else +#define DBGPRINT( kwszDebugFormatString, ... ) ;; +#endif -// -// DeviceIOControl request notification handler classes for X360 and DS4 controller types. -// vigem_target_XXX_register_notification functions use x360 or DS4 derived class instances in a notification thread handlers. -// -class NotificationRequestPayload -{ -public: - LPVOID lpPayloadBuffer; - DWORD payloadBufferSize; - DWORD ioControlCode; - -public: - NotificationRequestPayload(DWORD _bufferSize, DWORD _ioControlCode) - { - lpPayloadBuffer = malloc(_bufferSize); - payloadBufferSize = _bufferSize; - ioControlCode = _ioControlCode; - } - - virtual ~NotificationRequestPayload() - { - free(lpPayloadBuffer); - } - - virtual void ProcessNotificationRequest(PVIGEM_CLIENT client, PVIGEM_TARGET target) = 0; -}; - -class NotificationRequestPayloadX360 : public NotificationRequestPayload +VOID _DBGPRINT(LPCWSTR kwszFunction, INT iLineNumber, LPCWSTR kwszDebugFormatString, ...) { -public: - NotificationRequestPayloadX360(ULONG _serialNo) : NotificationRequestPayload(sizeof(XUSB_REQUEST_NOTIFICATION), IOCTL_XUSB_REQUEST_NOTIFICATION) - { - // Let base class to allocate required buffer size, but initialize it here with a correct type of initialization function - XUSB_REQUEST_NOTIFICATION_INIT((PXUSB_REQUEST_NOTIFICATION)lpPayloadBuffer, _serialNo); - } - - void ProcessNotificationRequest(PVIGEM_CLIENT client, PVIGEM_TARGET target) override - { - if(target->Notification != nullptr) - PFN_VIGEM_X360_NOTIFICATION(target->Notification)(client, target, - ((PXUSB_REQUEST_NOTIFICATION)lpPayloadBuffer)->LargeMotor, - ((PXUSB_REQUEST_NOTIFICATION)lpPayloadBuffer)->SmallMotor, - ((PXUSB_REQUEST_NOTIFICATION)lpPayloadBuffer)->LedNumber - ); - } -}; +#if defined(VIGEM_VERBOSE_LOGGING_ENABLED) + INT cbFormatString = 0; + va_list args; + PWCHAR wszDebugString = nullptr; + size_t st_Offset = 0; + + va_start(args, kwszDebugFormatString); + + cbFormatString = _scwprintf(L"[%s:%d] ", kwszFunction, iLineNumber) * sizeof(WCHAR); + cbFormatString += _vscwprintf(kwszDebugFormatString, args) * sizeof(WCHAR) + 2; + + /* Depending on the size of the format string, allocate space on the stack or the heap. */ + wszDebugString = static_cast((0)); + + /* Populate the buffer with the contents of the format string. */ + StringCbPrintfW(wszDebugString, cbFormatString, L"[%s:%d] ", kwszFunction, iLineNumber); + StringCbLengthW(wszDebugString, cbFormatString, &st_Offset); + StringCbVPrintfW(&wszDebugString[st_Offset / sizeof(WCHAR)], cbFormatString - st_Offset, kwszDebugFormatString, + args); + + OutputDebugStringW(wszDebugString); + + _freea(wszDebugString); + va_end(args); +#else + std::ignore = kwszFunction; + std::ignore = iLineNumber; + std::ignore = kwszDebugFormatString; +#endif +} -class NotificationRequestPayloadDS4 : public NotificationRequestPayload +static void to_hex(unsigned char* in, size_t insz, char* out, size_t outsz) { -public: - NotificationRequestPayloadDS4(ULONG _serialNo) : NotificationRequestPayload(sizeof(DS4_REQUEST_NOTIFICATION), IOCTL_DS4_REQUEST_NOTIFICATION) + unsigned char* pin = in; + auto hex = "0123456789ABCDEF"; + char* pout = out; + for (; pin < in + insz; pout += 3, pin++) { - // Let base class to allocate required buffer size, but initialize it here with a correct type of initialization function - DS4_REQUEST_NOTIFICATION_INIT((PDS4_REQUEST_NOTIFICATION)lpPayloadBuffer, _serialNo); + pout[0] = hex[(*pin >> 4) & 0xF]; + pout[1] = hex[*pin & 0xF]; + pout[2] = ':'; + if (pout + 3 - out > outsz) + { + /* Better to truncate output string than overflow buffer */ + /* it would be still better to either return a status */ + /* or ensure the target buffer is large enough and it never happen */ + break; + } } + pout[-1] = 0; +} - void ProcessNotificationRequest(PVIGEM_CLIENT client, PVIGEM_TARGET target) override - { - if (target->Notification != nullptr) - PFN_VIGEM_DS4_NOTIFICATION(target->Notification)(client, target, - ((PDS4_REQUEST_NOTIFICATION)lpPayloadBuffer)->Report.LargeMotor, - ((PDS4_REQUEST_NOTIFICATION)lpPayloadBuffer)->Report.SmallMotor, - ((PDS4_REQUEST_NOTIFICATION)lpPayloadBuffer)->Report.LightbarColor - ); - } -}; +#pragma endregion // // Initializes a virtual gamepad object. // PVIGEM_TARGET FORCEINLINE VIGEM_TARGET_ALLOC_INIT( - _In_ VIGEM_TARGET_TYPE Type + _In_ VIGEM_TARGET_TYPE Type ) { - auto target = static_cast(malloc(sizeof(VIGEM_TARGET))); + auto target = static_cast(malloc(sizeof(VIGEM_TARGET))); - if (!target) - return nullptr; + if (!target) + return nullptr; - memset(target, 0, sizeof(VIGEM_TARGET)); + memset(target, 0, sizeof(VIGEM_TARGET)); - target->Size = sizeof(VIGEM_TARGET); - target->State = VIGEM_TARGET_INITIALIZED; - target->Type = Type; - target->notificationThreadList = nullptr; - return target; + target->Size = sizeof(VIGEM_TARGET); + target->State = VIGEM_TARGET_INITIALIZED; + target->Type = Type; + return target; } - -LONG WINAPI vigem_internal_exception_handler(struct _EXCEPTION_POINTERS* apExceptionInfo) +static DWORD WINAPI vigem_internal_ds4_output_report_pickup_handler(LPVOID Parameter) { - const auto mhLib = LoadLibrary(L"dbghelp.dll"); - const auto pDump = reinterpret_cast(GetProcAddress(mhLib, "MiniDumpWriteDump")); + const auto pClient = static_cast(Parameter); + DS4_AWAIT_OUTPUT await; + DEVICE_IO_CONTROL_BEGIN; + + DBGPRINT(L"Started DS4 Output Report pickup thread for 0x%p", pClient); + + do + { + DS4_AWAIT_OUTPUT_INIT(&await, 0); + + DeviceIoControl( + pClient->hBusDevice, + IOCTL_DS4_AWAIT_OUTPUT_AVAILABLE, + &await, + await.Size, + &await, + await.Size, + &transferred, + &lOverlapped + ); + + if (GetOverlappedResult(pClient->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) + { + const DWORD error = GetLastError(); + + // + // Backwards compatibility with version pre-1.19, where this IOCTL doesn't exist + // + if (error == ERROR_INVALID_PARAMETER) + { + DBGPRINT(L"Currently used driver version doesn't support this request, aborting"); + break; + } - const auto hFile = CreateFile( - L"ViGEmClient.dmp", - GENERIC_WRITE, - FILE_SHARE_WRITE, - nullptr, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - nullptr - ); + DBGPRINT(L"Win32 Error: 0x%X", error); + } - const DWORD flags = MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithUnloadedModules | - MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData | - MiniDumpWithFullMemoryInfo | MiniDumpWithThreadInfo | - MiniDumpWithFullAuxiliaryState | MiniDumpIgnoreInaccessibleMemory | - MiniDumpWithTokenInformation; +#if defined(VIGEM_VERBOSE_LOGGING_ENABLED) + DBGPRINT(L"Dumping buffer for %d", await.SerialNo); - if (hFile != INVALID_HANDLE_VALUE) - { - _MINIDUMP_EXCEPTION_INFORMATION ExInfo; - ExInfo.ThreadId = GetCurrentThreadId(); - ExInfo.ExceptionPointers = apExceptionInfo; - ExInfo.ClientPointers = FALSE; + const PCHAR dumpBuffer = (PCHAR)calloc(sizeof(DS4_OUTPUT_BUFFER), 3); + to_hex(await.Report.Buffer, sizeof(DS4_OUTPUT_BUFFER), dumpBuffer, sizeof(DS4_OUTPUT_BUFFER) * 3); + OutputDebugStringA(dumpBuffer); +#endif - pDump( - GetCurrentProcess(), - GetCurrentProcessId(), - hFile, - (MINIDUMP_TYPE)flags, - &ExInfo, - nullptr, - nullptr - ); - CloseHandle(hFile); - } + const PVIGEM_TARGET pTarget = pClient->pTargetsList[await.SerialNo]; + + if (pTarget) + { + memcpy(&pTarget->Ds4CachedOutputReport, &await.Report, sizeof(DS4_OUTPUT_BUFFER)); + SetEvent(pTarget->Ds4CachedOutputReportUpdateAvailable); + } + else + { + DBGPRINT(L"No target to report to for serial %d", await.SerialNo); + } + } while (WaitForSingleObjectEx(pClient->hDS4OutputReportPickupThreadAbortEvent, 0, FALSE) == WAIT_TIMEOUT); + + DEVICE_IO_CONTROL_END; - return EXCEPTION_CONTINUE_SEARCH; + DBGPRINT(L"Finished DS4 Output Report pickup thread for 0x%p", pClient); + + return 0; } PVIGEM_CLIENT vigem_alloc() { - SetUnhandledExceptionFilter(vigem_internal_exception_handler); - - const auto driver = static_cast(malloc(sizeof(VIGEM_CLIENT))); + const auto driver = static_cast(malloc(sizeof(VIGEM_CLIENT))); - if (!driver) - return nullptr; + if (!driver) + return nullptr; - RtlZeroMemory(driver, sizeof(VIGEM_CLIENT)); - driver->hBusDevice = INVALID_HANDLE_VALUE; + RtlZeroMemory(driver, sizeof(VIGEM_CLIENT)); + driver->hBusDevice = INVALID_HANDLE_VALUE; + driver->hDS4OutputReportPickupThreadAbortEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); - return driver; + return driver; } void vigem_free(PVIGEM_CLIENT vigem) { - if (vigem) - free(vigem); + if (vigem) + free(vigem); } VIGEM_ERROR vigem_connect(PVIGEM_CLIENT vigem) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; - - SP_DEVICE_INTERFACE_DATA deviceInterfaceData = { 0 }; - deviceInterfaceData.cbSize = sizeof(deviceInterfaceData); - DWORD memberIndex = 0; - DWORD requiredSize = 0; - auto error = VIGEM_ERROR_BUS_NOT_FOUND; - - // check for already open handle as re-opening accidentally would destroy all live targets - if (vigem->hBusDevice != INVALID_HANDLE_VALUE) - { - return VIGEM_ERROR_BUS_ALREADY_CONNECTED; - } - - const auto deviceInfoSet = SetupDiGetClassDevs( - &GUID_DEVINTERFACE_BUSENUM_VIGEM, - nullptr, - nullptr, - DIGCF_PRESENT | DIGCF_DEVICEINTERFACE - ); - - // enumerate device instances - while (SetupDiEnumDeviceInterfaces( - deviceInfoSet, - nullptr, - &GUID_DEVINTERFACE_BUSENUM_VIGEM, - memberIndex++, - &deviceInterfaceData - )) - { - // get required target buffer size - SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, nullptr, 0, &requiredSize, nullptr); - - // allocate target buffer - const auto detailDataBuffer = static_cast(malloc(requiredSize)); - detailDataBuffer->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); - - // get detail buffer - if (!SetupDiGetDeviceInterfaceDetail( - deviceInfoSet, - &deviceInterfaceData, - detailDataBuffer, - requiredSize, - &requiredSize, - nullptr - )) - { - SetupDiDestroyDeviceInfoList(deviceInfoSet); - free(detailDataBuffer); - error = VIGEM_ERROR_BUS_NOT_FOUND; - continue; - } - - // bus found, open it - vigem->hBusDevice = CreateFile( - detailDataBuffer->DevicePath, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - nullptr, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH | FILE_FLAG_OVERLAPPED, - nullptr - ); - - // check bus open result - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - { - error = VIGEM_ERROR_BUS_ACCESS_FAILED; - free(detailDataBuffer); - continue; - } - - DWORD transferred = 0; - OVERLAPPED lOverlapped = { 0 }; - lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); - - VIGEM_CHECK_VERSION version; - VIGEM_CHECK_VERSION_INIT(&version, VIGEM_COMMON_VERSION); - - // send compiled library version to driver to check compatibility - DeviceIoControl( - vigem->hBusDevice, - IOCTL_VIGEM_CHECK_VERSION, - &version, - version.Size, - nullptr, - 0, - &transferred, - &lOverlapped - ); - - // wait for result - if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) != 0) - { - error = VIGEM_ERROR_NONE; - free(detailDataBuffer); - CloseHandle(lOverlapped.hEvent); - break; - } - - error = VIGEM_ERROR_BUS_VERSION_MISMATCH; - - CloseHandle(lOverlapped.hEvent); - free(detailDataBuffer); - } - - SetupDiDestroyDeviceInfoList(deviceInfoSet); - - return error; -} + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; -void vigem_disconnect(PVIGEM_CLIENT vigem) -{ - if (!vigem) - return; + SP_DEVICE_INTERFACE_DATA deviceInterfaceData = { 0 }; + deviceInterfaceData.cbSize = sizeof(deviceInterfaceData); + DWORD memberIndex = 0; + DWORD requiredSize = 0; + auto error = VIGEM_ERROR_BUS_NOT_FOUND; - if (vigem->hBusDevice != INVALID_HANDLE_VALUE) - { - CloseHandle(vigem->hBusDevice); + // check for already open handle as re-opening accidentally would destroy all live targets + if (vigem->hBusDevice != INVALID_HANDLE_VALUE) + { + return VIGEM_ERROR_BUS_ALREADY_CONNECTED; + } - RtlZeroMemory(vigem, sizeof(VIGEM_CLIENT)); - vigem->hBusDevice = INVALID_HANDLE_VALUE; - } -} + const auto deviceInfoSet = SetupDiGetClassDevs( + &GUID_DEVINTERFACE_BUSENUM_VIGEM, + nullptr, + nullptr, + DIGCF_PRESENT | DIGCF_DEVICEINTERFACE + ); + + // enumerate device instances + while (SetupDiEnumDeviceInterfaces( + deviceInfoSet, + nullptr, + &GUID_DEVINTERFACE_BUSENUM_VIGEM, + memberIndex++, + &deviceInterfaceData + )) + { + // get required target buffer size + SetupDiGetDeviceInterfaceDetail(deviceInfoSet, &deviceInterfaceData, nullptr, 0, &requiredSize, nullptr); + + // allocate target buffer + const auto detailDataBuffer = static_cast(malloc(requiredSize)); + detailDataBuffer->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); + + // get detail buffer + if (!SetupDiGetDeviceInterfaceDetail( + deviceInfoSet, + &deviceInterfaceData, + detailDataBuffer, + requiredSize, + &requiredSize, + nullptr + )) + { + free(detailDataBuffer); + error = VIGEM_ERROR_BUS_NOT_FOUND; + continue; + } -PVIGEM_TARGET vigem_target_x360_alloc(void) -{ - const auto target = VIGEM_TARGET_ALLOC_INIT(Xbox360Wired); + // bus found, open it + vigem->hBusDevice = CreateFile( + detailDataBuffer->DevicePath, + GENERIC_READ | GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH | FILE_FLAG_OVERLAPPED, + nullptr + ); - if (!target) - return nullptr; + // check bus open result + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + { + error = VIGEM_ERROR_BUS_ACCESS_FAILED; + free(detailDataBuffer); + continue; + } - target->VendorId = 0x045E; - target->ProductId = 0x028E; + DWORD transferred = 0; + OVERLAPPED lOverlapped = { 0 }; + lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + + VIGEM_CHECK_VERSION version; + VIGEM_CHECK_VERSION_INIT(&version, VIGEM_COMMON_VERSION); + + // send compiled library version to driver to check compatibility + DeviceIoControl( + vigem->hBusDevice, + IOCTL_VIGEM_CHECK_VERSION, + &version, + version.Size, + nullptr, + 0, + &transferred, + &lOverlapped + ); - return target; -} + // wait for result + if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) != 0) + { + vigem->hDS4OutputReportPickupThread = CreateThread( + nullptr, + 0, + vigem_internal_ds4_output_report_pickup_handler, + vigem, + 0, + nullptr + ); -PVIGEM_TARGET vigem_target_ds4_alloc(void) -{ - const auto target = VIGEM_TARGET_ALLOC_INIT(DualShock4Wired); + error = VIGEM_ERROR_NONE; + free(detailDataBuffer); + CloseHandle(lOverlapped.hEvent); + break; + } - if (!target) - return nullptr; + error = VIGEM_ERROR_BUS_VERSION_MISMATCH; - target->VendorId = 0x054C; - target->ProductId = 0x05C4; + CloseHandle(lOverlapped.hEvent); + free(detailDataBuffer); + } - return target; -} + SetupDiDestroyDeviceInfoList(deviceInfoSet); -void vigem_target_free(PVIGEM_TARGET target) -{ - if (target) - free(target); + return error; } -VIGEM_ERROR vigem_target_add(PVIGEM_CLIENT vigem, PVIGEM_TARGET target) +void vigem_disconnect(PVIGEM_CLIENT vigem) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + if (!vigem) + return; + + if (vigem->hDS4OutputReportPickupThread && vigem->hDS4OutputReportPickupThreadAbortEvent) + { + DBGPRINT(L"Awaiting DS4 thread clean-up for 0x%p", vigem); - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + SetEvent(vigem->hDS4OutputReportPickupThreadAbortEvent); - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + if (vigem->hBusDevice != INVALID_HANDLE_VALUE) + { + DBGPRINT(L"Cancelling all I/O for 0x%p", vigem); + CancelIoEx(vigem->hBusDevice, nullptr); + } - if (target->State == VIGEM_TARGET_NEW) - return VIGEM_ERROR_TARGET_UNINITIALIZED; + WaitForSingleObject(vigem->hDS4OutputReportPickupThread, INFINITE); + CloseHandle(vigem->hDS4OutputReportPickupThread); + CloseHandle(vigem->hDS4OutputReportPickupThreadAbortEvent); - if (target->State == VIGEM_TARGET_CONNECTED) - return VIGEM_ERROR_ALREADY_CONNECTED; + DBGPRINT(L"DS4 thread clean-up for 0x%p finished", vigem); + } - DWORD transferred = 0; - VIGEM_PLUGIN_TARGET plugin; - OVERLAPPED lOverlapped = { 0 }; - lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + if (vigem->hBusDevice != INVALID_HANDLE_VALUE) + { + DBGPRINT(L"Closing bus handle for 0x%p", vigem); - for (target->SerialNo = 1; target->SerialNo <= VIGEM_TARGETS_MAX; target->SerialNo++) - { - VIGEM_PLUGIN_TARGET_INIT(&plugin, target->SerialNo, target->Type); + CloseHandle(vigem->hBusDevice); + vigem->hBusDevice = INVALID_HANDLE_VALUE; + } - plugin.VendorId = target->VendorId; - plugin.ProductId = target->ProductId; + RtlZeroMemory(vigem, sizeof(VIGEM_CLIENT)); +} - DeviceIoControl( - vigem->hBusDevice, - IOCTL_VIGEM_PLUGIN_TARGET, - &plugin, - plugin.Size, - nullptr, - 0, - &transferred, - &lOverlapped - ); +BOOLEAN vigem_target_is_waitable_add_supported(PVIGEM_TARGET target) +{ + // + // Safety check to make people use the older functions and not cause issues + // Should never pass in an invalid target but doesn't hurt to check. + // + if (!target) + return FALSE; + + // TODO: Replace all this with a more robust version check system + return !target->IsWaitReadyUnsupported; +} - if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) != 0) - { - target->State = VIGEM_TARGET_CONNECTED; - CloseHandle(lOverlapped.hEvent); +PVIGEM_TARGET vigem_target_x360_alloc(void) +{ + const auto target = VIGEM_TARGET_ALLOC_INIT(Xbox360Wired); - return VIGEM_ERROR_NONE; - } - } + if (!target) + return nullptr; - CloseHandle(lOverlapped.hEvent); + target->VendorId = 0x045E; + target->ProductId = 0x028E; - return VIGEM_ERROR_NO_FREE_SLOT; + return target; } -VIGEM_ERROR vigem_target_add_async(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PFN_VIGEM_TARGET_ADD_RESULT result) +PVIGEM_TARGET vigem_target_ds4_alloc(void) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + const auto target = VIGEM_TARGET_ALLOC_INIT(DualShock4Wired); - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + if (!target) + return nullptr; - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + target->VendorId = 0x054C; + target->ProductId = 0x05C4; + target->Ds4CachedOutputReportUpdateAvailable = CreateEvent(nullptr, FALSE, FALSE, nullptr); - if (target->State == VIGEM_TARGET_NEW) - return VIGEM_ERROR_TARGET_UNINITIALIZED; + return target; +} - if (target->State == VIGEM_TARGET_CONNECTED) - return VIGEM_ERROR_ALREADY_CONNECTED; +void vigem_target_free(PVIGEM_TARGET target) +{ + if (target) + free(target); +} - std::thread _async{ []( - PVIGEM_TARGET _Target, - PVIGEM_CLIENT _Client, - PFN_VIGEM_TARGET_ADD_RESULT _Result) - { - DWORD transferred = 0; - VIGEM_PLUGIN_TARGET plugin; - OVERLAPPED lOverlapped = { 0 }; - lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); +VIGEM_ERROR vigem_target_add(PVIGEM_CLIENT vigem, PVIGEM_TARGET target) +{ + VIGEM_ERROR error = VIGEM_ERROR_NO_FREE_SLOT; + DWORD transferred = 0; + VIGEM_PLUGIN_TARGET plugin; + VIGEM_WAIT_DEVICE_READY devReady; + OVERLAPPED olPlugIn = { 0 }; + olPlugIn.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + OVERLAPPED olWait = { 0 }; + olWait.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); - for (_Target->SerialNo = 1; _Target->SerialNo <= VIGEM_TARGETS_MAX; _Target->SerialNo++) - { - VIGEM_PLUGIN_TARGET_INIT(&plugin, _Target->SerialNo, _Target->Type); + do + { + if (!vigem) + { + error = VIGEM_ERROR_BUS_INVALID_HANDLE; + break; + } - plugin.VendorId = _Target->VendorId; - plugin.ProductId = _Target->ProductId; + if (!target) + { + error = VIGEM_ERROR_INVALID_TARGET; + break; + } - DeviceIoControl( - _Client->hBusDevice, - IOCTL_VIGEM_PLUGIN_TARGET, - &plugin, - plugin.Size, - nullptr, - 0, - &transferred, - &lOverlapped - ); + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + { + error = VIGEM_ERROR_BUS_NOT_FOUND; + break; + } - if (GetOverlappedResult(_Client->hBusDevice, &lOverlapped, &transferred, TRUE) != 0) - { - _Target->State = VIGEM_TARGET_CONNECTED; - CloseHandle(lOverlapped.hEvent); + if (target->State == VIGEM_TARGET_NEW) + { + error = VIGEM_ERROR_TARGET_UNINITIALIZED; + break; + } - if (_Result) - _Result(_Client, _Target, VIGEM_ERROR_NONE); + if (target->State == VIGEM_TARGET_CONNECTED) + { + error = VIGEM_ERROR_ALREADY_CONNECTED; + break; + } - return; - } - } + // + // TODO: this is mad stupid, redesign, so that the bus fills the assigned slot + // + for (target->SerialNo = 1; target->SerialNo <= VIGEM_TARGETS_MAX; target->SerialNo++) + { + VIGEM_PLUGIN_TARGET_INIT(&plugin, target->SerialNo, target->Type); + + plugin.VendorId = target->VendorId; + plugin.ProductId = target->ProductId; + + /* + * Request plugin of device. This is an inherently asynchronous operation, + * which is addressed differently through the history of the driver design. + * Pre-v1.17 this request was kept pending until the child was deemed operational + * which unfortunately causes synchronization issues on some systems. + * Starting with v1.17 "waiting" for full power-up is done with an additional + * IOCTL that is sent immediately after and kept pending until the driver + * reports that the device can receive report updates. The following section + * and error handling is designed to achieve transparent backwards compatibility + * to not break applications using the pre-v1.17 client SDK. This is not a 100% + * perfect and can cause other functions to fail if called too soon but + * hopefully the applications will just ignore these errors and retry ;) + */ + DeviceIoControl( + vigem->hBusDevice, + IOCTL_VIGEM_PLUGIN_TARGET, + &plugin, + plugin.Size, + nullptr, + 0, + &transferred, + &olPlugIn + ); - CloseHandle(lOverlapped.hEvent); + // + // This should return fairly immediately >=v1.17 + // + if (GetOverlappedResult(vigem->hBusDevice, &olPlugIn, &transferred, TRUE) != 0) + { + /* + * This function is announced to be blocking/synchronous, a concept that + * doesn't reflect the way the bus driver/PNP manager bring child devices + * to life. Therefore, we send another IOCTL which will be kept pending + * until the bus driver has been notified that the child device has + * reached a state that is deemed operational. This request is only + * supported on drivers v1.17 or higher, so gracefully cause errors + * of this call as a potential success and keep the device plugged in. + */ + VIGEM_WAIT_DEVICE_READY_INIT(&devReady, plugin.SerialNo); + + DeviceIoControl( + vigem->hBusDevice, + IOCTL_VIGEM_WAIT_DEVICE_READY, + &devReady, + devReady.Size, + nullptr, + 0, + &transferred, + &olWait + ); + + if (GetOverlappedResult(vigem->hBusDevice, &olWait, &transferred, TRUE) != 0) + { + target->State = VIGEM_TARGET_CONNECTED; + + error = VIGEM_ERROR_NONE; + break; + } + + // + // Backwards compatibility with version pre-1.17, where this IOCTL doesn't exist + // + if (GetLastError() == ERROR_INVALID_PARAMETER) + { + target->State = VIGEM_TARGET_CONNECTED; + target->IsWaitReadyUnsupported = true; + + error = VIGEM_ERROR_NONE; + break; + } + + // + // Don't leave device connected if the wait call failed + // + error = vigem_target_remove(vigem, target); + break; + } + } + } while (false); - if (_Result) - _Result(_Client, _Target, VIGEM_ERROR_NO_FREE_SLOT); + if (VIGEM_SUCCESS(error)) + { + vigem->pTargetsList[target->SerialNo] = target; + } - }, target, vigem, result }; + if (olPlugIn.hEvent) + CloseHandle(olPlugIn.hEvent); - _async.detach(); + if (olWait.hEvent) + CloseHandle(olWait.hEvent); - return VIGEM_ERROR_NONE; + return error; } -VIGEM_ERROR vigem_target_remove(PVIGEM_CLIENT vigem, PVIGEM_TARGET target) +VIGEM_ERROR vigem_target_add_async(PVIGEM_CLIENT vigem, PVIGEM_TARGET target, PFN_VIGEM_TARGET_ADD_RESULT result) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + if (!target) + return VIGEM_ERROR_INVALID_TARGET; - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; - if (target->State == VIGEM_TARGET_NEW) - return VIGEM_ERROR_TARGET_UNINITIALIZED; + if (target->State == VIGEM_TARGET_NEW) + return VIGEM_ERROR_TARGET_UNINITIALIZED; - if (target->State != VIGEM_TARGET_CONNECTED) - return VIGEM_ERROR_TARGET_NOT_PLUGGED_IN; + if (target->State == VIGEM_TARGET_CONNECTED) + return VIGEM_ERROR_ALREADY_CONNECTED; - DWORD transfered = 0; - VIGEM_UNPLUG_TARGET unplug; - OVERLAPPED lOverlapped = { 0 }; - lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); - - VIGEM_UNPLUG_TARGET_INIT(&unplug, target->SerialNo); - - DeviceIoControl( - vigem->hBusDevice, - IOCTL_VIGEM_UNPLUG_TARGET, - &unplug, - unplug.Size, - nullptr, - 0, - &transfered, - &lOverlapped - ); - - if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transfered, TRUE) != 0) - { - target->State = VIGEM_TARGET_DISCONNECTED; - CloseHandle(lOverlapped.hEvent); + std::thread _async{ + []( + PVIGEM_TARGET _Target, + PVIGEM_CLIENT _Client, + PFN_VIGEM_TARGET_ADD_RESULT _Result) + { + const auto error = vigem_target_add(_Client, _Target); - return VIGEM_ERROR_NONE; - } + _Result(_Client, _Target, error); + }, + target, vigem, result + }; - CloseHandle(lOverlapped.hEvent); + _async.detach(); - return VIGEM_ERROR_REMOVAL_FAILED; + return VIGEM_ERROR_NONE; } -// Num of items in Notification DeviceIOControl queue (at any time there should be at least one extra call waiting for the new events or there is danger that notification events are lost). -// The size of this queue is based on "scientific" experimentals and estimations (few games seem to sometimes flood the FFB driver interface). -#define NOTIFICATION_OVERLAPPED_QUEUE_SIZE 6 - -void vigem_notification_thread_worker( - PVIGEM_CLIENT client, - PVIGEM_TARGET target, - std::unique_ptr >> pNotificationRequestPayload -) +VIGEM_ERROR vigem_target_remove(PVIGEM_CLIENT vigem, PVIGEM_TARGET target) { - int idx; - DWORD error; + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; - HANDLE waitObjects[2]; + if (!target) + return VIGEM_ERROR_INVALID_TARGET; - BOOL devIoResult[NOTIFICATION_OVERLAPPED_QUEUE_SIZE]; - DWORD lastIoError[NOTIFICATION_OVERLAPPED_QUEUE_SIZE]; - DWORD transferred[NOTIFICATION_OVERLAPPED_QUEUE_SIZE]; - OVERLAPPED lOverlapped[NOTIFICATION_OVERLAPPED_QUEUE_SIZE]; + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; - int currentOverlappedIdx; - int futureOverlappedIdx; + if (target->State == VIGEM_TARGET_NEW) + return VIGEM_ERROR_TARGET_UNINITIALIZED; - memset(lOverlapped, 0, sizeof(lOverlapped)); - for(idx = 0; idx < NOTIFICATION_OVERLAPPED_QUEUE_SIZE; idx++) - lOverlapped[idx].hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + if (target->State != VIGEM_TARGET_CONNECTED) + return VIGEM_ERROR_TARGET_NOT_PLUGGED_IN; - waitObjects[0] = target->cancelNotificationThreadEvent; + VIGEM_UNPLUG_TARGET unplug; + DEVICE_IO_CONTROL_BEGIN; - currentOverlappedIdx = 0; - futureOverlappedIdx = NOTIFICATION_OVERLAPPED_QUEUE_SIZE - 1; + VIGEM_UNPLUG_TARGET_INIT(&unplug, target->SerialNo); - // Send out DeviceIOControl calls to wait for incoming feedback notifications. Use N pending requests to make sure that events are not lost even when application would flood FFB events. - // The order of DeviceIoControl calls and GetOverlappedResult requests is important to ensure that feedback callback function is called in correct order (ie. FIFO buffer with FFB events). - // Note! This loop doesn't call DevIo for the last lOverlapped item on purpose. The DO while loop does it as a first step (futureOverlappedIdx=NOTIFICATION_OVERLAPPED_QUEUE_SIZE-1 in the first loop round). - for (idx = 0; idx < NOTIFICATION_OVERLAPPED_QUEUE_SIZE-1; idx++) - { - devIoResult[idx] = DeviceIoControl(client->hBusDevice, - (*pNotificationRequestPayload)[idx]->ioControlCode, - (*pNotificationRequestPayload)[idx]->lpPayloadBuffer, - (*pNotificationRequestPayload)[idx]->payloadBufferSize, - (*pNotificationRequestPayload)[idx]->lpPayloadBuffer, - (*pNotificationRequestPayload)[idx]->payloadBufferSize, - &transferred[idx], - &lOverlapped[idx]); - - lastIoError[idx] = GetLastError(); - } + DeviceIoControl( + vigem->hBusDevice, + IOCTL_VIGEM_UNPLUG_TARGET, + &unplug, + unplug.Size, + nullptr, + 0, + &transferred, + &lOverlapped + ); - do + if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) != 0) { - // Before reading data from "current overlapped request" then send a new DeviceIoControl request to wait for upcoming new FFB events (ring buffer of overlapped objects). - devIoResult[futureOverlappedIdx] = DeviceIoControl(client->hBusDevice, - (*pNotificationRequestPayload)[futureOverlappedIdx]->ioControlCode, - (*pNotificationRequestPayload)[futureOverlappedIdx]->lpPayloadBuffer, - (*pNotificationRequestPayload)[futureOverlappedIdx]->payloadBufferSize, - (*pNotificationRequestPayload)[futureOverlappedIdx]->lpPayloadBuffer, - (*pNotificationRequestPayload)[futureOverlappedIdx]->payloadBufferSize, - &transferred[futureOverlappedIdx], - &lOverlapped[futureOverlappedIdx]); - - lastIoError[futureOverlappedIdx] = GetLastError(); - - // currentOverlappedIdx is an index to the "oldest" DeviceIOControl call, so it will receive the next FFB event in a FFB sequence (in case there are multiple FFB events coming in) - if (!devIoResult[currentOverlappedIdx]) + if (target->Ds4CachedOutputReportUpdateAvailable) { - if (lastIoError[currentOverlappedIdx] == ERROR_IO_PENDING) - { - // DeviceIoControl is not yet completed to return all data. Wait for overlapped completion and thread cancellation events - waitObjects[1] = lOverlapped[currentOverlappedIdx].hEvent; - error = WaitForMultipleObjects(2, waitObjects, FALSE, INFINITE); - if (error != (WAIT_OBJECT_0 + 1)) - break; // Cancel event signaled or error while waiting for events (maybe handles were closed?). Quit this thread worker - - // At this point overlapped event was signaled by a device driver and data is ready and waiting for in a buffer. The next GetOverlappedResult call should return immediately. - } - else - // Hmm... DeviceIoControl failed and is not just in async pending state. Quit the notification thread because the virtual controller may be in unknown state or device handles were closed - break; + CloseHandle(target->Ds4CachedOutputReportUpdateAvailable); } - if (GetOverlappedResult(client->hBusDevice, &lOverlapped[currentOverlappedIdx], &transferred[currentOverlappedIdx], TRUE) != 0) - (*pNotificationRequestPayload)[currentOverlappedIdx]->ProcessNotificationRequest(client, target); + vigem->pTargetsList[target->SerialNo] = nullptr; - if (currentOverlappedIdx >= NOTIFICATION_OVERLAPPED_QUEUE_SIZE-1) - currentOverlappedIdx = 0; - else - currentOverlappedIdx++; + target->State = VIGEM_TARGET_DISCONNECTED; + DEVICE_IO_CONTROL_END; - if (futureOverlappedIdx >= NOTIFICATION_OVERLAPPED_QUEUE_SIZE-1) - futureOverlappedIdx = 0; - else - futureOverlappedIdx++; - } while (target->closingNotificationThreads != TRUE && target->Notification != nullptr); + return VIGEM_ERROR_NONE; + } - for (idx = 0; idx < NOTIFICATION_OVERLAPPED_QUEUE_SIZE; idx++) - if(lOverlapped[idx].hEvent) - CloseHandle(lOverlapped[idx].hEvent); + DEVICE_IO_CONTROL_END; - // Caller created the unique_ptr object, but this thread worker function should delete the object because it is no longer needed (thread specific object) - pNotificationRequestPayload.reset(); + return VIGEM_ERROR_REMOVAL_FAILED; } VIGEM_ERROR vigem_target_x360_register_notification( - PVIGEM_CLIENT vigem, - PVIGEM_TARGET target, - PFN_VIGEM_X360_NOTIFICATION notification + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PFN_VIGEM_X360_NOTIFICATION notification, + LPVOID userData ) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + if (!target) + return VIGEM_ERROR_INVALID_TARGET; - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; - if (target->SerialNo == 0 || notification == nullptr) - return VIGEM_ERROR_INVALID_TARGET; + if (target->SerialNo == 0 || notification == nullptr) + return VIGEM_ERROR_INVALID_TARGET; - if (target->Notification == reinterpret_cast(notification)) - return VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED; + if (target->Notification == reinterpret_cast(notification)) + return VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED; - target->Notification = reinterpret_cast(notification); + target->Notification = reinterpret_cast(notification); + target->NotificationUserData = userData; - if (target->cancelNotificationThreadEvent == 0) - target->cancelNotificationThreadEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); + if (target->CancelNotificationThreadEvent == nullptr) + target->CancelNotificationThreadEvent = CreateEvent( + nullptr, + TRUE, + FALSE, + nullptr + ); else - ResetEvent(target->cancelNotificationThreadEvent); + ResetEvent(target->CancelNotificationThreadEvent); - if(target->notificationThreadList == nullptr) - target->notificationThreadList = std::make_unique>(); - - target->closingNotificationThreads = FALSE; - - std::unique_ptr>> payloadVector = std::make_unique>>(); - payloadVector->reserve(NOTIFICATION_OVERLAPPED_QUEUE_SIZE); - for (int idx = 0; idx < NOTIFICATION_OVERLAPPED_QUEUE_SIZE; idx++) - payloadVector->push_back(std::make_unique(target->SerialNo)); + std::thread _async{ + []( + PVIGEM_TARGET _Target, + PVIGEM_CLIENT _Client, + LPVOID _UserData) + { + DEVICE_IO_CONTROL_BEGIN; - // Nowadays there is only one background thread listening for incoming FFB events, but there used to be more. This code still uses notificationThreadList vector even - // when there is only one item in the vector. If it is someday find out that this logic needs more background threads then it is easy to do because the thread vector is already in place. - //for (int i = 0; i < 1; i++) - target->notificationThreadList->emplace_back(std::thread(&vigem_notification_thread_worker, vigem, target, std::move(payloadVector))); + XUSB_REQUEST_NOTIFICATION xrn; + XUSB_REQUEST_NOTIFICATION_INIT(&xrn, _Target->SerialNo); - return VIGEM_ERROR_NONE; + do + { + DeviceIoControl( + _Client->hBusDevice, + IOCTL_XUSB_REQUEST_NOTIFICATION, + &xrn, + xrn.Size, + &xrn, + xrn.Size, + &transferred, + &lOverlapped + ); + + if (GetOverlappedResult(_Client->hBusDevice, &lOverlapped, &transferred, TRUE) != 0) + { + if (_Target->Notification == nullptr) + { + DEVICE_IO_CONTROL_END; + return; + } + + reinterpret_cast(_Target->Notification)( + _Client, _Target, xrn.LargeMotor, xrn.SmallMotor, xrn.LedNumber, _UserData + ); + + continue; + } + + if (GetLastError() == ERROR_ACCESS_DENIED || GetLastError() == ERROR_OPERATION_ABORTED) + { + DEVICE_IO_CONTROL_END; + return; + } + } while (TRUE); + }, + target, vigem, userData + }; + + _async.detach(); + + return VIGEM_ERROR_NONE; } VIGEM_ERROR vigem_target_ds4_register_notification( - PVIGEM_CLIENT vigem, - PVIGEM_TARGET target, - PFN_VIGEM_DS4_NOTIFICATION notification + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PFN_VIGEM_DS4_NOTIFICATION notification, + LPVOID userData ) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + if (!target) + return VIGEM_ERROR_INVALID_TARGET; - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; - if (target->SerialNo == 0 || notification == nullptr) - return VIGEM_ERROR_INVALID_TARGET; + if (target->SerialNo == 0 || notification == nullptr) + return VIGEM_ERROR_INVALID_TARGET; - if (target->Notification == reinterpret_cast(notification)) - return VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED; + if (target->Notification == reinterpret_cast(notification)) + return VIGEM_ERROR_CALLBACK_ALREADY_REGISTERED; - target->Notification = reinterpret_cast(notification); + target->Notification = reinterpret_cast(notification); + target->NotificationUserData = userData; - if (target->cancelNotificationThreadEvent == 0) - target->cancelNotificationThreadEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); + if (target->CancelNotificationThreadEvent == nullptr) + target->CancelNotificationThreadEvent = CreateEvent( + nullptr, + TRUE, + FALSE, + nullptr + ); else - ResetEvent(target->cancelNotificationThreadEvent); + ResetEvent(target->CancelNotificationThreadEvent); - if (target->notificationThreadList == nullptr) - target->notificationThreadList = std::make_unique>(); - - target->closingNotificationThreads = FALSE; - - std::unique_ptr>> payloadVector = std::make_unique>>(); - payloadVector->reserve(NOTIFICATION_OVERLAPPED_QUEUE_SIZE); - for (int idx = 0; idx < NOTIFICATION_OVERLAPPED_QUEUE_SIZE; idx++) - payloadVector->push_back(std::make_unique(target->SerialNo)); + std::thread _async{ + []( + PVIGEM_TARGET _Target, + PVIGEM_CLIENT _Client, + LPVOID _UserData) + { + DEVICE_IO_CONTROL_BEGIN; - //for (int i = 0; i < 1; i++) - target->notificationThreadList->emplace_back(std::thread(&vigem_notification_thread_worker, vigem, target, std::move(payloadVector))); + DS4_REQUEST_NOTIFICATION ds4rn; + DS4_REQUEST_NOTIFICATION_INIT(&ds4rn, _Target->SerialNo); - return VIGEM_ERROR_NONE; + do + { + DeviceIoControl( + _Client->hBusDevice, + IOCTL_DS4_REQUEST_NOTIFICATION, + &ds4rn, + ds4rn.Size, + &ds4rn, + ds4rn.Size, + &transferred, + &lOverlapped + ); + + if (GetOverlappedResult(_Client->hBusDevice, &lOverlapped, &transferred, TRUE) != 0) + { + if (_Target->Notification == nullptr) + { + DEVICE_IO_CONTROL_END; + return; + } + + reinterpret_cast(_Target->Notification)( + _Client, _Target, ds4rn.Report.LargeMotor, + ds4rn.Report.SmallMotor, + ds4rn.Report.LightbarColor, _UserData + ); + + continue; + } + + if (GetLastError() == ERROR_ACCESS_DENIED || GetLastError() == ERROR_OPERATION_ABORTED) + { + DEVICE_IO_CONTROL_END; + return; + } + } while (TRUE); + }, + target, vigem, userData + }; + + _async.detach(); + + return VIGEM_ERROR_NONE; } void vigem_target_x360_unregister_notification(PVIGEM_TARGET target) { - target->closingNotificationThreads = TRUE; + if (target->CancelNotificationThreadEvent != nullptr) + SetEvent(target->CancelNotificationThreadEvent); - if (target->cancelNotificationThreadEvent != 0) - SetEvent(target->cancelNotificationThreadEvent); - - if (target->notificationThreadList != nullptr) - { - // Wait for completion of all notification threads before cleaning up target object and Notification function pointer (a thread may be in the middle of handling a notification request, so close it cleanly) - std::for_each(target->notificationThreadList->begin(), target->notificationThreadList->end(), std::mem_fn(&std::thread::join)); - target->notificationThreadList.reset(); - target->notificationThreadList = nullptr; - } - - if (target->cancelNotificationThreadEvent != 0) + if (target->CancelNotificationThreadEvent != nullptr) { - CloseHandle(target->cancelNotificationThreadEvent); - target->cancelNotificationThreadEvent = 0; + CloseHandle(target->CancelNotificationThreadEvent); + target->CancelNotificationThreadEvent = nullptr; } target->Notification = nullptr; + target->NotificationUserData = nullptr; } void vigem_target_ds4_unregister_notification(PVIGEM_TARGET target) @@ -776,202 +866,310 @@ void vigem_target_ds4_unregister_notification(PVIGEM_TARGET target) void vigem_target_set_vid(PVIGEM_TARGET target, USHORT vid) { - target->VendorId = vid; + target->VendorId = vid; } void vigem_target_set_pid(PVIGEM_TARGET target, USHORT pid) { - target->ProductId = pid; + target->ProductId = pid; } USHORT vigem_target_get_vid(PVIGEM_TARGET target) { - return target->VendorId; + return target->VendorId; } USHORT vigem_target_get_pid(PVIGEM_TARGET target) { - return target->ProductId; + return target->ProductId; } VIGEM_ERROR vigem_target_x360_update( - PVIGEM_CLIENT vigem, - PVIGEM_TARGET target, - XUSB_REPORT report + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + XUSB_REPORT report ) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + if (!target) + return VIGEM_ERROR_INVALID_TARGET; - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; - if (target->SerialNo == 0) - return VIGEM_ERROR_INVALID_TARGET; + if (target->SerialNo == 0) + return VIGEM_ERROR_INVALID_TARGET; - DWORD transferred = 0; - OVERLAPPED lOverlapped = { 0 }; - lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + DEVICE_IO_CONTROL_BEGIN; - XUSB_SUBMIT_REPORT xsr; - XUSB_SUBMIT_REPORT_INIT(&xsr, target->SerialNo); + XUSB_SUBMIT_REPORT xsr; + XUSB_SUBMIT_REPORT_INIT(&xsr, target->SerialNo); - xsr.Report = report; + xsr.Report = report; - DeviceIoControl( - vigem->hBusDevice, - IOCTL_XUSB_SUBMIT_REPORT, - &xsr, - xsr.Size, - nullptr, - 0, - &transferred, - &lOverlapped - ); + DeviceIoControl( + vigem->hBusDevice, + IOCTL_XUSB_SUBMIT_REPORT, + &xsr, + xsr.Size, + nullptr, + 0, + &transferred, + &lOverlapped + ); - if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) - { - if (GetLastError() == ERROR_ACCESS_DENIED) - { - CloseHandle(lOverlapped.hEvent); - return VIGEM_ERROR_INVALID_TARGET; - } - } + if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) + { + if (GetLastError() == ERROR_ACCESS_DENIED) + { + DEVICE_IO_CONTROL_END; + return VIGEM_ERROR_INVALID_TARGET; + } + } - CloseHandle(lOverlapped.hEvent); + DEVICE_IO_CONTROL_END; - return VIGEM_ERROR_NONE; + return VIGEM_ERROR_NONE; } VIGEM_ERROR vigem_target_ds4_update( - PVIGEM_CLIENT vigem, - PVIGEM_TARGET target, - DS4_REPORT report + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + DS4_REPORT report +) +{ + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; + + if (!target) + return VIGEM_ERROR_INVALID_TARGET; + + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; + + if (target->SerialNo == 0) + return VIGEM_ERROR_INVALID_TARGET; + + DEVICE_IO_CONTROL_BEGIN; + + DS4_SUBMIT_REPORT dsr; + DS4_SUBMIT_REPORT_INIT(&dsr, target->SerialNo); + + dsr.Report = report; + + DeviceIoControl( + vigem->hBusDevice, + IOCTL_DS4_SUBMIT_REPORT, + &dsr, + dsr.Size, + nullptr, + 0, + &transferred, + &lOverlapped + ); + + if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) + { + if (GetLastError() == ERROR_ACCESS_DENIED) + { + DEVICE_IO_CONTROL_END; + return VIGEM_ERROR_INVALID_TARGET; + } + } + + DEVICE_IO_CONTROL_END; + + return VIGEM_ERROR_NONE; +} + +VIGEM_ERROR vigem_target_ds4_update_ex( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + DS4_REPORT_EX report ) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + if (!target) + return VIGEM_ERROR_INVALID_TARGET; - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; - if (target->SerialNo == 0) - return VIGEM_ERROR_INVALID_TARGET; + if (target->SerialNo == 0) + return VIGEM_ERROR_INVALID_TARGET; - DWORD transferred = 0; - OVERLAPPED lOverlapped = { 0 }; - lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); + DEVICE_IO_CONTROL_BEGIN; - DS4_SUBMIT_REPORT dsr; - DS4_SUBMIT_REPORT_INIT(&dsr, target->SerialNo); + DS4_SUBMIT_REPORT_EX dsr; + DS4_SUBMIT_REPORT_EX_INIT(&dsr, target->SerialNo); - dsr.Report = report; + dsr.Report = report; - DeviceIoControl( - vigem->hBusDevice, - IOCTL_DS4_SUBMIT_REPORT, - &dsr, - dsr.Size, - nullptr, - 0, - &transferred, - &lOverlapped - ); + DeviceIoControl( + vigem->hBusDevice, + IOCTL_DS4_SUBMIT_REPORT, // Same IOCTL, just different size + &dsr, + dsr.Size, + nullptr, + 0, + &transferred, + &lOverlapped + ); + + if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) + { + if (GetLastError() == ERROR_ACCESS_DENIED) + { + DEVICE_IO_CONTROL_END; + return VIGEM_ERROR_INVALID_TARGET; + } - if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) - { - if (GetLastError() == ERROR_ACCESS_DENIED) - { - CloseHandle(lOverlapped.hEvent); - return VIGEM_ERROR_INVALID_TARGET; - } - } + /* + * NOTE: this will not happen on v1.16 due to NTSTATUS accidentally been set + * as STATUS_SUCCESS when the submitted buffer size wasn't the expected one. + * For backwards compatibility this function will silently fail (not cause + * report updates) when run with the v1.16 driver. This API was introduced + * with v1.17 so it won't affect existing applications built before. + */ + if (GetLastError() == ERROR_INVALID_PARAMETER) + { + DEVICE_IO_CONTROL_END; + return VIGEM_ERROR_NOT_SUPPORTED; + } + } - CloseHandle(lOverlapped.hEvent); + DEVICE_IO_CONTROL_END; - return VIGEM_ERROR_NONE; + return VIGEM_ERROR_NONE; } ULONG vigem_target_get_index(PVIGEM_TARGET target) { - return target->SerialNo; + return target->SerialNo; } VIGEM_TARGET_TYPE vigem_target_get_type(PVIGEM_TARGET target) { - return target->Type; + return target->Type; } BOOL vigem_target_is_attached(PVIGEM_TARGET target) { - return (target->State == VIGEM_TARGET_CONNECTED); + return (target->State == VIGEM_TARGET_CONNECTED); } VIGEM_ERROR vigem_target_x360_get_user_index( - PVIGEM_CLIENT vigem, - PVIGEM_TARGET target, - PULONG index + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PULONG index ) { - if (!vigem) - return VIGEM_ERROR_BUS_INVALID_HANDLE; + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; - if (!target) - return VIGEM_ERROR_INVALID_TARGET; + if (!target) + return VIGEM_ERROR_INVALID_TARGET; - if (vigem->hBusDevice == INVALID_HANDLE_VALUE) - return VIGEM_ERROR_BUS_NOT_FOUND; + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; - if (target->SerialNo == 0 || target->Type != Xbox360Wired) - return VIGEM_ERROR_INVALID_TARGET; + if (target->SerialNo == 0 || target->Type != Xbox360Wired) + return VIGEM_ERROR_INVALID_TARGET; if (!index) return VIGEM_ERROR_INVALID_PARAMETER; - DWORD transferred = 0; - OVERLAPPED lOverlapped = { 0 }; - lOverlapped.hEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); - - XUSB_GET_USER_INDEX gui; - XUSB_GET_USER_INDEX_INIT(&gui, target->SerialNo); - - DeviceIoControl( - vigem->hBusDevice, - IOCTL_XUSB_GET_USER_INDEX, - &gui, - gui.Size, - &gui, - gui.Size, - &transferred, - &lOverlapped - ); - - if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) - { - const auto error = GetLastError(); - - if (error == ERROR_ACCESS_DENIED) - { - CloseHandle(lOverlapped.hEvent); - return VIGEM_ERROR_INVALID_TARGET; - } - - if (error == ERROR_INVALID_DEVICE_OBJECT_PARAMETER) - { - CloseHandle(lOverlapped.hEvent); - return VIGEM_ERROR_XUSB_USERINDEX_OUT_OF_RANGE; - } - } - - CloseHandle(lOverlapped.hEvent); - - *index = gui.UserIndex; - - return VIGEM_ERROR_NONE; + DEVICE_IO_CONTROL_BEGIN; + + XUSB_GET_USER_INDEX gui; + XUSB_GET_USER_INDEX_INIT(&gui, target->SerialNo); + + DeviceIoControl( + vigem->hBusDevice, + IOCTL_XUSB_GET_USER_INDEX, + &gui, + gui.Size, + &gui, + gui.Size, + &transferred, + &lOverlapped + ); + + if (GetOverlappedResult(vigem->hBusDevice, &lOverlapped, &transferred, TRUE) == 0) + { + const auto error = GetLastError(); + + if (error == ERROR_ACCESS_DENIED) + { + DEVICE_IO_CONTROL_END; + return VIGEM_ERROR_INVALID_TARGET; + } + + if (error == ERROR_INVALID_DEVICE_OBJECT_PARAMETER) + { + DEVICE_IO_CONTROL_END; + return VIGEM_ERROR_XUSB_USERINDEX_OUT_OF_RANGE; + } + } + + DEVICE_IO_CONTROL_END; + + *index = gui.UserIndex; + + return VIGEM_ERROR_NONE; +} + +VIGEM_ERROR vigem_target_ds4_await_output_report( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + PDS4_OUTPUT_BUFFER buffer +) +{ + return vigem_target_ds4_await_output_report_timeout(vigem, target, INFINITE, buffer); +} + +VIGEM_ERROR vigem_target_ds4_await_output_report_timeout( + PVIGEM_CLIENT vigem, + PVIGEM_TARGET target, + DWORD milliseconds, + PDS4_OUTPUT_BUFFER buffer +) +{ + if (!vigem) + return VIGEM_ERROR_BUS_INVALID_HANDLE; + + if (!target) + return VIGEM_ERROR_INVALID_TARGET; + + if (vigem->hBusDevice == INVALID_HANDLE_VALUE) + return VIGEM_ERROR_BUS_NOT_FOUND; + + if (target->SerialNo == 0) + return VIGEM_ERROR_INVALID_TARGET; + + if (!buffer) + return VIGEM_ERROR_INVALID_PARAMETER; + + const DWORD status = WaitForSingleObject(target->Ds4CachedOutputReportUpdateAvailable, milliseconds); + + if (status == WAIT_TIMEOUT) + { + return VIGEM_ERROR_TIMED_OUT; +} + +#if defined(VIGEM_VERBOSE_LOGGING_ENABLED) + DBGPRINT(L"Dumping buffer for %d", target->SerialNo); + + const PCHAR dumpBuffer = (PCHAR)calloc(sizeof(DS4_OUTPUT_BUFFER), 3); + to_hex(target->Ds4CachedOutputReport.Buffer, sizeof(DS4_OUTPUT_BUFFER), dumpBuffer, sizeof(DS4_OUTPUT_BUFFER) * 3); + OutputDebugStringA(dumpBuffer); +#endif + + RtlCopyMemory(buffer, &target->Ds4CachedOutputReport, sizeof(DS4_OUTPUT_BUFFER)); + + return VIGEM_ERROR_NONE; } diff --git a/Xb2XInput/XboxController.cpp b/Xb2XInput/XboxController.cpp index 1caa884..52afe3f 100644 --- a/Xb2XInput/XboxController.cpp +++ b/Xb2XInput/XboxController.cpp @@ -30,6 +30,7 @@ std::vector> xbox_devices = {0x0738, 0x4556}, // MadCatz Lynx Wireless Controller {0x0738, 0x4586}, // MadCatz MicroCon Wireless Controller {0x0738, 0x4588}, // MadCatz Blaster + {0x0738, 0x6320}, // MadCatz MC2 Universal Racing Wheel and Pedals {0x0C12, 0x0005}, // Intec wireless {0x0C12, 0x8801}, // Nyko Xbox Controller {0x0C12, 0x8802}, // Zeroplus Xbox Controller @@ -382,7 +383,7 @@ XboxController::~XboxController() active_ = false; } -void CALLBACK XboxController::OnVigemNotification(PVIGEM_CLIENT Client, PVIGEM_TARGET Target, UCHAR LargeMotor, UCHAR SmallMotor, UCHAR LedNumber) +void CALLBACK XboxController::OnVigemNotification(PVIGEM_CLIENT Client, PVIGEM_TARGET Target, UCHAR LargeMotor, UCHAR SmallMotor, UCHAR LedNumber, LPVOID UserData) { for (auto& controller : controllers_) { diff --git a/Xb2XInput/XboxController.hpp b/Xb2XInput/XboxController.hpp index 3239e41..cdc9f19 100644 --- a/Xb2XInput/XboxController.hpp +++ b/Xb2XInput/XboxController.hpp @@ -173,6 +173,7 @@ class XboxController PVIGEM_TARGET Target, UCHAR LargeMotor, UCHAR SmallMotor, - UCHAR LedNumber + UCHAR LedNumber, + LPVOID UserData ); }; diff --git a/dist/x64/Drivers/install drivers.bat b/dist/x64/Drivers/install drivers.bat index ed9d990..e0f330e 100644 --- a/dist/x64/Drivers/install drivers.bat +++ b/dist/x64/Drivers/install drivers.bat @@ -39,6 +39,7 @@ wdi-simple --vid 0x0738 --pid 0x4536 --type 0 --name "MadCatz MicroCON" wdi-simple --vid 0x0738 --pid 0x4556 --type 0 --name "MadCatz Lynx Wireless Controller" wdi-simple --vid 0x0738 --pid 0x4586 --type 0 --name "MadCatz MicroCon Wireless Controller" wdi-simple --vid 0x0738 --pid 0x4588 --type 0 --name "MadCatz Blaster" +wdi-simple --vid 0x0738 --pid 0x6320 --type 0 --name "MadCatz MC2 Universal Racing Wheel and Pedals" wdi-simple --vid 0x0C12 --pid 0x0005 --type 0 --name "Intec wireless" wdi-simple --vid 0x0C12 --pid 0x8801 --type 0 --name "Nyko Xbox Controller" wdi-simple --vid 0x0C12 --pid 0x8802 --type 0 --name "Zeroplus Xbox Controller" diff --git a/dist/x64/libusb-1.0.dll b/dist/x64/libusb-1.0.dll index b6d3aa2..137897c 100644 Binary files a/dist/x64/libusb-1.0.dll and b/dist/x64/libusb-1.0.dll differ diff --git a/dist/x86/Drivers/install drivers.bat b/dist/x86/Drivers/install drivers.bat index ed9d990..e0f330e 100644 --- a/dist/x86/Drivers/install drivers.bat +++ b/dist/x86/Drivers/install drivers.bat @@ -39,6 +39,7 @@ wdi-simple --vid 0x0738 --pid 0x4536 --type 0 --name "MadCatz MicroCON" wdi-simple --vid 0x0738 --pid 0x4556 --type 0 --name "MadCatz Lynx Wireless Controller" wdi-simple --vid 0x0738 --pid 0x4586 --type 0 --name "MadCatz MicroCon Wireless Controller" wdi-simple --vid 0x0738 --pid 0x4588 --type 0 --name "MadCatz Blaster" +wdi-simple --vid 0x0738 --pid 0x6320 --type 0 --name "MadCatz MC2 Universal Racing Wheel and Pedals" wdi-simple --vid 0x0C12 --pid 0x0005 --type 0 --name "Intec wireless" wdi-simple --vid 0x0C12 --pid 0x8801 --type 0 --name "Nyko Xbox Controller" wdi-simple --vid 0x0C12 --pid 0x8802 --type 0 --name "Zeroplus Xbox Controller" diff --git a/dist/x86/libusb-1.0.dll b/dist/x86/libusb-1.0.dll index 4eda7fa..52ad17b 100644 Binary files a/dist/x86/libusb-1.0.dll and b/dist/x86/libusb-1.0.dll differ