AudioFlinger: fix timed audio

(cherry picked from commit e20ac92c564a2f4e8123885807abdf0a78de0dd7)

> AudioFlinger: fix timed audio
>
> Addresses Bug 6900517.
>
> Finish up support for timed audio in the new FastMixer world.  Pay special
> attention to remaining lock-less and voluntary yield free on the FastMixer
> thread.  This fixes audio playback for Q on JB.
>
> Change-Id: Iaf815e58a1b1d0a0190051794bec8dc5c9231785
> Signed-off-by: John Grossman <johngro@google.com>

Change-Id: I9bd687acc345a05867af48e71116690fdb0ce1b5
Signed-off-by: John Grossman <johngro@google.com>
diff --git a/services/audioflinger/MonoPipeReader.cpp b/services/audioflinger/MonoPipeReader.cpp
index b80d0c0..39a07de 100644
--- a/services/audioflinger/MonoPipeReader.cpp
+++ b/services/audioflinger/MonoPipeReader.cpp
@@ -43,11 +43,25 @@
     return ret;
 }
 
-ssize_t MonoPipeReader::read(void *buffer, size_t count)
+ssize_t MonoPipeReader::read(void *buffer, size_t count, int64_t readPTS)
 {
+    // Compute the "next read PTS" and cache it.  Callers of read pass a read
+    // PTS indicating the local time for which they are requesting data along
+    // with a count (which is the number of audio frames they are going to
+    // ultimately pass to the next stage of the pipeline).  Offsetting readPTS
+    // by the duration of count will give us the readPTS which will be passed to
+    // us next time, assuming they system continues to operate in steady state
+    // with no discontinuities.  We stash this value so it can be used by the
+    // MonoPipe writer to imlement getNextWriteTimestamp.
+    int64_t nextReadPTS;
+    nextReadPTS = mPipe->offsetTimestampByAudioFrames(readPTS, count);
+
     // count == 0 is unlikely and not worth checking for explicitly; will be handled automatically
     ssize_t red = availableToRead();
     if (CC_UNLIKELY(red <= 0)) {
+        // Uh-oh, looks like we are underflowing.  Update the next read PTS and
+        // get out.
+        mPipe->updateFrontAndNRPTS(mPipe->mFront, nextReadPTS);
         return red;
     }
     if (CC_LIKELY((size_t) red > count)) {
@@ -66,7 +80,7 @@
                 memcpy((char *) buffer + (part1 << mBitShift), mPipe->mBuffer, part2 << mBitShift);
             }
         }
-        android_atomic_release_store(red + mPipe->mFront, &mPipe->mFront);
+        mPipe->updateFrontAndNRPTS(red + mPipe->mFront, nextReadPTS);
         mFramesRead += red;
     }
     return red;