From f63e9a8a3fecc34f1e2110974f3171b91b56e761 Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Fri, 27 Oct 2023 01:30:27 -0400
Subject: [PATCH] wasapi: Handle disconnected devices that get reconnected.
The device ID strings don't change between connects, so we need to move the
old device object out of the way if it still exists as a zombie, and let
the reconnected device get itself a fresh object.
---
src/core/windows/SDL_immdevice.c | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/src/core/windows/SDL_immdevice.c b/src/core/windows/SDL_immdevice.c
index 12ce1c5d2e1d..629f4a181c02 100644
--- a/src/core/windows/SDL_immdevice.c
+++ b/src/core/windows/SDL_immdevice.c
@@ -133,6 +133,18 @@ static SDL_AudioDevice *SDL_IMMDevice_Add(const SDL_bool iscapture, const char *
// see if we already have this one first.
SDL_AudioDevice *device = SDL_IMMDevice_FindByDevID(devid);
+ if (device) {
+ if (SDL_AtomicGet(&device->zombie)) {
+ // whoa, it came back! This can happen if you unplug and replug USB headphones while we're still keeping the SDL object alive.
+ // Kill this device's IMMDevice id; the device will go away when the app closes it, or maybe a new default device is chosen
+ // (possibly this reconnected device), so we just want to make sure IMMDevice doesn't try to find the old device by the existing ID string.
+ SDL_IMMDevice_HandleData *handle = (SDL_IMMDevice_HandleData *) device->handle;
+ SDL_free(handle->immdevice_id);
+ handle->immdevice_id = NULL;
+ device = NULL; // add a new device, below.
+ }
+ }
+
if (!device) {
// handle is freed by SDL_IMMDevice_FreeDeviceHandle!
SDL_IMMDevice_HandleData *handle = SDL_malloc(sizeof(SDL_IMMDevice_HandleData));