audioflinger: Update throttling logic in MixerThread

The throttling logic in MixerThread only keeps track of
time spent during sink write. However, on low tier
APs and with high sample rate tracks, it is possible
that time spent in mixing the tracks is significant.
This inturn leads to sink writes returning earlier than
expected kicking in (incorrectly) the throttling logic.

To fix this, update throttling logic to include
the time spent in mixing buffers along with the time
spent in sink write.

authored-by: Dhananjay Kumar <dhakumar@codeaurora.org>

Bug: 28672515
Change-Id: Iac4994c3084850bb93640c978b4a519db8d7951d
diff --git a/services/audioflinger/Threads.cpp b/services/audioflinger/Threads.cpp
index bd7f6d5..e721a80 100644
--- a/services/audioflinger/Threads.cpp
+++ b/services/audioflinger/Threads.cpp
@@ -2846,6 +2846,7 @@
 
     // MIXER
     nsecs_t lastWarning = 0;
+    nsecs_t mixStartNs = 0;
 
     // DUPLICATING
     // FIXME could this be made local to while loop?
@@ -3010,6 +3011,7 @@
         if (mBytesRemaining == 0) {
             mCurrentWriteLength = 0;
             if (mMixerStatus == MIXER_TRACKS_READY) {
+                mixStartNs = systemTime();
                 // threadLoop_mix() sets mCurrentWriteLength
                 threadLoop_mix();
             } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
@@ -3137,8 +3139,13 @@
                         // (1) mixer threads without a fast mixer (which has its own warm-up)
                         // (2) minimum buffer sized tracks (even if the track is full,
                         //     the app won't fill fast enough to handle the sudden draw).
+                        //
+                        // Total time spent in last processing cycle equals time spent in
+                        // 1. threadLoop_write, as well as time spent in
+                        // 2. threadLoop_mix (significant for heavy mixing, especially
+                        //                    on low tier processors)
 
-                        const int32_t deltaMs = delta / 1000000;
+                        const int32_t deltaMs = (now - mixStartNs)/ 1000000;
                         const int32_t throttleMs = mHalfBufferMs - deltaMs;
                         if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
                             usleep(throttleMs * 1000);