aaudio: fix timestamps and underruns
Start the client after we get valid timing data from the server.
That can take a while because of the long cold start times.
The client is synced with the current position of the service.
Now the client can start clean with no underruns.
Bug: 63918065
Test: test_timestamps.cpp
Change-Id: I5d01eb844e4b14cd5477d56ea1dd9e309abc1c52
diff --git a/media/libaaudio/src/utility/AAudioUtilities.h b/media/libaaudio/src/utility/AAudioUtilities.h
index b0c6c94..f56be32 100644
--- a/media/libaaudio/src/utility/AAudioUtilities.h
+++ b/media/libaaudio/src/utility/AAudioUtilities.h
@@ -272,8 +272,7 @@
class SimpleDoubleBuffer {
public:
SimpleDoubleBuffer()
- : mValues()
- , mCounter(0) {}
+ : mValues() {}
__attribute__((no_sanitize("integer")))
void write(T value) {
@@ -282,6 +281,14 @@
mCounter++; // Increment AFTER updating storage, OK if it wraps.
}
+ /**
+ * This should only be called by the same thread that calls write() or when
+ * no other thread is calling write.
+ */
+ void clear() {
+ mCounter.store(0);
+ }
+
T read() const {
T result;
int before;
@@ -293,7 +300,7 @@
int index = (before & 1) ^ 1;
result = mValues[index];
after = mCounter.load();
- } while ((after != before) && --timeout > 0);
+ } while ((after != before) && (after > 0) && (--timeout > 0));
return result;
}
@@ -306,7 +313,7 @@
private:
T mValues[2];
- std::atomic<int> mCounter;
+ std::atomic<int> mCounter{0};
};
class Timestamp {
@@ -328,4 +335,32 @@
int64_t mNanoseconds;
};
+
+/**
+ * Pass a request to another thread.
+ * This is used when one thread, A, wants another thread, B, to do something.
+ * A naive approach would be for A to set a flag and for B to clear it when done.
+ * But that creates a race condition. This technique avoids the race condition.
+ *
+ * Assumes only one requester and one acknowledger.
+ */
+class AtomicRequestor {
+public:
+ void request() {
+ // TODO handle overflows, very unlikely
+ mRequested++;
+ }
+
+ bool isRequested() {
+ return mRequested.load() > mAcknowledged.load();
+ }
+
+ void acknowledge() {
+ mAcknowledged++;
+ }
+
+private:
+ std::atomic<int> mRequested{0};
+ std::atomic<int> mAcknowledged{0};
+};
#endif //UTILITY_AAUDIO_UTILITIES_H