SDL: coreaudio: fix race condition when closing an input device.

From 4659a84bd1aebeeeac94793afb046a4059e8366d Mon Sep 17 00:00:00 2001
From: "Ryan C. Gordon" <[EMAIL REDACTED]>
Date: Fri, 29 Mar 2024 00:55:38 -0400
Subject: [PATCH] coreaudio: fix race condition when closing an input device.

---
 src/audio/coreaudio/SDL_coreaudio.m | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/audio/coreaudio/SDL_coreaudio.m b/src/audio/coreaudio/SDL_coreaudio.m
index 17cfe79f6707b..8de8d96c052b0 100644
--- a/src/audio/coreaudio/SDL_coreaudio.m
+++ b/src/audio/coreaudio/SDL_coreaudio.m
@@ -621,7 +621,12 @@ static void InputBufferReadyCallback(void *inUserData, AudioQueueRef inAQ, Audio
     SDL_assert(device->hidden->current_buffer == NULL);  // shouldn't have anything pending
     device->hidden->current_buffer = inBuffer;
     SDL_CaptureAudioThreadIterate(device);
-    SDL_assert(device->hidden->current_buffer == NULL);  // CaptureFromDevice/FlushCapture should have enqueued and cleaned it out.
+
+    // buffer is unexpectedly here? We're probably dying, but try to requeue this buffer anyhow.
+    if (device->hidden->current_buffer != NULL) {
+        SDL_assert(SDL_AtomicGet(&device->shutdown) != 0);
+        COREAUDIO_FlushCapture(device);  // just flush it manually, which will requeue it.
+    }
 }
 
 static void COREAUDIO_CloseDevice(SDL_AudioDevice *device)