aaudio: fix audioserver crash when starting a stream is rejected

Bug: 65738271
Test: repeat when not root:   input_monitor  -m2 -pl
Change-Id: I98659dbd78a75785565b1b6f0254a48220253af6
diff --git a/services/oboeservice/AAudioServiceEndpointShared.cpp b/services/oboeservice/AAudioServiceEndpointShared.cpp
index 18dc12f..cd40066 100644
--- a/services/oboeservice/AAudioServiceEndpointShared.cpp
+++ b/services/oboeservice/AAudioServiceEndpointShared.cpp
@@ -115,15 +115,33 @@
 aaudio_result_t AAudioServiceEndpointShared::startStream(sp<AAudioServiceStreamBase> sharedStream,
                                                          audio_port_handle_t *clientHandle) {
     aaudio_result_t result = AAUDIO_OK;
-    if (++mRunningStreamCount == 1) {
-        // TODO use real-time technique to avoid mutex, eg. atomic command FIFO
+
+    {
         std::lock_guard<std::mutex> lock(mLockStreams);
-        result = getStreamInternal()->requestStart();
-        startSharingThread_l();
+        if (++mRunningStreamCount == 1) { // atomic
+            result = getStreamInternal()->requestStart();
+            if (result != AAUDIO_OK) {
+                --mRunningStreamCount;
+            } else {
+                result = startSharingThread_l();
+                if (result != AAUDIO_OK) {
+                    getStreamInternal()->requestStop();
+                    --mRunningStreamCount;
+                }
+            }
+        }
     }
+
     if (result == AAUDIO_OK) {
         result = getStreamInternal()->startClient(sharedStream->getAudioClient(), clientHandle);
+        if (result != AAUDIO_OK) {
+            if (--mRunningStreamCount == 0) { // atomic
+                stopSharingThread();
+                getStreamInternal()->requestStop();
+            }
+        }
     }
+
     return result;
 }
 
@@ -141,7 +159,6 @@
     return AAUDIO_OK;
 }
 
-
 // Get timestamp that was written by the real-time service thread, eg. mixer.
 aaudio_result_t AAudioServiceEndpointShared::getFreeRunningPosition(int64_t *positionFrames,
                                                                   int64_t *timeNanos) {