SDL: Fixed crash on Android 8, due to bugs in AAudio implementation

From 6d5edfa733cca54671207e2d02b732b231971c76 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Tue, 2 Nov 2021 15:59:26 -0700
Subject: [PATCH] Fixed crash on Android 8, due to bugs in AAudio
 implementation

---
 src/audio/aaudio/SDL_aaudio.c | 15 ++++++++++++---
 1 file changed, 12 insertions(+), 3 deletions(-)

diff --git a/src/audio/aaudio/SDL_aaudio.c b/src/audio/aaudio/SDL_aaudio.c
index 91bd114706..43c897182f 100644
--- a/src/audio/aaudio/SDL_aaudio.c
+++ b/src/audio/aaudio/SDL_aaudio.c
@@ -65,7 +65,7 @@ static int aaudio_LoadFunctions(AAUDIO_Data *data)
 void aaudio_errorCallback( AAudioStream *stream, void *userData, aaudio_result_t error );
 void aaudio_errorCallback( AAudioStream *stream, void *userData, aaudio_result_t error )
 {
-	LOGI( "SDL aaudio_errorCallback: %d - %s", error, ctx.AAudio_convertResultToText( error ) );
+    LOGI( "SDL aaudio_errorCallback: %d - %s", error, ctx.AAudio_convertResultToText( error ) );
 }
 
 #define LIB_AAUDIO_SO "libaaudio.so"
@@ -115,7 +115,7 @@ aaudio_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
         ctx.AAudioStreamBuilder_setFormat(ctx.builder, format);
     }
 
-	ctx.AAudioStreamBuilder_setErrorCallback( ctx.builder, aaudio_errorCallback, private );
+    ctx.AAudioStreamBuilder_setErrorCallback( ctx.builder, aaudio_errorCallback, private );
 
     LOGI("AAudio Try to open %u hz %u bit chan %u %s samples %u",
           this->spec.freq, SDL_AUDIO_BITSIZE(this->spec.format),
@@ -274,11 +274,20 @@ aaudio_Init(SDL_AudioDriverImpl *impl)
     aaudio_result_t res;
     LOGI(__func__);
 
+    /* AAudio was introduced in Android 8.0, but has reference counting crash issues in that release,
+     * so don't use it until 8.1.
+     *
+     * See https://github.com/google/oboe/issues/40 for more information.
+     */
+    if (SDL_GetAndroidSDKVersion() < 27) {
+        return 0;
+    }
+
     SDL_zero(ctx);
 
     ctx.handle = SDL_LoadObject(LIB_AAUDIO_SO);
     if (ctx.handle == NULL) {
-        LOGI("SDL Failed to found " LIB_AAUDIO_SO);
+        LOGI("SDL couldn't find " LIB_AAUDIO_SO);
         goto failure;
     }