Fix inconsistant results for some cts tests.

This patch fixes any cts test that uses the camera's startPreview function
without the proper timing delay before stopping the preview. When we do a
startPreview(), it will start a WorkerThread. If that thread don't get a
chance to run, then when we try to stop the thread, the stop can fail and
cause the current test to fail (thread not running) or subsequent tests
to fail (thread already started).

The following tests are known to fail randomly due to this timing problem:
android.hardware.cts.CameraTest#testDisplayOrientation
android.hardware.cts.CameraTest#testGetParameterDuringFocus
android.hardware.cts.CameraTest#testJpegCallbackStartPreview
android.hardware.cts.CameraTest#testRecordingHint
android.hardware.cts.CameraTest#testLockUnlock
android.hardware.cts.CameraTest#testPreviewCallback
android.hardware.cts.CameraTest#testSetOneShotPreviewCallback
android.media.cts.MediaRandomTest#testRecorderRandomAction

Change-Id: Ifc20d93bc02cdc49161f54c083a32138574a8d39
diff --git a/camera/EmulatedCameraDevice.cpp b/camera/EmulatedCameraDevice.cpp
index b76353d..c8e5640 100755
--- a/camera/EmulatedCameraDevice.cpp
+++ b/camera/EmulatedCameraDevice.cpp
@@ -291,16 +291,21 @@
             "%s: Thread control FDs are opened", __FUNCTION__);
     /* Create a pair of FDs that would be used to control the thread. */
     int thread_fds[2];
+    status_t ret;
+    Mutex::Autolock lock(mCameraDevice->mObjectLock);
     if (pipe(thread_fds) == 0) {
         mThreadControl = thread_fds[1];
         mControlFD = thread_fds[0];
         ALOGV("Emulated device's worker thread has been started.");
-        return NO_ERROR;
+        ret = NO_ERROR;
     } else {
         ALOGE("%s: Unable to create thread control FDs: %d -> %s",
              __FUNCTION__, errno, strerror(errno));
-        return errno;
+        ret = errno;
     }
+
+    mSetup.signal();
+    return ret;
 }
 
 status_t EmulatedCameraDevice::WorkerThread::stopThread()
@@ -308,6 +313,17 @@
     ALOGV("Stopping emulated camera device's worker thread...");
 
     status_t res = EINVAL;
+
+    // Limit the scope of the Autolock
+    {
+      // If thread is running and readyToRun() has not finished running,
+      //    then wait until it is done.
+      Mutex::Autolock lock(mCameraDevice->mObjectLock);
+      if (isRunning() && (mThreadControl < 0 || mControlFD < 0)) {
+          mSetup.wait(mCameraDevice->mObjectLock);
+      }
+    }
+
     if (mThreadControl >= 0) {
         /* Send "stop" message to the thread loop. */
         const ControlMessage msg = THREAD_STOP;
diff --git a/camera/EmulatedCameraDevice.h b/camera/EmulatedCameraDevice.h
index b7cdcb7..ee9f7dd 100755
--- a/camera/EmulatedCameraDevice.h
+++ b/camera/EmulatedCameraDevice.h
@@ -467,6 +467,8 @@
                 /* Stop the thread. */
                 THREAD_STOP
             };
+
+            Condition mSetup;
     };
 
     /* Worker thread accessor. */