Allow ALooper::awaitResponse to return immediately if the looper is stopped.

Bug: 25088488
Change-Id: I63e69886a8e9cffcaad675ca1a5642c0abf3b466
diff --git a/media/libstagefright/MediaCodec.cpp b/media/libstagefright/MediaCodec.cpp
index dc6009b..c2ffdf2 100644
--- a/media/libstagefright/MediaCodec.cpp
+++ b/media/libstagefright/MediaCodec.cpp
@@ -600,7 +600,12 @@
     msg->setInt32("force", force ? 1 : 0);
 
     sp<AMessage> response;
-    return PostAndAwaitResponse(msg, &response);
+    status_t ret = PostAndAwaitResponse(msg, &response);
+    if (ret == -ENOENT) {
+        ALOGD("MediaCodec looper is gone, skip reclaim");
+        ret = OK;
+    }
+    return ret;
 }
 
 status_t MediaCodec::release() {
diff --git a/media/libstagefright/foundation/ALooper.cpp b/media/libstagefright/foundation/ALooper.cpp
index 90b5f68..5c2e9f9 100644
--- a/media/libstagefright/foundation/ALooper.cpp
+++ b/media/libstagefright/foundation/ALooper.cpp
@@ -151,6 +151,10 @@
     }
 
     mQueueChangedCondition.signal();
+    {
+        Mutex::Autolock autoLock(mRepliesLock);
+        mRepliesCondition.broadcast();
+    }
 
     if (!runningLocally && !thread->isCurrentThread()) {
         // If not running locally and this thread _is_ the looper thread,
@@ -230,13 +234,31 @@
 
 // to be called by AMessage::postAndAwaitResponse only
 status_t ALooper::awaitResponse(const sp<AReplyToken> &replyToken, sp<AMessage> *response) {
+    {
+        Mutex::Autolock autoLock(mLock);
+        if (mThread == NULL) {
+            return -ENOENT;
+        }
+    }
+
     // return status in case we want to handle an interrupted wait
     Mutex::Autolock autoLock(mRepliesLock);
     CHECK(replyToken != NULL);
-    while (!replyToken->retrieveReply(response)) {
+    bool gotReply;
+    bool shouldContinue = true;
+    while (!(gotReply = replyToken->retrieveReply(response)) && shouldContinue) {
         mRepliesCondition.wait(mRepliesLock);
+
+        {
+            Mutex::Autolock autoLock(mLock);
+            if (mThread == NULL) {
+                shouldContinue = false;
+                // continue and try to get potential reply one more time before break the loop
+            }
+        }
     }
-    return OK;
+
+    return gotReply ? OK : -ENOENT;
 }
 
 status_t ALooper::postReply(const sp<AReplyToken> &replyToken, const sp<AMessage> &reply) {