aaudio: prevent noise when stopping a stream

The DSP is stopped after the callback is stopped.
If the CPU is slow and the time gap is too large then
the DSP can play past the valid data and play invalid data.

To prevent noise, this new code clears part of the FIFO
beyond the valid data. Then when the DSP has read the valid
data it clears the entire FIFO.

Then it waits for the valid data to reach the speaker,
based on a latency estimation using timestamps.

Bug: 261783315
Test: Use OboeTester with repro steps in the bug.
Change-Id: Ia31df4b21c805b4ae9ca4fb8366068be1cce2c9f
diff --git a/media/libaaudio/src/client/AudioStreamInternal.cpp b/media/libaaudio/src/client/AudioStreamInternal.cpp
index 7648e25..b2e93f0 100644
--- a/media/libaaudio/src/client/AudioStreamInternal.cpp
+++ b/media/libaaudio/src/client/AudioStreamInternal.cpp
@@ -575,10 +575,20 @@
         return AAUDIO_ERROR_INVALID_STATE;
     }
 
+    // For playback, sleep until all the audio data has played.
+    // Then clear the buffer to prevent noise.
+    prepareBuffersForStop();
+
     mClockModel.stop(AudioClock::getNanoseconds());
     setState(AAUDIO_STREAM_STATE_STOPPING);
     mAtomicInternalTimestamp.clear();
 
+#if 0
+    // Simulate very slow CPU, force race condition where the
+    // DSP keeps playing after we stop writing.
+    AudioClock::sleepForNanos(800 * AAUDIO_NANOS_PER_MILLISECOND);
+#endif
+
     result = mServiceInterface.stopStream(mServiceStreamHandleInfo);
     if (result == AAUDIO_ERROR_INVALID_HANDLE) {
         ALOGD("%s() INVALID_HANDLE, stream was probably stolen", __func__);