Fix uncertainty of one normal mix buffer in AudioTrack::getTimestamp

The per-thread timestamp latch was not synchronized with the per-track
released frames.  Now the value of each track's released frames is
latched along with the timestamp.

Bug: 17531839
Bug: 17669342
Change-Id: I9d50c8c6a5de55a3f4561ac40e20d497376c1257
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index 12e09ab..b1e9c07 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -2101,6 +2101,7 @@
 
     // If an NBAIO sink is present, use it to write the normal mixer's submix
     if (mNormalSink != 0) {
+
         const size_t count = mBytesRemaining / mFrameSize;
 
         ATRACE_BEGIN("write");
@@ -2126,6 +2127,7 @@
             size_t totalFramesWritten = mNormalSink->framesWritten();
             if (totalFramesWritten >= mLatchD.mTimestamp.mPosition) {
                 mLatchD.mUnpresentedFrames = totalFramesWritten - mLatchD.mTimestamp.mPosition;
+                // mLatchD.mFramesReleased is set immediately before D is clocked into Q
                 mLatchDValid = true;
             }
         }
@@ -2418,6 +2420,18 @@
                 logString = NULL;
             }
 
+            // Gather the framesReleased counters for all active tracks,
+            // and latch them atomically with the timestamp.
+            // FIXME We're using raw pointers as indices. A unique track ID would be a better index.
+            mLatchD.mFramesReleased.clear();
+            size_t size = mActiveTracks.size();
+            for (size_t i = 0; i < size; i++) {
+                sp<Track> t = mActiveTracks[i].promote();
+                if (t != 0) {
+                    mLatchD.mFramesReleased.add(t.get(),
+                            t->mAudioTrackServerProxy->framesReleased());
+                }
+            }
             if (mLatchDValid) {
                 mLatchQ = mLatchD;
                 mLatchDValid = false;
@@ -3093,6 +3107,7 @@
     sleepTime = 0;
     standbyTime = systemTime() + standbyDelay;
     //TODO: delay standby when effects have a tail
+
 }
 
 void AudioFlinger::MixerThread::threadLoop_sleepTime()