Camera2: On stopping preview, wait until captures are completed.

If preview is stopped while a still capture or a video snapshot is
underway, wait until the capture completes before stopping preview.

Also use the same behavior for disconnect - do not shut down the
camera device until captures are complete.

This works around HAL implementations which report to be done
(get_in_progress_count returns 0) even when a capture is still
outstanding.

Bug: 7276954

Change-Id: I66290acf1740cc330eadecbcded0c59fa9c5d2fd
diff --git a/services/camera/libcameraservice/Camera2Client.cpp b/services/camera/libcameraservice/Camera2Client.cpp
index 3239483..e073e39 100644
--- a/services/camera/libcameraservice/Camera2Client.cpp
+++ b/services/camera/libcameraservice/Camera2Client.cpp
@@ -378,16 +378,7 @@
 
     ALOGV("Camera %d: Shutting down", mCameraId);
 
-    res = mStreamingProcessor->stopStream();
-    if (res != OK) {
-        ALOGE("%s: Problem stopping streaming: %s (%d)",
-                __FUNCTION__, strerror(-res), res);
-    }
-    res = mDevice->waitUntilDrained();
-    if (res != OK) {
-        ALOGE("%s: Problem waiting for HAL: %s (%d)",
-                __FUNCTION__, strerror(-res), res);
-    }
+    stopPreviewL();
 
     {
         SharedParameters::Lock l(mParameters);
@@ -733,6 +724,7 @@
 void Camera2Client::stopPreviewL() {
     ATRACE_CALL();
     status_t res;
+    const nsecs_t kStopCaptureTimeout = 3000000000LL; // 3 seconds
     Parameters::State state;
     {
         SharedParameters::Lock l(mParameters);
@@ -745,13 +737,11 @@
                     __FUNCTION__, mCameraId);
             break;
         case Parameters::STOPPED:
-            break;
+        case Parameters::VIDEO_SNAPSHOT:
         case Parameters::STILL_CAPTURE:
-            ALOGE("%s: Camera %d: Cannot stop preview during still capture.",
-                    __FUNCTION__, mCameraId);
-            break;
+            mCaptureSequencer->waitUntilIdle(kStopCaptureTimeout);
+            // no break
         case Parameters::RECORD:
-            // no break - identical to preview
         case Parameters::PREVIEW:
             mStreamingProcessor->stopStream();
             res = mDevice->waitUntilDrained();