media.bufferpool2: ensure message-ids are safe from overflow/underflow

Since message-ids can be wrapped, they are not safe from
overflow/underflow. Change them to be safe from overflow/underflow.

Bug: 321674574
Change-Id: I39a4baf057fc81389925e0fe358894f62ade9423
diff --git a/media/bufferpool/aidl/default/BufferPool.cpp b/media/bufferpool/aidl/default/BufferPool.cpp
index ed4574f..57716db 100644
--- a/media/bufferpool/aidl/default/BufferPool.cpp
+++ b/media/bufferpool/aidl/default/BufferPool.cpp
@@ -102,11 +102,11 @@
         if (it->isInvalidated(bufferId)) {
             uint32_t msgId = 0;
             if (it->mNeedsAck) {
-                msgId = ++mInvalidationId;
-                if (msgId == 0) {
-                    // wrap happens
-                    msgId = ++mInvalidationId;
+                if (mInvalidationId == UINT_MAX) {
+                    // wrap happens;
+                    mInvalidationId = 0;
                 }
+                msgId = ++mInvalidationId;
             }
             channel.postInvalidation(msgId, it->mFrom, it->mTo);
             it = mPendings.erase(it);
@@ -125,11 +125,11 @@
         const std::shared_ptr<Accessor> &impl) {
         uint32_t msgId = 0;
     if (needsAck) {
-        msgId = ++mInvalidationId;
-        if (msgId == 0) {
-            // wrap happens
-            msgId = ++mInvalidationId;
+        if (mInvalidationId == UINT_MAX) {
+            //wrap happens
+            mInvalidationId = 0;
         }
+        msgId = ++mInvalidationId;
     }
     ALOGV("bufferpool2 invalidation requested and queued");
     if (left == 0) {
diff --git a/media/bufferpool/aidl/default/BufferStatus.cpp b/media/bufferpool/aidl/default/BufferStatus.cpp
index 19caa1e..fecbe3f 100644
--- a/media/bufferpool/aidl/default/BufferStatus.cpp
+++ b/media/bufferpool/aidl/default/BufferStatus.cpp
@@ -26,8 +26,17 @@
 
 using aidl::android::hardware::media::bufferpool2::BufferStatus;
 
+uint32_t wrappedMinus(uint32_t a, uint32_t b) {
+    if (a >= b) {
+        return a - b;
+    } else {
+        return ~(b - a) + 1;
+    }
+}
+
 bool isMessageLater(uint32_t curMsgId, uint32_t prevMsgId) {
-    return curMsgId != prevMsgId && curMsgId - prevMsgId < prevMsgId - curMsgId;
+    return curMsgId != prevMsgId &&
+            wrappedMinus(curMsgId, prevMsgId) < wrappedMinus(prevMsgId, curMsgId);
 }
 
 bool isBufferInRange(BufferId from, BufferId to, BufferId bufferId) {