Fix some issues with pending buffer traces

1. If there is already something in the pending transactions queue, we
will skip calling transactionIsReadyToBeApplied. This means we won't
increment the buffer count properly. Instead, call
transactionIsReadyToBeApplied first since it's pretty harmless and will
update the buffer count if needed.

2. updateActiveBuffer can be called multiple times with the same buffer.
This is because when checking hasReadyFrame, we only check if something
has been modified and there's a buffer. It's possible that the geometry
was updated, but we didn't receive a new buffer. In that case, we'd still
call updateActiveBuffer. That would call decrementPendingBufferCount which
is incorrect since there's no new buffer.

Instead, check if the buffer has changed in updateActiveBuffer before
calling decrementPendingBufferCount to make sure the buffer getting
updated is a new buffer buffer.

Test: trace isn't going negative
Fixes: 176903239
Change-Id: I0bd492463e5e440db16fc8bef1408b5156e961e4
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 63201b0..d179d22 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -3377,8 +3377,10 @@
     const int originPid = ipc->getCallingPid();
     const int originUid = ipc->getCallingUid();
 
-    if (pendingTransactions ||
-        !transactionIsReadyToBeApplied(isAutoTimestamp ? 0 : desiredPresentTime, states, true)) {
+    // Call transactionIsReadyToBeApplied first in case we need to incrementPendingBufferCount
+    // if the transaction contains a buffer.
+    if (!transactionIsReadyToBeApplied(isAutoTimestamp ? 0 : desiredPresentTime, states, true) ||
+        pendingTransactions) {
         mTransactionQueues[applyToken].emplace(frameTimelineVsyncId, states, displays, flags,
                                                desiredPresentTime, isAutoTimestamp, uncacheBuffer,
                                                postTime, privileged, hasListenerCallbacks,