diff --git a/CMakeLists.txt b/CMakeLists.txt index 032e35dd65..cd827bceed 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2317,6 +2317,8 @@ elseif(UNIX AND NOT (APPLE OR RISCOS OR HAIKU OR CYGWIN)) sdl_sources( "${SDL3_SOURCE_DIR}/src/core/linux/SDL_evdev_capabilities.c" "${SDL3_SOURCE_DIR}/src/core/linux/SDL_evdev_capabilities.h" + "${SDL3_SOURCE_DIR}/src/core/linux/SDL_sysfs.c" + "${SDL3_SOURCE_DIR}/src/core/linux/SDL_sysfs.h" "${SDL3_SOURCE_DIR}/src/core/linux/SDL_threadprio.c" "${SDL3_SOURCE_DIR}/src/core/linux/SDL_ubuntu_touch.c" ) @@ -2759,6 +2761,13 @@ elseif(APPLE) # !!! FIXME: all the `if(IOS OR TVOS OR VISIONOS)` checks should get merged into one variable, so we're ready for the next platform (or just WatchOS). + if(MACOS) + sdl_glob_sources( + "${SDL3_SOURCE_DIR}/src/core/macos/*.c" + "${SDL3_SOURCE_DIR}/src/core/macos/*.h" + ) + endif() + # We always need these libs on macOS at the moment. # !!! FIXME: we need Carbon for some very old API calls in # !!! FIXME: src/video/cocoa/SDL_cocoakeyboard.c, but we should figure out diff --git a/Xcode/SDL/SDL.xcodeproj/project.pbxproj b/Xcode/SDL/SDL.xcodeproj/project.pbxproj index 6663fb0deb..d1d887a7f7 100644 --- a/Xcode/SDL/SDL.xcodeproj/project.pbxproj +++ b/Xcode/SDL/SDL.xcodeproj/project.pbxproj @@ -396,6 +396,8 @@ F32DDAD12AB795A30041EAA5 /* SDL_audioqueue.c in Sources */ = {isa = PBXBuildFile; fileRef = F32DDACB2AB795A30041EAA5 /* SDL_audioqueue.c */; }; F32DDAD32AB795A30041EAA5 /* SDL_audioqueue.h in Headers */ = {isa = PBXBuildFile; fileRef = F32DDACD2AB795A30041EAA5 /* SDL_audioqueue.h */; }; F32DDAD42AB795A30041EAA5 /* SDL_audioresample.c in Sources */ = {isa = PBXBuildFile; fileRef = F32DDACE2AB795A30041EAA5 /* SDL_audioresample.c */; }; + F332BC2C309E981500C967E5 /* SDL_ioreg.h in Headers */ = {isa = PBXBuildFile; fileRef = F332BC2A309E981500C967E5 /* SDL_ioreg.h */; platformFilters = (macos, ); }; + F332BC2D309E981500C967E5 /* SDL_ioreg.c in Sources */ = {isa = PBXBuildFile; fileRef = F332BC2B309E981500C967E5 /* SDL_ioreg.c */; platformFilters = (macos, ); }; F338A1182D1B37D8007CDFDF /* SDL_tray.m in Sources */ = {isa = PBXBuildFile; fileRef = F338A1172D1B37D8007CDFDF /* SDL_tray.m */; }; F338A11A2D1B37E4007CDFDF /* SDL_tray.c in Sources */ = {isa = PBXBuildFile; fileRef = F338A1192D1B37E4007CDFDF /* SDL_tray.c */; }; F3395BA82D9A5971007246C8 /* SDL_hidapi_8bitdo.c in Sources */ = {isa = PBXBuildFile; fileRef = F3395BA72D9A5971007246C8 /* SDL_hidapi_8bitdo.c */; }; @@ -988,6 +990,8 @@ F32DDACB2AB795A30041EAA5 /* SDL_audioqueue.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_audioqueue.c; sourceTree = ""; }; F32DDACD2AB795A30041EAA5 /* SDL_audioqueue.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SDL_audioqueue.h; sourceTree = ""; }; F32DDACE2AB795A30041EAA5 /* SDL_audioresample.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = SDL_audioresample.c; sourceTree = ""; }; + F332BC2A309E981500C967E5 /* SDL_ioreg.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SDL_ioreg.h; sourceTree = ""; }; + F332BC2B309E981500C967E5 /* SDL_ioreg.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = SDL_ioreg.c; sourceTree = ""; }; F338A1172D1B37D8007CDFDF /* SDL_tray.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SDL_tray.m; sourceTree = ""; }; F338A1192D1B37E4007CDFDF /* SDL_tray.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = SDL_tray.c; sourceTree = ""; }; F3395BA72D9A5971007246C8 /* SDL_hidapi_8bitdo.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = SDL_hidapi_8bitdo.c; sourceTree = ""; }; @@ -2450,6 +2454,15 @@ path = xr; sourceTree = ""; }; + F332BC29309E97E500C967E5 /* macos */ = { + isa = PBXGroup; + children = ( + F332BC2A309E981500C967E5 /* SDL_ioreg.h */, + F332BC2B309E981500C967E5 /* SDL_ioreg.c */, + ); + path = macos; + sourceTree = ""; + }; F338A1142D1B3735007CDFDF /* tray */ = { isa = PBXGroup; children = ( @@ -2488,6 +2501,7 @@ F36C7ACF294B9F5E004D61C3 /* core */ = { isa = PBXGroup; children = ( + F332BC29309E97E500C967E5 /* macos */, E4F798192AD8D84800669F54 /* SDL_core_unsupported.c */, ); path = core; @@ -2790,6 +2804,7 @@ 566E26E1246274CC00718109 /* SDL_syslocale.h in Headers */, A7D8B44023E2514300DCD162 /* SDL_sysmutex_c.h in Headers */, A7D8B5D523E2514300DCD162 /* SDL_syspower.h in Headers */, + F332BC2C309E981500C967E5 /* SDL_ioreg.h in Headers */, A7D8B61123E2514300DCD162 /* SDL_syspower.h in Headers */, A7D8B9D723E2514400DCD162 /* SDL_sysrender.h in Headers */, A7D8A97B23E2514000DCD162 /* SDL_syssensor.h in Headers */, @@ -3175,6 +3190,7 @@ A7D8B54523E2514300DCD162 /* SDL_hidapijoystick.c in Sources */, A7D8B97423E2514400DCD162 /* SDL_malloc.c in Sources */, A7D8B8C623E2514400DCD162 /* SDL_audio.c in Sources */, + F332BC2D309E981500C967E5 /* SDL_ioreg.c in Sources */, A7D8B61D23E2514300DCD162 /* SDL_sysfilesystem.c in Sources */, E4F257932C81903800FCEAFC /* SDL_gpu_metal.m in Sources */, F3820713284F3609004DD584 /* controller_type.c in Sources */, diff --git a/include/SDL3/SDL_audio.h b/include/SDL3/SDL_audio.h index af5fc9585e..583d4fb076 100644 --- a/include/SDL3/SDL_audio.h +++ b/include/SDL3/SDL_audio.h @@ -675,6 +675,7 @@ extern SDL_DECLSPEC int * SDLCALL SDL_GetAudioDeviceChannelMap(SDL_AudioDeviceID * The application can hang any data it wants here, but the following * properties are understood by SDL: * + * - `SDL_PROP_AUDIO_DEVICE_CONTAINER_ID_STRING`: a string identifying the container for this audio device, if available. This can be compared with SDL_PROP_GAMEPAD_CONTAINER_ID_STRING to find associated controllers. * - `SDL_PROP_AUDIO_DEVICE_UNIQUE_ID_STRING`: This identifier can be used to * locate a specific device. In optimal conditions, this identifier will not * change between runs of an app, hardware disconnection, and system @@ -702,7 +703,8 @@ extern SDL_DECLSPEC int * SDLCALL SDL_GetAudioDeviceChannelMap(SDL_AudioDeviceID */ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetAudioDeviceProperties(SDL_AudioDeviceID devid); -#define SDL_PROP_AUDIO_DEVICE_UNIQUE_ID_STRING "SDL.audio.device.unique_id" +#define SDL_PROP_AUDIO_DEVICE_CONTAINER_ID_STRING "SDL.audio.device.container_id" +#define SDL_PROP_AUDIO_DEVICE_UNIQUE_ID_STRING "SDL.audio.device.unique_id" /** diff --git a/include/SDL3/SDL_gamepad.h b/include/SDL3/SDL_gamepad.h index 2cb050071a..73297c864a 100644 --- a/include/SDL3/SDL_gamepad.h +++ b/include/SDL3/SDL_gamepad.h @@ -807,6 +807,7 @@ extern SDL_DECLSPEC SDL_Gamepad * SDLCALL SDL_GetGamepadFromPlayerIndex(int play * * The following read-only properties are provided by SDL: * + * - `SDL_PROP_GAMEPAD_CONTAINER_ID_STRING`: a string identifying the container for this gamepad, if available. This can be compared with SDL_PROP_AUDIO_DEVICE_CONTAINER_ID_STRING to find associated audio devices. * - `SDL_PROP_GAMEPAD_CAP_MONO_LED_BOOLEAN`: true if this gamepad has an LED * that has adjustable brightness * - `SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN`: true if this gamepad has an LED @@ -829,6 +830,7 @@ extern SDL_DECLSPEC SDL_Gamepad * SDLCALL SDL_GetGamepadFromPlayerIndex(int play */ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetGamepadProperties(SDL_Gamepad *gamepad); +#define SDL_PROP_GAMEPAD_CONTAINER_ID_STRING SDL_PROP_JOYSTICK_CONTAINER_ID_STRING #define SDL_PROP_GAMEPAD_CAP_MONO_LED_BOOLEAN SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN #define SDL_PROP_GAMEPAD_CAP_RGB_LED_BOOLEAN SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN #define SDL_PROP_GAMEPAD_CAP_PLAYER_LED_BOOLEAN SDL_PROP_JOYSTICK_CAP_PLAYER_LED_BOOLEAN diff --git a/include/SDL3/SDL_joystick.h b/include/SDL3/SDL_joystick.h index a1ab60ff89..35c2d14858 100644 --- a/include/SDL3/SDL_joystick.h +++ b/include/SDL3/SDL_joystick.h @@ -763,6 +763,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_SendJoystickVirtualSensorData(SDL_Joystick * * The following read-only properties are provided by SDL: * + * - `SDL_PROP_JOYSTICK_CONTAINER_ID_STRING`: a string identifying the container for this joystick, if available. * - `SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN`: true if this joystick has an * LED that has adjustable brightness * - `SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN`: true if this joystick has an LED @@ -784,6 +785,7 @@ extern SDL_DECLSPEC bool SDLCALL SDL_SendJoystickVirtualSensorData(SDL_Joystick */ extern SDL_DECLSPEC SDL_PropertiesID SDLCALL SDL_GetJoystickProperties(SDL_Joystick *joystick); +#define SDL_PROP_JOYSTICK_CONTAINER_ID_STRING "SDL.joystick.container_id" #define SDL_PROP_JOYSTICK_CAP_MONO_LED_BOOLEAN "SDL.joystick.cap.mono_led" #define SDL_PROP_JOYSTICK_CAP_RGB_LED_BOOLEAN "SDL.joystick.cap.rgb_led" #define SDL_PROP_JOYSTICK_CAP_PLAYER_LED_BOOLEAN "SDL.joystick.cap.player_led" diff --git a/src/SDL_utils.c b/src/SDL_utils.c index fdad1e57ad..f847569bbc 100644 --- a/src/SDL_utils.c +++ b/src/SDL_utils.c @@ -131,6 +131,16 @@ bool SDL_endswith(const char *string, const char *suffix) return false; } +bool SDL_IsZeroGUID(const SDL_GUID *guid) +{ + for (int i = 0; i < SDL_arraysize(guid->data); ++i) { + if (guid->data[i]) { + return false; + } + } + return true; +} + SDL_COMPILE_TIME_ASSERT(sizeof_object_id, sizeof(int) == sizeof(Uint32)); Uint32 SDL_GetNextObjectID(void) diff --git a/src/SDL_utils_c.h b/src/SDL_utils_c.h index a49eaa11b6..5830c84c3f 100644 --- a/src/SDL_utils_c.h +++ b/src/SDL_utils_c.h @@ -35,6 +35,8 @@ extern void SDL_CalculateFraction(float x, int *numerator, int *denominator); extern bool SDL_startswith(const char *string, const char *prefix); extern bool SDL_endswith(const char *string, const char *suffix); +extern bool SDL_IsZeroGUID(const SDL_GUID *guid); + /** Convert URI to a local filename, stripping the "file://" * preamble and hostname if present, and writes the result * to the dst buffer. Since URI-encoded characters take diff --git a/src/audio/SDL_audio.c b/src/audio/SDL_audio.c index f678df9fc1..bc080bcf2d 100644 --- a/src/audio/SDL_audio.c +++ b/src/audio/SDL_audio.c @@ -592,6 +592,22 @@ static void DestroyLogicalAudioDevice(SDL_LogicalAudioDevice *logdev) SDL_free(logdev); } +static void FreePhysicalAudioDevice(SDL_AudioDevice *device) +{ + if (device->props) { + SDL_DestroyProperties(device->props); + } + + SDL_DestroyMutex(device->lock); + SDL_DestroyCondition(device->close_cond); + SDL_free(device->work_buffer); + SDL_free(device->chmap); + SDL_free(device->container_id); + SDL_free(device->unique_id); + SDL_free(device->name); + SDL_free(device); +} + // this must not be called while `device` is still in a device list, or while a device's audio thread is still running. static void DestroyPhysicalAudioDevice(SDL_AudioDevice *device) { @@ -611,17 +627,7 @@ static void DestroyPhysicalAudioDevice(SDL_AudioDevice *device) SDL_UnlockMutex(device->lock); // don't use ReleaseAudioDevice because we don't want to change refcounts while destroying. - if (device->props) { - SDL_DestroyProperties(device->props); - } - - SDL_DestroyMutex(device->lock); - SDL_DestroyCondition(device->close_cond); - SDL_free(device->work_buffer); - SDL_free(device->chmap); - SDL_free(device->unique_id); - SDL_free(device->name); - SDL_free(device); + FreePhysicalAudioDevice(device); } // Don't hold the device lock when calling this, as we may destroy the device! @@ -643,7 +649,7 @@ void RefPhysicalAudioDevice(SDL_AudioDevice *device) SDL_AtomicIncRef(&device->refcount); } -static SDL_AudioDevice *CreatePhysicalAudioDevice(const char *name, const char *unique_id, bool recording, const SDL_AudioSpec *spec, void *handle, SDL_AtomicInt *device_count) +static SDL_AudioDevice *CreatePhysicalAudioDevice(const char *name, const char *container_id, const char *unique_id, bool recording, const SDL_AudioSpec *spec, void *handle, SDL_AtomicInt *device_count) { SDL_assert(name != NULL); @@ -654,40 +660,42 @@ static SDL_AudioDevice *CreatePhysicalAudioDevice(const char *name, const char * return NULL; // we're shutting down, don't add any devices that are hotplugged at the last possible moment. } - SDL_AudioDevice *device = (SDL_AudioDevice *)SDL_calloc(1, sizeof(SDL_AudioDevice)); + SDL_AudioDevice *device = (SDL_AudioDevice *)SDL_calloc(1, sizeof(*device)); if (!device) { return NULL; } device->name = SDL_strdup(name); if (!device->name) { - SDL_free(device); + FreePhysicalAudioDevice(device); return NULL; } + if (container_id) { + device->container_id = SDL_strdup(container_id); + if (!device->container_id) { + FreePhysicalAudioDevice(device); + return NULL; + } + } + if (unique_id) { device->unique_id = SDL_strdup(unique_id); if (!device->unique_id) { - SDL_free(device->name); - SDL_free(device); + FreePhysicalAudioDevice(device); return NULL; } } device->lock = SDL_CreateMutex(); if (!device->lock) { - SDL_free(device->unique_id); - SDL_free(device->name); - SDL_free(device); + FreePhysicalAudioDevice(device); return NULL; } device->close_cond = SDL_CreateCondition(); if (!device->close_cond) { - SDL_DestroyMutex(device->lock); - SDL_free(device->unique_id); - SDL_free(device->name); - SDL_free(device); + FreePhysicalAudioDevice(device); return NULL; } @@ -705,33 +713,29 @@ static SDL_AudioDevice *CreatePhysicalAudioDevice(const char *name, const char * SDL_LockRWLockForWriting(current_audio.subsystem_rwlock); if (SDL_InsertIntoHashTable(current_audio.device_hash_physical, (const void *) (uintptr_t) device->instance_id, device, false)) { SDL_AddAtomicInt(device_count, 1); + RefPhysicalAudioDevice(device); // unref'd on device disconnect. } else { - SDL_DestroyCondition(device->close_cond); - SDL_DestroyMutex(device->lock); - SDL_free(device->unique_id); - SDL_free(device->name); - SDL_free(device); + FreePhysicalAudioDevice(device); device = NULL; } SDL_UnlockRWLock(current_audio.subsystem_rwlock); - RefPhysicalAudioDevice(device); // unref'd on device disconnect. return device; } -static SDL_AudioDevice *CreateAudioRecordingDevice(const char *name, const char *unique_id, const SDL_AudioSpec *spec, void *handle) +static SDL_AudioDevice *CreateAudioRecordingDevice(const char *name, const char *container_id, const char *unique_id, const SDL_AudioSpec *spec, void *handle) { SDL_assert(current_audio.impl.HasRecordingSupport); - return CreatePhysicalAudioDevice(name, unique_id, true, spec, handle, ¤t_audio.recording_device_count); + return CreatePhysicalAudioDevice(name, container_id, unique_id, true, spec, handle, ¤t_audio.recording_device_count); } -static SDL_AudioDevice *CreateAudioPlaybackDevice(const char *name, const char *unique_id, const SDL_AudioSpec *spec, void *handle) +static SDL_AudioDevice *CreateAudioPlaybackDevice(const char *name, const char *container_id, const char *unique_id, const SDL_AudioSpec *spec, void *handle) { - return CreatePhysicalAudioDevice(name, unique_id, false, spec, handle, ¤t_audio.playback_device_count); + return CreatePhysicalAudioDevice(name, container_id, unique_id, false, spec, handle, ¤t_audio.playback_device_count); } // The audio backends call this when a new device is plugged in. -SDL_AudioDevice *SDL_AddAudioDevice(bool recording, const char *name, const char *unique_id, const SDL_AudioSpec *inspec, void *handle) +SDL_AudioDevice *SDL_AddAudioDevice(bool recording, const char *name, const char *container_id, const char *unique_id, const SDL_AudioSpec *inspec, void *handle) { // device handles MUST be unique! If the target reuses the same handle for hardware with both recording and playback interfaces, wrap it in a pointer you SDL_malloc'd! SDL_assert(SDL_FindPhysicalAudioDeviceByHandle(handle) == NULL); @@ -752,7 +756,7 @@ SDL_AudioDevice *SDL_AddAudioDevice(bool recording, const char *name, const char spec.freq = (inspec->freq != 0) ? inspec->freq : default_freq; } - SDL_AudioDevice *device = recording ? CreateAudioRecordingDevice(name, unique_id, &spec, handle) : CreateAudioPlaybackDevice(name, unique_id, &spec, handle); + SDL_AudioDevice *device = recording ? CreateAudioRecordingDevice(name, container_id, unique_id, &spec, handle) : CreateAudioPlaybackDevice(name, container_id, unique_id, &spec, handle); // Add a device add event to the pending list, to be pushed when the event queue is pumped (away from any of our internal threads). if (device) { @@ -900,9 +904,9 @@ static void SDL_AudioDetectDevices_Default(SDL_AudioDevice **default_playback, S SDL_assert(current_audio.impl.OnlyHasDefaultPlaybackDevice); SDL_assert(current_audio.impl.OnlyHasDefaultRecordingDevice || !current_audio.impl.HasRecordingSupport); - *default_playback = SDL_AddAudioDevice(false, DEFAULT_PLAYBACK_DEVNAME, NULL, NULL, (void *)((size_t)0x1)); + *default_playback = SDL_AddAudioDevice(false, DEFAULT_PLAYBACK_DEVNAME, NULL, NULL, NULL, (void *)((size_t)0x1)); if (current_audio.impl.HasRecordingSupport) { - *default_recording = SDL_AddAudioDevice(true, DEFAULT_RECORDING_DEVNAME, NULL, NULL, (void *)((size_t)0x2)); + *default_recording = SDL_AddAudioDevice(true, DEFAULT_RECORDING_DEVNAME, NULL, NULL, NULL, (void *)((size_t)0x2)); } } @@ -1722,6 +1726,9 @@ SDL_PropertiesID SDL_GetAudioDeviceProperties(SDL_AudioDeviceID devid) if (!props) { props = *propsptr = SDL_CreateProperties(); if (props != 0) { // fill in some basic properties. + if (device->container_id) { + SDL_SetStringProperty(props, SDL_PROP_AUDIO_DEVICE_CONTAINER_ID_STRING, device->container_id); + } SDL_SetStringProperty(props, SDL_PROP_AUDIO_DEVICE_UNIQUE_ID_STRING, device->unique_id); } } diff --git a/src/audio/SDL_audiodev.c b/src/audio/SDL_audiodev.c index 4a1a1cf21b..a7e9e037ec 100644 --- a/src/audio/SDL_audiodev.c +++ b/src/audio/SDL_audiodev.c @@ -63,7 +63,7 @@ static void test_device(const bool recording, const char *fname, int flags, bool * information, making this information inaccessible at * enumeration time */ - SDL_AddAudioDevice(recording, fname, NULL, NULL, (void *)(uintptr_t)dummyhandle); + SDL_AddAudioDevice(recording, fname, NULL, NULL, NULL, (void *)(uintptr_t)dummyhandle); } } else { close(audio_fd); diff --git a/src/audio/SDL_sysaudio.h b/src/audio/SDL_sysaudio.h index 934595cdac..53b020e6fc 100644 --- a/src/audio/SDL_sysaudio.h +++ b/src/audio/SDL_sysaudio.h @@ -71,7 +71,7 @@ extern void SDL_SetupAudioResampler(void); /* Backends should call this as devices are added to the system (such as a USB headset being plugged in), and should also be called for for every device found during DetectDevices(). */ -extern SDL_AudioDevice *SDL_AddAudioDevice(bool recording, const char *name, const char *unique_id, const SDL_AudioSpec *spec, void *handle); +extern SDL_AudioDevice *SDL_AddAudioDevice(bool recording, const char *name, const char *container_id, const char *unique_id, const SDL_AudioSpec *spec, void *handle); /* Backends should call this if an opened audio device is lost. This can happen due to i/o errors, or a device being unplugged, etc. */ @@ -306,6 +306,9 @@ struct SDL_AudioDevice // human-readable name of the device. ("SoundBlaster Pro 16") char *name; + // the container ID of this device, used to match associated controllers or other devices, optional. + char *container_id; + // unique, platform-specific, backend-specific string to identify this specific device. // It needs to survive between runs of the program, but ideally it survives reboots and // device disconnect/reconnect, if possible. If it can't be provided, leave this NULL. diff --git a/src/audio/alsa/SDL_alsa_audio.c b/src/audio/alsa/SDL_alsa_audio.c index f229bc085f..50ac39d754 100644 --- a/src/audio/alsa/SDL_alsa_audio.c +++ b/src/audio/alsa/SDL_alsa_audio.c @@ -38,6 +38,9 @@ #include "../SDL_sysaudio.h" #include "SDL_alsa_audio.h" +#ifdef SDL_PLATFORM_LINUX +#include "../../core/linux/SDL_sysfs.h" +#endif #include "../../core/linux/SDL_udev.h" #if SDL_ALSA_DEBUG @@ -107,6 +110,7 @@ static const char *(*ALSA_snd_ctl_card_info_get_id)(const snd_ctl_card_info_t *) static const char *(*ALSA_snd_pcm_info_get_name)(const snd_pcm_info_t *); static const char *(*ALSA_snd_pcm_info_get_subdevice_name)(const snd_pcm_info_t *); static const char *(*ALSA_snd_ctl_card_info_get_name)(const snd_ctl_card_info_t *); +static int (*ALSA_snd_ctl_card_info_get_card)(const snd_ctl_card_info_t *); static void (*ALSA_snd_ctl_card_info_clear)(snd_ctl_card_info_t *); static int (*ALSA_snd_pcm_hw_free)(snd_pcm_t *); static int (*ALSA_snd_pcm_hw_params_set_channels_near)(snd_pcm_t *, snd_pcm_hw_params_t *, unsigned int *); @@ -202,6 +206,7 @@ static bool load_alsa_syms(void) SDL_ALSA_SYM(snd_pcm_info_get_name); SDL_ALSA_SYM(snd_pcm_info_get_subdevice_name); SDL_ALSA_SYM(snd_ctl_card_info_get_name); + SDL_ALSA_SYM(snd_ctl_card_info_get_card); SDL_ALSA_SYM(snd_ctl_card_info_clear); SDL_ALSA_SYM(snd_pcm_hw_free); SDL_ALSA_SYM(snd_pcm_hw_params_set_channels_near); @@ -1364,7 +1369,14 @@ static int hotplug_device_process(snd_ctl_t *ctl, snd_ctl_card_info_t *ctl_card_ adev->device_index = dev_idx; adev->recording = (direction == SND_PCM_STREAM_CAPTURE); - if (SDL_AddAudioDevice(recording, adev->name, NULL, NULL, adev) == NULL) { + char *container_id = NULL; +#ifdef SDL_PLATFORM_LINUX + container_id = SDL_GetContainerIDFromALSACard(ALSA_snd_ctl_card_info_get_card(ctl_card_info)); +#endif + SDL_AudioDevice *device = SDL_AddAudioDevice(recording, adev->name, container_id, NULL, NULL, adev); + SDL_free(container_id); + + if (device == NULL) { SDL_small_free(pcm_info, isstack); SDL_free(adev->id); SDL_free(adev->name); @@ -1592,10 +1604,10 @@ static void ALSA_DetectDevices(SDL_AudioDevice **default_playback, SDL_AudioDevi bool has_default_playback = false, has_default_recording = false; ALSA_HotplugIteration(&has_default_playback, &has_default_recording); // run once now before a thread continues to check. if (has_default_playback) { - *default_playback = SDL_AddAudioDevice(/*recording=*/false, "ALSA default playback device", NULL, NULL, (void *)&default_playback_handle); + *default_playback = SDL_AddAudioDevice(/*recording=*/false, "ALSA default playback device", NULL, NULL, NULL, (void *)&default_playback_handle); } if (has_default_recording) { - *default_recording = SDL_AddAudioDevice(/*recording=*/true, "ALSA default recording device", NULL, NULL, (void *)&default_recording_handle); + *default_recording = SDL_AddAudioDevice(/*recording=*/true, "ALSA default recording device", NULL, NULL, NULL, (void *)&default_recording_handle); } if (!ALSA_start_udev()) { diff --git a/src/audio/coreaudio/SDL_coreaudio.m b/src/audio/coreaudio/SDL_coreaudio.m index c9f0c31f37..38d0126643 100644 --- a/src/audio/coreaudio/SDL_coreaudio.m +++ b/src/audio/coreaudio/SDL_coreaudio.m @@ -146,6 +146,40 @@ static char *GetAudioDeviceStringProperty(AudioDeviceID dev, const AudioObjectPr return retval; } +// Apple's USB audio driver includes the USB location ID in the device UID, e.g. +// "AppleUSBAudioEngine:Sony Interactive Entertainment:Wireless Controller:2120000:1" +// We use that as the container ID, so audio devices can be matched with USB controllers. +static char *GetContainerIDFromUID(const char *unique_id) +{ + char *result = NULL; + + if (!unique_id || SDL_strncmp(unique_id, "AppleUSBAudioEngine:", 20) != 0) { + return NULL; + } + + // The location ID is the second to last field + const char *end = SDL_strrchr(unique_id, ':'); + if (!end) { + return NULL; + } + const char *start = end; + while (start > unique_id && start[-1] != ':') { + --start; + } + if (start == unique_id) { + return NULL; + } + + Uint32 location_id = (Uint32)SDL_strtoul(start, NULL, 16); + if (location_id == 0) { + return NULL; + } + + // This needs to match the format used by SDL_GetContainerIDFromRegistryEntryID() + SDL_asprintf(&result, "0x%08" SDL_PRIx32, location_id); + return result; +} + // This only _adds_ new devices. Removal is handled by devices triggering kAudioDevicePropertyDeviceIsAlive property changes. static void RefreshPhysicalDevices(void) @@ -244,7 +278,9 @@ static void RefreshPhysicalDevices(void) if (newhandle) { newhandle->devid = dev; newhandle->recording = recording ? true : false; - SDL_AudioDevice *device = SDL_AddAudioDevice(newhandle->recording, name ? name : "Unnamed audio device", unique_id, &spec, newhandle); + char *container_id = GetContainerIDFromUID(unique_id); + SDL_AudioDevice *device = SDL_AddAudioDevice(newhandle->recording, name ? name : "Unnamed audio device", container_id, unique_id, &spec, newhandle); + SDL_free(container_id); if (device) { AudioObjectAddPropertyListener(dev, &alive_address, DeviceAliveNotification, device); } else { diff --git a/src/audio/directsound/SDL_directsound.c b/src/audio/directsound/SDL_directsound.c index 9e13574713..6973e606a6 100644 --- a/src/audio/directsound/SDL_directsound.c +++ b/src/audio/directsound/SDL_directsound.c @@ -188,7 +188,7 @@ static BOOL CALLBACK FindAllDevs(LPGUID guid, LPCWSTR desc, LPCWSTR module, LPVO // Note that spec is NULL, because we are required to connect to the // device before getting the channel mask and output format, making // this information inaccessible at enumeration time - SDL_AudioDevice *device = SDL_AddAudioDevice(data->recording, str, NULL, NULL, cpyguid); + SDL_AudioDevice *device = SDL_AddAudioDevice(data->recording, str, NULL, NULL, NULL, cpyguid); if (device && data->default_device && data->default_device_guid) { if (SDL_memcmp(cpyguid, data->default_device_guid, sizeof (GUID)) == 0) { *data->default_device = device; diff --git a/src/audio/disk/SDL_diskaudio.c b/src/audio/disk/SDL_diskaudio.c index 6a58ac860d..2926befe81 100644 --- a/src/audio/disk/SDL_diskaudio.c +++ b/src/audio/disk/SDL_diskaudio.c @@ -155,8 +155,8 @@ static bool DISKAUDIO_OpenDevice(SDL_AudioDevice *device) static void DISKAUDIO_DetectDevices(SDL_AudioDevice **default_playback, SDL_AudioDevice **default_recording) { - *default_playback = SDL_AddAudioDevice(false, DEFAULT_PLAYBACK_DEVNAME, NULL, NULL, (void *)0x1); - *default_recording = SDL_AddAudioDevice(true, DEFAULT_RECORDING_DEVNAME, NULL, NULL, (void *)0x2); + *default_playback = SDL_AddAudioDevice(false, DEFAULT_PLAYBACK_DEVNAME, NULL, NULL, NULL, (void *)0x1); + *default_recording = SDL_AddAudioDevice(true, DEFAULT_RECORDING_DEVNAME, NULL, NULL, NULL, (void *)0x2); } static bool DISKAUDIO_Init(SDL_AudioDriverImpl *impl) diff --git a/src/audio/pipewire/SDL_pipewire.c b/src/audio/pipewire/SDL_pipewire.c index 901e8eb6f8..4d7a4b963a 100644 --- a/src/audio/pipewire/SDL_pipewire.c +++ b/src/audio/pipewire/SDL_pipewire.c @@ -24,6 +24,9 @@ #ifdef SDL_AUDIO_DRIVER_PIPEWIRE #include "SDL_pipewire.h" +#ifdef SDL_PLATFORM_LINUX +#include "../../core/linux/SDL_sysfs.h" +#endif #include #include @@ -240,6 +243,7 @@ struct io_node Uint32 id; bool recording; SDL_AudioSpec spec; + int alsa_card; // ALSA card number, or -1 if unknown const char *name; // Friendly name const char *path; // OS identifier (i.e. ALSA endpoint) @@ -275,6 +279,17 @@ static bool pipewire_core_version_at_least(int major, int minor, int patch) (pipewire_version_major > major || pipewire_version_minor > minor || pipewire_version_patch >= patch); } +static SDL_AudioDevice *AddPipewireAudioDevice(struct io_node *node) +{ + char *container_id = NULL; +#ifdef SDL_PLATFORM_LINUX + container_id = SDL_GetContainerIDFromALSACard(node->alsa_card); +#endif + SDL_AudioDevice *device = SDL_AddAudioDevice(node->recording, node->name, container_id, NULL, &node->spec, PW_ID_TO_HANDLE(node->id)); + SDL_free(container_id); + return device; +} + // The active node list static bool io_list_check_add(struct io_node *node) { @@ -291,7 +306,7 @@ static bool io_list_check_add(struct io_node *node) spa_list_append(&hotplug_io_list, &node->link); if (hotplug_events_enabled) { - SDL_AudioDevice *device = SDL_AddAudioDevice(node->recording, node->name, NULL, &node->spec, PW_ID_TO_HANDLE(node->id)); + SDL_AudioDevice *device = AddPipewireAudioDevice(node); const char *default_path = node->recording ? pipewire_default_source_id : pipewire_default_sink_id; if (default_path && SDL_strcmp(node->path, default_path) == 0) { SDL_DefaultAudioDeviceChanged(device); @@ -561,6 +576,14 @@ static void node_event_info(void *object, const struct pw_node_info *info) io->spec.channels = (Uint8)SDL_atoi(prop_val); } + prop_val = spa_dict_lookup(info->props, "api.alsa.card"); + if (!prop_val) { + prop_val = spa_dict_lookup(info->props, "alsa.card"); + } + if (prop_val) { + io->alsa_card = SDL_atoi(prop_val); + } + // Need to parse the parameters to get the sample rate for (i = 0; i < info->n_params; ++i) { pw_node_enum_params((struct pw_node *)node->proxy, 0, info->params[i].id, 0, 0, NULL); @@ -740,6 +763,7 @@ static void registry_event_global_callback(void *object, uint32_t id, uint32_t p // Begin setting the node properties io->id = id; io->recording = recording; + io->alsa_card = -1; if (io->spec.format == SDL_AUDIO_UNKNOWN) { io->spec.format = SDL_AUDIO_S16; // we'll go conservative here if for some reason the format isn't known. } @@ -880,7 +904,7 @@ static void PIPEWIRE_DetectDevices(SDL_AudioDevice **default_playback, SDL_Audio } spa_list_for_each (io, &hotplug_io_list, link) { - SDL_AudioDevice *device = SDL_AddAudioDevice(io->recording, io->name, NULL, &io->spec, PW_ID_TO_HANDLE(io->id)); + SDL_AudioDevice *device = AddPipewireAudioDevice(io); if (pipewire_default_sink_id && SDL_strcmp(io->path, pipewire_default_sink_id) == 0) { if (!io->recording) { *default_playback = device; diff --git a/src/audio/pulseaudio/SDL_pulseaudio.c b/src/audio/pulseaudio/SDL_pulseaudio.c index 38e5d0a0f4..77681db778 100644 --- a/src/audio/pulseaudio/SDL_pulseaudio.c +++ b/src/audio/pulseaudio/SDL_pulseaudio.c @@ -34,6 +34,9 @@ #include "../SDL_sysaudio.h" #include "SDL_pulseaudio.h" #include "../../thread/SDL_systhread.h" +#ifdef SDL_PLATFORM_LINUX +#include "../../core/linux/SDL_sysfs.h" +#endif #if (PA_PROTOCOL_VERSION < 28) typedef void (*pa_operation_notify_cb_t) (pa_operation *o, void *userdata); @@ -69,6 +72,7 @@ static const char *(*PULSEAUDIO_pa_strerror)(int); static pa_proplist *(*PULSEAUDIO_pa_proplist_new)(void); static void (*PULSEAUDIO_pa_proplist_free)(pa_proplist *); static int (*PULSEAUDIO_pa_proplist_sets)(pa_proplist *, const char *, const char *); +static const char *(*PULSEAUDIO_pa_proplist_gets)(const pa_proplist *, const char *); static pa_threaded_mainloop *(*PULSEAUDIO_pa_threaded_mainloop_new)(void); static void (*PULSEAUDIO_pa_threaded_mainloop_set_name)(pa_threaded_mainloop *, const char *); @@ -252,6 +256,7 @@ static bool load_pulseaudio_syms(void) SDL_PULSEAUDIO_SYM(pa_proplist_new); SDL_PULSEAUDIO_SYM(pa_proplist_free); SDL_PULSEAUDIO_SYM(pa_proplist_sets); + SDL_PULSEAUDIO_SYM(pa_proplist_gets); // optional #ifdef SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC @@ -840,10 +845,17 @@ static SDL_AudioFormat PulseFormatToSDLFormat(pa_sample_format_t format) } } -static void AddPulseAudioDevice(const bool recording, const char *description, const char *name, const uint32_t index, const pa_sample_spec *sample_spec) +static void AddPulseAudioDevice(const bool recording, const char *description, const char *name, const uint32_t index, const pa_sample_spec *sample_spec, const pa_proplist *proplist) { SDL_AudioSpec spec; + char *container_id = NULL; SDL_zero(spec); +#ifdef SDL_PLATFORM_LINUX + const char *card = PULSEAUDIO_pa_proplist_gets(proplist, "alsa.card"); + if (card) { + container_id = SDL_GetContainerIDFromALSACard(SDL_atoi(card)); + } +#endif spec.format = PulseFormatToSDLFormat(sample_spec->format); spec.channels = sample_spec->channels; spec.freq = sample_spec->rate; @@ -854,16 +866,17 @@ static void AddPulseAudioDevice(const bool recording, const char *description, c SDL_free(handle); } else { handle->device_index = index; - SDL_AddAudioDevice(recording, description, NULL, &spec, handle); + SDL_AddAudioDevice(recording, description, container_id, NULL, &spec, handle); } } + SDL_free(container_id); } // This is called when PulseAudio adds an playback ("sink") device. static void SinkInfoCallback(pa_context *c, const pa_sink_info *i, int is_last, void *data) { if (i) { - AddPulseAudioDevice(false, i->description, i->name, i->index, &i->sample_spec); + AddPulseAudioDevice(false, i->description, i->name, i->index, &i->sample_spec, i->proplist); } PULSEAUDIO_pa_threaded_mainloop_signal(pulseaudio_threaded_mainloop, 0); } @@ -873,7 +886,7 @@ static void SourceInfoCallback(pa_context *c, const pa_source_info *i, int is_la { // Maybe skip "monitor" sources. These are just output from other sinks. if (i && (include_monitors || (i->monitor_of_sink == PA_INVALID_INDEX))) { - AddPulseAudioDevice(true, i->description, i->name, i->index, &i->sample_spec); + AddPulseAudioDevice(true, i->description, i->name, i->index, &i->sample_spec, i->proplist); } PULSEAUDIO_pa_threaded_mainloop_signal(pulseaudio_threaded_mainloop, 0); } diff --git a/src/audio/qnx/SDL_qsa_audio.c b/src/audio/qnx/SDL_qsa_audio.c index a43e44dc56..8da12c8e10 100644 --- a/src/audio/qnx/SDL_qsa_audio.c +++ b/src/audio/qnx/SDL_qsa_audio.c @@ -383,7 +383,7 @@ static void QSA_DetectDevices(SDL_AudioDevice **default_playback, SDL_AudioDevic SDL_assert(card <= 0xFFFF); SDL_assert(deviceno <= 0xFFFF); const Uint32 sdlhandle = ((Uint32) card) | (((Uint32) deviceno) << 16); - SDL_AddAudioDevice(recording, fullname, NULL, pspec, (void *) ((size_t) sdlhandle)); + SDL_AddAudioDevice(recording, fullname, NULL, NULL, pspec, (void *) ((size_t) sdlhandle)); } } else { // Check if we got end of devices list diff --git a/src/audio/sndio/SDL_sndioaudio.c b/src/audio/sndio/SDL_sndioaudio.c index 81545bfcb2..59ec435e08 100644 --- a/src/audio/sndio/SDL_sndioaudio.c +++ b/src/audio/sndio/SDL_sndioaudio.c @@ -331,8 +331,8 @@ static void SNDIO_Deinitialize(void) static void SNDIO_DetectDevices(SDL_AudioDevice **default_playback, SDL_AudioDevice **default_recording) { // !!! FIXME: shouldn't we just use OnlyHasDefaultPlaybackDevice/OnlyHasDefaultRecordingDevice? - *default_playback = SDL_AddAudioDevice(false, DEFAULT_PLAYBACK_DEVNAME, NULL, NULL, (void *)0x1); - *default_recording = SDL_AddAudioDevice(true, DEFAULT_RECORDING_DEVNAME, NULL, NULL, (void *)0x2); + *default_playback = SDL_AddAudioDevice(false, DEFAULT_PLAYBACK_DEVNAME, NULL, NULL, NULL, (void *)0x1); + *default_recording = SDL_AddAudioDevice(true, DEFAULT_RECORDING_DEVNAME, NULL, NULL, NULL, (void *)0x2); } static bool SNDIO_Init(SDL_AudioDriverImpl *impl) diff --git a/src/core/android/SDL_android.c b/src/core/android/SDL_android.c index e8f88cbd0e..fcc15ae165 100644 --- a/src/core/android/SDL_android.c +++ b/src/core/android/SDL_android.c @@ -825,7 +825,7 @@ JNIEXPORT void JNICALL SDL_JAVA_AUDIO_INTERFACE(nativeAddAudioDevice)(JNIEnv *en void *handle = (void *)((size_t)device_id); if (!SDL_FindPhysicalAudioDeviceByHandle(handle)) { const char *utf8name = (*env)->GetStringUTFChars(env, name, NULL); - SDL_AddAudioDevice(recording, SDL_strdup(utf8name), NULL, NULL, handle); + SDL_AddAudioDevice(recording, utf8name, NULL, NULL, NULL, handle); (*env)->ReleaseStringUTFChars(env, name, utf8name); } } diff --git a/src/core/linux/SDL_sysfs.c b/src/core/linux/SDL_sysfs.c new file mode 100644 index 0000000000..2d62625189 --- /dev/null +++ b/src/core/linux/SDL_sysfs.c @@ -0,0 +1,101 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2026 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifdef SDL_PLATFORM_LINUX + +#include "SDL_sysfs.h" + +#include +#include +#include +#include +#include + + +static bool IsUSBDevice(const char *syspath) +{ + // USB devices have a bus number, USB interfaces don't + char path[PATH_MAX]; + if (SDL_snprintf(path, sizeof(path), "%s/busnum", syspath) >= (int)sizeof(path)) { + return false; + } + return access(path, F_OK) == 0; +} + +// The container ID is the directory in /sys/devices that corresponds to the USB device, if available +static char *GetContainerIDFromSysfsPath(const char *syspath) +{ + char path[PATH_MAX]; + + if (!realpath(syspath, path)) { + return NULL; + } + + // Only physical devices have a container, and for Bluetooth devices + // the first USB device above them is the Bluetooth adapter. + const char *devices_root = "/sys/devices/"; + if (!SDL_startswith(path, devices_root) || + SDL_startswith(path, "/sys/devices/virtual/") || + SDL_strstr(path, "/bluetooth/") != NULL) { + return NULL; + } + + // Walk back up to the USB device containing this path + const char *base = path + SDL_strlen(devices_root); + while (!IsUSBDevice(path)) { + char *slash = SDL_strrchr(path, '/'); + if (!slash || slash <= base) { + return NULL; + } + *slash = '\0'; + } + + // The sysfs path of the USB device is shared by all of its interfaces + return SDL_strdup(path); +} + +char *SDL_GetContainerIDFromDevicePath(const char *devpath) +{ + struct stat sb; + char syspath[64]; + + if (!devpath || stat(devpath, &sb) < 0 || !S_ISCHR(sb.st_mode)) { + return NULL; + } + + (void)SDL_snprintf(syspath, sizeof(syspath), "/sys/dev/char/%u:%u", major(sb.st_rdev), minor(sb.st_rdev)); + return GetContainerIDFromSysfsPath(syspath); +} + +char *SDL_GetContainerIDFromALSACard(int card) +{ + char syspath[64]; + + if (card < 0) { + return NULL; + } + + (void)SDL_snprintf(syspath, sizeof(syspath), "/sys/class/sound/card%d", card); + return GetContainerIDFromSysfsPath(syspath); +} + +#endif // SDL_PLATFORM_LINUX diff --git a/src/core/linux/SDL_sysfs.h b/src/core/linux/SDL_sysfs.h new file mode 100644 index 0000000000..a512303e86 --- /dev/null +++ b/src/core/linux/SDL_sysfs.h @@ -0,0 +1,32 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2026 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_sysfs_h_ +#define SDL_sysfs_h_ + +// Get a container ID for a character device node, e.g. /dev/input/event3 or /dev/hidraw2 +extern char *SDL_GetContainerIDFromDevicePath(const char *devpath); + +// Get a container ID for an ALSA sound card +extern char *SDL_GetContainerIDFromALSACard(int card); + +#endif // SDL_sysfs_h_ diff --git a/src/core/macos/SDL_ioreg.c b/src/core/macos/SDL_ioreg.c new file mode 100644 index 0000000000..0379f53c2a --- /dev/null +++ b/src/core/macos/SDL_ioreg.c @@ -0,0 +1,83 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2026 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#include "SDL_ioreg.h" + +#include +#include +#include + + +static char *GetContainerIDFromProperties(CFTypeRef transport, CFTypeRef location) +{ + char *result = NULL; + + // Only USB devices can be matched with audio devices + if (!transport || CFGetTypeID(transport) != CFStringGetTypeID() || + CFStringCompare((CFStringRef)transport, CFSTR(kIOHIDTransportUSBValue), 0) != kCFCompareEqualTo) { + return NULL; + } + + Uint32 location_id = 0; + if (!location || CFGetTypeID(location) != CFNumberGetTypeID() || + !CFNumberGetValue((CFNumberRef)location, kCFNumberSInt32Type, &location_id) || + location_id == 0) { + return NULL; + } + + // This needs to match the format used in SDL_coreaudio.m + SDL_asprintf(&result, "0x%08" SDL_PRIx32, location_id); + return result; +} + +char *SDL_GetContainerIDFromRegistryEntryID(Uint64 entry_id) +{ + char *result = NULL; + + io_service_t service = IOServiceGetMatchingService(0, IORegistryEntryIDMatching(entry_id)); + if (service == MACH_PORT_NULL) { + return NULL; + } + + CFTypeRef transport = IORegistryEntryCreateCFProperty(service, CFSTR(kIOHIDTransportKey), kCFAllocatorDefault, 0); + if (transport) { + CFTypeRef location = IORegistryEntryCreateCFProperty(service, CFSTR(kIOHIDLocationIDKey), kCFAllocatorDefault, 0); + if (location) { + result = GetContainerIDFromProperties(transport, location); + CFRelease(location); + } + CFRelease(transport); + } + IOObjectRelease(service); + + return result; +} + +char *SDL_GetContainerIDFromHIDDevice(IOHIDDeviceRef device) +{ + if (!device) { + return NULL; + } + + return GetContainerIDFromProperties(IOHIDDeviceGetProperty(device, CFSTR(kIOHIDTransportKey)), + IOHIDDeviceGetProperty(device, CFSTR(kIOHIDLocationIDKey))); +} diff --git a/src/core/macos/SDL_ioreg.h b/src/core/macos/SDL_ioreg.h new file mode 100644 index 0000000000..ba93f90cc8 --- /dev/null +++ b/src/core/macos/SDL_ioreg.h @@ -0,0 +1,34 @@ +/* + Simple DirectMedia Layer + Copyright (C) 1997-2026 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ +#include "SDL_internal.h" + +#ifndef SDL_ioreg_h_ +#define SDL_ioreg_h_ + +#include + +// Function to return the container ID of a USB device in the IOKit registry, or NULL if not available +extern char *SDL_GetContainerIDFromRegistryEntryID(Uint64 entry_id); + +// Function to return the container ID of a USB HID device, or NULL if not available +extern char *SDL_GetContainerIDFromHIDDevice(IOHIDDeviceRef device); + +#endif // SDL_ioreg_h_ diff --git a/src/core/windows/SDL_hid.c b/src/core/windows/SDL_hid.c index 79739885c5..9990ab5e8e 100644 --- a/src/core/windows/SDL_hid.c +++ b/src/core/windows/SDL_hid.c @@ -82,8 +82,31 @@ void WIN_UnloadHIDDLL(void) } } +char *WIN_GetContainerIDString(const GUID *container_id) +{ + static const GUID NULL_CONTAINER_ID = { 0x00000000L, 0x0000, 0x0000, { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } }; + static const GUID SYSTEM_CONTAINER_ID = { 0x00000000L, 0x0000, 0x0000, { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } }; + char *result = NULL; + + // Devices that are part of the computer all share the system container ID, + // so it can't be used to find associated devices. + if (SDL_memcmp(container_id, &NULL_CONTAINER_ID, sizeof(*container_id)) == 0 || + SDL_memcmp(container_id, &SYSTEM_CONTAINER_ID, sizeof(*container_id)) == 0) { + return NULL; + } + + // Use the same format that Windows uses, e.g. {24555b7b-4ecc-11f1-bc07-4c233802a1fc} + SDL_asprintf(&result, "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", + (unsigned long)container_id->Data1, container_id->Data2, container_id->Data3, + container_id->Data4[0], container_id->Data4[1], container_id->Data4[2], container_id->Data4[3], + container_id->Data4[4], container_id->Data4[5], container_id->Data4[6], container_id->Data4[7]); + return result; +} + #if !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES) +#include + // CM_Register_Notification definitions #define CR_SUCCESS 0x00 @@ -169,17 +192,28 @@ typedef DWORD (WINAPI *CM_Register_NotificationFunc)(PCM_NOTIFY_FILTER pFilter, typedef DWORD (WINAPI *CM_Unregister_NotificationFunc)(HCMNOTIFICATION NotifyContext); typedef DWORD (WINAPI *CM_Get_Device_Interface_List_SizeWFunc)(PULONG pulLen, LPGUID InterfaceClassGuid, WCHAR *pDeviceID, ULONG ulFlags); typedef DWORD (WINAPI *CM_Get_Device_Interface_ListWFunc)(LPGUID InterfaceClassGuid, WCHAR *pDeviceID, WCHAR *Buffer, ULONG BufferLen, ULONG ulFlags); +typedef DWORD (WINAPI *CM_Get_Device_Interface_PropertyWFunc)(LPCWSTR pszDeviceInterface, const DEVPROPKEY *PropertyKey, DEVPROPTYPE *PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); +typedef DWORD (WINAPI *CM_Locate_DevNodeWFunc)(PDWORD pdnDevInst, WCHAR *pDeviceID, ULONG ulFlags); +typedef DWORD (WINAPI *CM_Get_DevNode_PropertyWFunc)(DWORD dnDevInst, const DEVPROPKEY *PropertyKey, DEVPROPTYPE *PropertyType, PBYTE PropertyBuffer, PULONG PropertyBufferSize, ULONG ulFlags); #define CM_NOTIFY_FILTER_FLAG_ALL_INTERFACE_CLASSES 0x00000001 #define CM_GET_DEVICE_INTERFACE_LIST_PRESENT 0x00000000 +#define CM_LOCATE_DEVNODE_NORMAL 0x00000000 + +#define MAX_DEVICE_ID_LEN 200 static GUID GUID_DEVINTERFACE_HID = { 0x4D1E55B2L, 0xF16F, 0x11CF, { 0x88, 0xCB, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30 } }; +static const DEVPROPKEY SDL_DEVPKEY_Device_InstanceId = { { 0x78c34fc8, 0x104a, 0x4aca, { 0x9e, 0xa4, 0x52, 0x4d, 0x52, 0x99, 0x6e, 0x57 } }, 256 }; +static const DEVPROPKEY SDL_DEVPKEY_Device_ContainerId = { { 0x8c7ed206, 0x3f8a, 0x4827, { 0xb3, 0xab, 0xae, 0x9e, 0x1f, 0xae, 0xfc, 0x6c } }, 2 }; static SDL_InitState SDL_cfgmgr32_init; static CM_Register_NotificationFunc SDL_CM_Register_Notification; static CM_Unregister_NotificationFunc SDL_CM_Unregister_Notification; static CM_Get_Device_Interface_List_SizeWFunc SDL_CM_Get_Device_Interface_List_SizeW; static CM_Get_Device_Interface_ListWFunc SDL_CM_Get_Device_Interface_ListW; +static CM_Get_Device_Interface_PropertyWFunc SDL_CM_Get_Device_Interface_PropertyW; +static CM_Locate_DevNodeWFunc SDL_CM_Locate_DevNodeW; +static CM_Get_DevNode_PropertyWFunc SDL_CM_Get_DevNode_PropertyW; static int s_DeviceNotificationsRequested; static HCMNOTIFICATION s_DeviceNotificationFuncHandle; @@ -190,25 +224,28 @@ static SDL_Thread *s_HotplugThread; static bool WIN_LoadCfgMgr32(void) { + static HMODULE cfgmgr32; + if (SDL_ShouldInit(&SDL_cfgmgr32_init)) { // We'll keep this loaded for future use - HMODULE cfgmgr32 = LoadLibraryA("cfgmgr32.dll"); + cfgmgr32 = LoadLibraryA("cfgmgr32.dll"); if (cfgmgr32) { SDL_CM_Register_Notification = (CM_Register_NotificationFunc)GetProcAddress(cfgmgr32, "CM_Register_Notification"); SDL_CM_Unregister_Notification = (CM_Unregister_NotificationFunc)GetProcAddress(cfgmgr32, "CM_Unregister_Notification"); SDL_CM_Get_Device_Interface_List_SizeW = (CM_Get_Device_Interface_List_SizeWFunc)GetProcAddress(cfgmgr32, "CM_Get_Device_Interface_List_SizeW"); SDL_CM_Get_Device_Interface_ListW = (CM_Get_Device_Interface_ListWFunc)GetProcAddress(cfgmgr32, "CM_Get_Device_Interface_ListW"); + SDL_CM_Get_Device_Interface_PropertyW = (CM_Get_Device_Interface_PropertyWFunc)GetProcAddress(cfgmgr32, "CM_Get_Device_Interface_PropertyW"); + SDL_CM_Locate_DevNodeW = (CM_Locate_DevNodeWFunc)GetProcAddress(cfgmgr32, "CM_Locate_DevNodeW"); + SDL_CM_Get_DevNode_PropertyW = (CM_Get_DevNode_PropertyWFunc)GetProcAddress(cfgmgr32, "CM_Get_DevNode_PropertyW"); } SDL_SetInitialized(&SDL_cfgmgr32_init, true); } - if (!SDL_CM_Register_Notification || - !SDL_CM_Unregister_Notification || - !SDL_CM_Get_Device_Interface_List_SizeW || - !SDL_CM_Get_Device_Interface_ListW) { + if (cfgmgr32) { + return true; + } else { return false; } - return true; } #ifdef SDL_VIDEO_DRIVER_WINDOWS @@ -256,16 +293,18 @@ void WIN_InitDeviceNotification(void) s_HotplugEvent = CreateEvent(NULL, FALSE, FALSE, NULL); s_HotplugThread = SDL_CreateThread(DeviceHotplugThread, "DeviceHotplugThread", NULL); - if (WIN_LoadCfgMgr32()) { - CM_NOTIFY_FILTER notify_filter; + if (!WIN_LoadCfgMgr32() || !SDL_CM_Register_Notification) { + return; + } - SDL_zero(notify_filter); - notify_filter.cbSize = sizeof(notify_filter); - notify_filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE; - notify_filter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_HID; - if (SDL_CM_Register_Notification(¬ify_filter, NULL, SDL_DeviceNotificationFunc, &s_DeviceNotificationFuncHandle) == CR_SUCCESS) { - return; - } + CM_NOTIFY_FILTER notify_filter; + + SDL_zero(notify_filter); + notify_filter.cbSize = sizeof(notify_filter); + notify_filter.FilterType = CM_NOTIFY_FILTER_TYPE_DEVICEINTERFACE; + notify_filter.u.DeviceInterface.ClassGuid = GUID_DEVINTERFACE_HID; + if (SDL_CM_Register_Notification(¬ify_filter, NULL, SDL_DeviceNotificationFunc, &s_DeviceNotificationFuncHandle) == CR_SUCCESS) { + return; } // FIXME: Should we log errors? @@ -299,7 +338,7 @@ WIN_DeviceInterfaceNotification *WIN_RegisterDeviceInterfaceNotification(WIN_Dev WIN_DeviceInterfaceNotification *notification; CM_NOTIFY_FILTER notify_filter; - if (!WIN_LoadCfgMgr32()) { + if (!WIN_LoadCfgMgr32() || !SDL_CM_Register_Notification) { return NULL; } @@ -323,6 +362,10 @@ WIN_DeviceInterfaceNotification *WIN_RegisterDeviceInterfaceNotification(WIN_Dev void WIN_UnregisterDeviceInterfaceNotification(WIN_DeviceInterfaceNotification *notification) { + if (!SDL_CM_Unregister_Notification) { + return; + } + if (notification) { SDL_CM_Unregister_Notification(notification->handle); SDL_free(notification); @@ -355,7 +398,7 @@ WCHAR *WIN_GetHIDDeviceInterfaces(ULONG *length) ULONG len = 0; DWORD result; - if (!WIN_LoadCfgMgr32()) { + if (!WIN_LoadCfgMgr32() || !SDL_CM_Get_Device_Interface_List_SizeW || !SDL_CM_Get_Device_Interface_ListW) { *length = 0; return NULL; } @@ -385,6 +428,55 @@ WCHAR *WIN_GetHIDDeviceInterfaces(ULONG *length) } } +static char *GetContainerIDFromInstanceID(const WCHAR *instance_id) +{ + DWORD devinst = 0; + DEVPROPTYPE type = DEVPROP_TYPE_EMPTY; + GUID container_id; + ULONG size = sizeof(container_id); + + if (!WIN_LoadCfgMgr32() || !SDL_CM_Locate_DevNodeW || !SDL_CM_Get_DevNode_PropertyW) { + return NULL; + } + + if (SDL_CM_Locate_DevNodeW(&devinst, (WCHAR *)instance_id, CM_LOCATE_DEVNODE_NORMAL) != CR_SUCCESS) { + return NULL; + } + if (SDL_CM_Get_DevNode_PropertyW(devinst, &SDL_DEVPKEY_Device_ContainerId, &type, (PBYTE)&container_id, &size, 0) != CR_SUCCESS || + type != DEVPROP_TYPE_GUID) { + return NULL; + } + return WIN_GetContainerIDString(&container_id); +} + +char *WIN_GetContainerIDFromInterfacePath(const char *path) +{ + WCHAR instance_id[MAX_DEVICE_ID_LEN]; + ULONG size = sizeof(instance_id); + DEVPROPTYPE type = DEVPROP_TYPE_EMPTY; + DWORD result; + + if (!path) { + return NULL; + } + + if (!WIN_LoadCfgMgr32() || !SDL_CM_Get_Device_Interface_PropertyW) { + return NULL; + } + + WCHAR *wpath = WIN_UTF8ToStringW(path); + if (!wpath) { + return NULL; + } + result = SDL_CM_Get_Device_Interface_PropertyW(wpath, &SDL_DEVPKEY_Device_InstanceId, &type, (PBYTE)instance_id, &size, 0); + SDL_free(wpath); + + if (result != CR_SUCCESS || type != DEVPROP_TYPE_STRING) { + return NULL; + } + return GetContainerIDFromInstanceID(instance_id); +} + #else void WIN_InitDeviceNotification(void) @@ -415,4 +507,9 @@ WCHAR *WIN_GetHIDDeviceInterfaces(ULONG *length) return NULL; } +char *WIN_GetContainerIDFromInterfacePath(const char *path) +{ + return NULL; +} + #endif // !SDL_PLATFORM_XBOXONE && !SDL_PLATFORM_XBOXSERIES diff --git a/src/core/windows/SDL_hid.h b/src/core/windows/SDL_hid.h index ad5aac7b56..a6e53ca1ff 100644 --- a/src/core/windows/SDL_hid.h +++ b/src/core/windows/SDL_hid.h @@ -214,4 +214,10 @@ extern void WIN_QuitDeviceNotification(void); extern WCHAR *WIN_GetHIDDeviceInterfaces(ULONG *length); +// Format a container ID as a Windows GUID string +extern char *WIN_GetContainerIDString(const GUID *container_id); + +// Get the container ID for a device interface path, e.g. a HID device path +extern char *WIN_GetContainerIDFromInterfacePath(const char *path); + #endif // SDL_hid_h_ diff --git a/src/core/windows/SDL_immdevice.c b/src/core/windows/SDL_immdevice.c index 9e243eb209..b182490f1a 100644 --- a/src/core/windows/SDL_immdevice.c +++ b/src/core/windows/SDL_immdevice.c @@ -23,6 +23,7 @@ #if defined(SDL_PLATFORM_WINDOWS) && defined(HAVE_MMDEVICEAPI_H) #include "SDL_windows.h" +#include "SDL_hid.h" #include "SDL_immdevice.h" #include "../../audio/SDL_sysaudio.h" #include // For CLSIDFromString @@ -55,6 +56,7 @@ static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, static const PROPERTYKEY SDL_PKEY_AudioEngine_DeviceFormat = { { 0xf19f064d, 0x82c, 0x4e27,{ 0xbc, 0x73, 0x68, 0x82, 0xa1, 0xbb, 0x8e, 0x4c, } }, 0 }; static const PROPERTYKEY SDL_PKEY_AudioEndpoint_GUID = { { 0x1da5d803, 0xd492, 0x4edd,{ 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, } }, 4 }; static const PROPERTYKEY SDL_PKEY_AudioEndpoint_StableId = { { 0x1da5d803, 0xd492, 0x4edd,{ 0x8c, 0x23, 0xe0, 0xc0, 0xff, 0xee, 0x7f, 0x0e, } }, 12 }; +static const PROPERTYKEY SDL_PKEY_Device_ContainerId = { { 0x8c7ed206, 0x3f8a, 0x4827,{ 0xb3, 0xab, 0xae, 0x9e, 0x1f, 0xae, 0xfc, 0x6c, } }, 2 }; /* *INDENT-ON* */ // clang-format on static bool FindByDevIDCallback(void *userdata, SDL_AudioDevice *device) @@ -84,7 +86,7 @@ LPCWSTR SDL_IMMDevice_GetDevID(SDL_AudioDevice *device) return (device && device->handle) ? ((const SDL_IMMDevice_HandleData *) device->handle)->immdevice_id : NULL; } -static void GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSIBLE *fmt, GUID *guid, char **unique_id) +static void GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSIBLE *fmt, GUID *guid, char **container_id, char **unique_id) { /* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be "SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in @@ -92,23 +94,35 @@ static void GetMMDeviceInfo(IMMDevice *device, char **utf8dev, WAVEFORMATEXTENSI LPWSTR devid = NULL; IPropertyStore *props = NULL; *utf8dev = NULL; - *unique_id = NULL; SDL_zerop(fmt); + SDL_zerop(guid); + *container_id = NULL; + *unique_id = NULL; + if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) { PROPVARIANT var; + PropVariantInit(&var); if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) { *utf8dev = WIN_StringToUTF8W(var.pwszVal); } + PropVariantClear(&var); if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEngine_DeviceFormat, &var))) { SDL_memcpy(fmt, var.blob.pBlobData, SDL_min(var.blob.cbSize, sizeof(WAVEFORMATEXTENSIBLE))); } + PropVariantClear(&var); if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEndpoint_GUID, &var))) { (void)CLSIDFromString(var.pwszVal, guid); } + PropVariantClear(&var); + if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_ContainerId, &var)) && + var.vt == VT_CLSID && var.puuid) { + *container_id = WIN_GetContainerIDString(var.puuid); + } + PropVariantClear(&var); if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_AudioEndpoint_StableId, &var)) && var.pwszVal) { // this was introduced in Windows 11, with stronger promises than IMMDevice_GetId(). *unique_id = WIN_StringToUTF8W(var.pwszVal); @@ -132,7 +146,7 @@ void SDL_IMMDevice_FreeDeviceHandle(SDL_AudioDevice *device) } } -static SDL_AudioDevice *SDL_IMMDevice_Add(const bool recording, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid, GUID *dsoundguid, const char *unique_id, SDL_AudioFormat force_format, bool supports_recording_playback_devices) +static SDL_AudioDevice *SDL_IMMDevice_Add(const bool recording, const char *devname, WAVEFORMATEXTENSIBLE *fmt, LPCWSTR devid, GUID *dsoundguid, const char *container_id, const char *unique_id, SDL_AudioFormat force_format, bool supports_recording_playback_devices) { /* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever). In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for @@ -176,7 +190,7 @@ static SDL_AudioDevice *SDL_IMMDevice_Add(const bool recording, const char *devn spec.freq = fmt->Format.nSamplesPerSec; spec.format = (force_format != SDL_AUDIO_UNKNOWN) ? force_format : SDL_WaveFormatExToSDLFormat((WAVEFORMATEX *)fmt); - device = SDL_AddAudioDevice(recording, devname, unique_id, &spec, handle); + device = SDL_AddAudioDevice(recording, devname, container_id, unique_id, &spec, handle); if (!recording && supports_recording_playback_devices) { // handle is freed by SDL_IMMDevice_FreeDeviceHandle! @@ -193,7 +207,7 @@ static SDL_AudioDevice *SDL_IMMDevice_Add(const bool recording, const char *devn SDL_copyp(&recording_handle->directsound_guid, dsoundguid); - if (!SDL_AddAudioDevice(true, devname, unique_id, &spec, recording_handle)) { + if (!SDL_AddAudioDevice(true, devname, container_id, unique_id, &spec, recording_handle)) { SDL_free(recording_handle->immdevice_id); SDL_free(recording_handle); } @@ -291,11 +305,13 @@ static HRESULT STDMETHODCALLTYPE SDLMMNotificationClient_OnDeviceStateChanged(IM char *unique_id; WAVEFORMATEXTENSIBLE fmt; GUID dsoundguid; - GetMMDeviceInfo(device, &utf8dev, &fmt, &dsoundguid, &unique_id); + char *container_id; + GetMMDeviceInfo(device, &utf8dev, &fmt, &dsoundguid, &container_id, &unique_id); if (utf8dev) { - SDL_IMMDevice_Add(recording, utf8dev, &fmt, pwstrDeviceId, &dsoundguid, unique_id, client->force_format, client->supports_recording_playback_devices); + SDL_IMMDevice_Add(recording, utf8dev, &fmt, pwstrDeviceId, &dsoundguid, container_id, unique_id, client->force_format, client->supports_recording_playback_devices); SDL_free(utf8dev); } + SDL_free(container_id); SDL_free(unique_id); } else { immcallbacks.audio_device_disconnected(SDL_IMMDevice_FindByDevID(pwstrDeviceId)); @@ -457,16 +473,16 @@ static void EnumerateEndpointsForFlow(const bool recording, SDL_AudioDevice **de char *unique_id = NULL; WAVEFORMATEXTENSIBLE fmt; GUID dsoundguid; - SDL_zero(fmt); - SDL_zero(dsoundguid); - GetMMDeviceInfo(immdevice, &devname, &fmt, &dsoundguid, &unique_id); + char *container_id = NULL; + GetMMDeviceInfo(immdevice, &devname, &fmt, &dsoundguid, &container_id, &unique_id); if (devname) { - SDL_AudioDevice *sdldevice = SDL_IMMDevice_Add(recording, devname, &fmt, devid, &dsoundguid, unique_id, force_format, supports_recording_playback_devices); + SDL_AudioDevice *sdldevice = SDL_IMMDevice_Add(recording, devname, &fmt, devid, &dsoundguid, container_id, unique_id, force_format, supports_recording_playback_devices); if (default_device && default_devid && SDL_wcscmp(default_devid, devid) == 0) { *default_device = sdldevice; } SDL_free(devname); } + SDL_free(container_id); SDL_free(unique_id); CoTaskMemFree(devid); } diff --git a/src/joystick/SDL_gamepad.c b/src/joystick/SDL_gamepad.c index 3dcead11c4..3445643ca3 100644 --- a/src/joystick/SDL_gamepad.c +++ b/src/joystick/SDL_gamepad.c @@ -120,7 +120,6 @@ typedef struct #undef _guarded -static SDL_GUID s_zeroGUID; static GamepadMapping_t *s_pSupportedGamepads SDL_GUARDED_BY(SDL_joystick_lock) = NULL; static GamepadMapping_t *s_pDefaultMapping SDL_GUARDED_BY(SDL_joystick_lock) = NULL; static GamepadMapping_t *s_pXInputMapping SDL_GUARDED_BY(SDL_joystick_lock) = NULL; @@ -1370,7 +1369,7 @@ static GamepadMapping_t *SDL_PrivateMatchGamepadMappingForGUID(SDL_GUID guid, bo for (mapping = s_pSupportedGamepads; mapping; mapping = mapping->next) { SDL_GUID mapping_guid; - if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { + if (SDL_IsZeroGUID(&mapping->guid)) { continue; } @@ -2783,7 +2782,7 @@ char **SDL_GetGamepadMappings(int *count) SDL_LockJoysticks(); for (GamepadMapping_t *mapping = s_pSupportedGamepads; mapping; mapping = mapping->next) { - if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { + if (SDL_IsZeroGUID(&mapping->guid)) { continue; } num_mappings++; @@ -2797,7 +2796,7 @@ char **SDL_GetGamepadMappings(int *count) } else { int i = 0; for (GamepadMapping_t *mapping = s_pSupportedGamepads; mapping; mapping = mapping->next) { - if (SDL_memcmp(&mapping->guid, &s_zeroGUID, sizeof(mapping->guid)) == 0) { + if (SDL_IsZeroGUID(&mapping->guid)) { continue; } @@ -2894,7 +2893,7 @@ bool SDL_SetGamepadMapping(SDL_JoystickID instance_id, const char *mapping) SDL_GUID guid = SDL_GetJoystickGUIDForID(instance_id); bool result = false; - CHECK_PARAM(SDL_memcmp(&guid, &s_zeroGUID, sizeof(guid)) == 0) { + CHECK_PARAM(SDL_IsZeroGUID(&guid)) { return SDL_InvalidParamError("instance_id"); } diff --git a/src/joystick/SDL_joystick.c b/src/joystick/SDL_joystick.c index ffb08e2dd1..deec2f4788 100644 --- a/src/joystick/SDL_joystick.c +++ b/src/joystick/SDL_joystick.c @@ -31,8 +31,8 @@ #include "../events/SDL_events_c.h" #include "../video/SDL_sysvideo.h" #include "../sensor/SDL_sensor_c.h" -#include "hidapi/SDL_hidapijoystick_c.h" #include "../hidapi/SDL_hidapi_c.h" +#include "hidapi/SDL_hidapijoystick_c.h" // This is included in only one place because it has a large static list of controllers #include "controller_type.h" @@ -896,6 +896,7 @@ void SDL_DestroyJoystickDevice(SDL_JoystickDevice *device) SDL_free(device->matches); SDL_free(device->name); SDL_free(device->path); + SDL_free(device->container_id); SDL_free(device); } @@ -2050,6 +2051,10 @@ SDL_Joystick *SDL_OpenJoystick(SDL_JoystickID instance_id) } } + if (device->container_id) { + SDL_SetStringProperty(SDL_GetJoystickProperties(joystick), SDL_PROP_JOYSTICK_CONTAINER_ID_STRING, device->container_id); + } + driver->Update(joystick); SDL_joysticks_opened = true; diff --git a/src/joystick/SDL_sysjoystick.h b/src/joystick/SDL_sysjoystick.h index f504ce235e..aef54f071d 100644 --- a/src/joystick/SDL_sysjoystick.h +++ b/src/joystick/SDL_sysjoystick.h @@ -79,6 +79,7 @@ struct SDL_JoystickDevice char *name; char *path; SDL_GUID guid; + char *container_id; int player_index; int steam_virtual_gamepad_slot; diff --git a/src/joystick/darwin/SDL_iokitjoystick.c b/src/joystick/darwin/SDL_iokitjoystick.c index 6e8475bd7c..0a3236d23f 100644 --- a/src/joystick/darwin/SDL_iokitjoystick.c +++ b/src/joystick/darwin/SDL_iokitjoystick.c @@ -29,6 +29,7 @@ #include "../../haptic/darwin/SDL_syshaptic_c.h" // For haptic hot plugging #include "../usb_ids.h" #include "../../SDL_hints_c.h" +#include "../../core/macos/SDL_ioreg.h" #include #define SDL_JOYSTICK_RUNLOOP_MODE CFSTR("SDLJoystick") @@ -918,8 +919,11 @@ static SDL_JoystickDevice *DARWIN_JoystickQueryDevices(void) static bool DARWIN_JoystickPrepareDevice(SDL_JoystickDevice *device) { -#ifdef SDL_HAPTIC_IOKIT recDevice *data = (recDevice *)device->internal; + + device->container_id = SDL_GetContainerIDFromHIDDevice(data->deviceRef); + +#ifdef SDL_HAPTIC_IOKIT if (data->ffservice) { MacHaptic_MaybeAddDevice(data->ffservice); } diff --git a/src/joystick/gdk/SDL_gameinputjoystick.cpp b/src/joystick/gdk/SDL_gameinputjoystick.cpp index 985b533b2d..d1eb35b65d 100644 --- a/src/joystick/gdk/SDL_gameinputjoystick.cpp +++ b/src/joystick/gdk/SDL_gameinputjoystick.cpp @@ -30,6 +30,7 @@ extern "C" { #include "../hidapi/SDL_hidapijoystick_c.h" +#include "../../core/windows/SDL_hid.h" } enum @@ -492,6 +493,12 @@ static bool GAMEINPUT_JoystickPrepareDevice(SDL_JoystickDevice *device) if (!device->name) { return false; } + +#if GAMEINPUT_API_VERSION >= 4 + GUID container_id; + data->device->GetContainerId(&container_id); + device->container_id = WIN_GetContainerIDString(&container_id); +#endif return true; } diff --git a/src/joystick/hidapi/SDL_hidapijoystick.c b/src/joystick/hidapi/SDL_hidapijoystick.c index 4642e15389..954c60e3e0 100644 --- a/src/joystick/hidapi/SDL_hidapijoystick.c +++ b/src/joystick/hidapi/SDL_hidapijoystick.c @@ -26,8 +26,12 @@ #include "SDL_hidapijoystick_c.h" #include "SDL_hidapi_rumble.h" #include "../../SDL_hints_c.h" - #if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) +#include "../../core/windows/SDL_hid.h" +#elif defined(SDL_PLATFORM_LINUX) +#include "../../core/linux/SDL_sysfs.h" +#elif defined(SDL_PLATFORM_MACOS) +#include "../../core/macos/SDL_ioreg.h" #endif @@ -1487,6 +1491,20 @@ static SDL_JoystickDevice *HIDAPI_JoystickQueryDevices(void) return devices; } +static bool HIDAPI_JoystickPrepareDevice(SDL_JoystickDevice *device) +{ +#if defined(SDL_PLATFORM_WIN32) || defined(SDL_PLATFORM_WINGDK) + device->container_id = WIN_GetContainerIDFromInterfacePath(device->path); +#elif defined(SDL_PLATFORM_LINUX) + device->container_id = SDL_GetContainerIDFromDevicePath(device->path); +#elif defined(SDL_PLATFORM_MACOS) + if (device->path && SDL_strncmp(device->path, "DevSrvsID:", 10) == 0) { + device->container_id = SDL_GetContainerIDFromRegistryEntryID(SDL_strtoull(device->path + 10, NULL, 10)); + } +#endif + return true; +} + static bool HIDAPI_JoystickOpen(SDL_Joystick *joystick, SDL_JoystickDevice *joystick_device) { SDL_JoystickID joystickID = joystick_device->instance_id; @@ -1724,6 +1742,7 @@ static void HIDAPI_JoystickQuit(void) SDL_JoystickDriver SDL_HIDAPI_JoystickDriver = { .Init = HIDAPI_JoystickInit, .QueryDevices = HIDAPI_JoystickQueryDevices, + .PrepareDevice = HIDAPI_JoystickPrepareDevice, .Open = HIDAPI_JoystickOpen, .Rumble = HIDAPI_JoystickRumble, .RumbleTriggers = HIDAPI_JoystickRumbleTriggers, diff --git a/src/joystick/linux/SDL_sysjoystick.c b/src/joystick/linux/SDL_sysjoystick.c index 66470cd9c5..ecd6b14ea0 100644 --- a/src/joystick/linux/SDL_sysjoystick.c +++ b/src/joystick/linux/SDL_sysjoystick.c @@ -43,6 +43,9 @@ #include "../../events/SDL_events_c.h" #include "../../core/linux/SDL_evdev.h" +#ifdef SDL_PLATFORM_LINUX +#include "../../core/linux/SDL_sysfs.h" +#endif #include "../SDL_sysjoystick.h" #include "../SDL_joystick_c.h" #include "../usb_ids.h" @@ -1085,6 +1088,14 @@ static SDL_JoystickDevice *LINUX_CreateJoystickDevice(SDL_joylist_item *data) return device; } +static bool LINUX_JoystickPrepareDevice(SDL_JoystickDevice *device) +{ +#ifdef SDL_PLATFORM_LINUX + device->container_id = SDL_GetContainerIDFromDevicePath(device->path); +#endif + return true; +} + static void FreeRemovedJoylistItems(void) { SDL_joylist_item *entry = SDL_joylist; @@ -2783,6 +2794,7 @@ SDL_JoystickDriver SDL_LINUX_JoystickDriver = { .Init = LINUX_JoystickInit, .QueryDevices = LINUX_JoystickQueryDevices, .DetectDevices = LINUX_JoystickDetectDevices, + .PrepareDevice = LINUX_JoystickPrepareDevice, .GetGamepadMapping = LINUX_JoystickGetGamepadMapping, .Open = LINUX_JoystickOpen, .Rumble = LINUX_JoystickRumble, diff --git a/src/joystick/windows/SDL_dinputjoystick.c b/src/joystick/windows/SDL_dinputjoystick.c index e6f76283c5..76bfe26c92 100644 --- a/src/joystick/windows/SDL_dinputjoystick.c +++ b/src/joystick/windows/SDL_dinputjoystick.c @@ -994,6 +994,8 @@ static bool DINPUT_JoystickPrepareDevice(SDL_JoystickDevice *device) return false; } + device->container_id = WIN_GetContainerIDFromInterfacePath(device->path); + #ifdef SDL_HAPTIC_DINPUT SDL_DINPUT_HapticMaybeAddDevice(&device->internal->dxdevice); #endif diff --git a/test/testaudioinfo.c b/test/testaudioinfo.c index cd0777fcac..7b2ba984c3 100644 --- a/test/testaudioinfo.c +++ b/test/testaudioinfo.c @@ -44,6 +44,11 @@ print_devices(bool recording) SDL_Log(" Unique ID: '%s'", str); } + str = SDL_GetStringProperty(SDL_GetAudioDeviceProperties(devices[i]), SDL_PROP_AUDIO_DEVICE_CONTAINER_ID_STRING, NULL); + if (str) { + SDL_Log(" Container ID: '%s'", str); + } + if (SDL_GetAudioDeviceFormat(devices[i], &spec, &frames)) { SDL_Log(" Sample Rate: %d", spec.freq); SDL_Log(" Channels: %d", spec.channels); diff --git a/test/testcontroller.c b/test/testcontroller.c index b3b4efbf42..5da38ee15d 100644 --- a/test/testcontroller.c +++ b/test/testcontroller.c @@ -1320,6 +1320,7 @@ static void HandleGamepadAdded(SDL_JoystickID id, bool verbose) SDL_PropertiesID props = SDL_GetGamepadProperties(gamepad); const char *name = SDL_GetGamepadName(gamepad); const char *path = SDL_GetGamepadPath(gamepad); + const char *container_id = SDL_GetStringProperty(props, SDL_PROP_GAMEPAD_CONTAINER_ID_STRING, NULL); SDL_GUID guid = SDL_GetGamepadGUIDForID(id); char guid_string[33]; SDL_GUIDToString(guid, guid_string, sizeof(guid_string)); @@ -1346,6 +1347,26 @@ static void HandleGamepadAdded(SDL_JoystickID id, bool verbose) SDL_Log("Player index: %d", SDL_GetGamepadPlayerIndex(gamepad)); } + if (container_id) { + SDL_Log("Container ID: %s", container_id); + + // Look for associated audio devices + for (int recording = 0; recording <= 1; ++recording) { + int num_devices = 0; + SDL_AudioDeviceID *devices = recording ? SDL_GetAudioRecordingDevices(&num_devices) : SDL_GetAudioPlaybackDevices(&num_devices); + if (devices) { + for (int j = 0; j < num_devices; ++j) { + SDL_PropertiesID audio_props = SDL_GetAudioDeviceProperties(devices[j]); + const char *audio_container_id = SDL_GetStringProperty(audio_props, SDL_PROP_AUDIO_DEVICE_CONTAINER_ID_STRING, NULL); + if (audio_container_id && SDL_strcmp(audio_container_id, container_id) == 0) { + SDL_Log("Audio %s device: %s", recording ? "recording" : "playback", SDL_GetAudioDeviceName(devices[j])); + } + } + SDL_free(devices); + } + } + } + switch (SDL_GetJoystickTypeForID(id)) { case SDL_JOYSTICK_TYPE_WHEEL: SDL_Log("Controller is a wheel"); @@ -2523,6 +2544,9 @@ SDL_AppResult SDLCALL SDL_AppInit(void **appstate, int argc, char *argv[]) return SDL_APP_FAILURE; } + /* Initialize audio so we can look up audio devices associated with controllers */ + SDL_Init(SDL_INIT_AUDIO); + SDL_AddGamepadMappingsFromFile("gamecontrollerdb.txt"); if (show_mappings) {