1 /*
2  * Copyright 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package androidx.camera.core;
18 
19 import androidx.camera.core.impl.ImageReaderProxy;
20 import androidx.camera.core.impl.utils.executor.CameraXExecutors;
21 import androidx.camera.core.impl.utils.futures.FutureCallback;
22 import androidx.camera.core.impl.utils.futures.Futures;
23 
24 import com.google.common.util.concurrent.ListenableFuture;
25 
26 import org.jspecify.annotations.NonNull;
27 import org.jspecify.annotations.Nullable;
28 
29 /**
30  * OnImageAvailableListener with blocking behavior. It never drops image without analyzing it.
31  *
32  * <p> Used with {@link ImageAnalysis}.
33  */
34 final class ImageAnalysisBlockingAnalyzer extends ImageAnalysisAbstractAnalyzer {
35 
36     @Override
acquireImage(@onNull ImageReaderProxy imageReaderProxy)37     @Nullable ImageProxy acquireImage(@NonNull ImageReaderProxy imageReaderProxy) {
38         // Use acquireNextImage() so it never drops older images.
39         return imageReaderProxy.acquireNextImage();
40     }
41 
42     @Override
onValidImageAvailable(@onNull ImageProxy imageProxy)43     void onValidImageAvailable(@NonNull ImageProxy imageProxy) {
44         ListenableFuture<Void> analyzeFuture = analyzeImage(imageProxy);
45 
46         // Callback to close the image only after analysis complete regardless of success
47         Futures.addCallback(analyzeFuture, new FutureCallback<Void>() {
48             @Override
49             public void onSuccess(Void result) {
50                 // No-op. Keep blocking the image reader until user closes the current one.
51             }
52 
53             @Override
54             public void onFailure(@NonNull Throwable t) {
55                 imageProxy.close();
56             }
57         }, CameraXExecutors.directExecutor());
58     }
59 
60     @Override
clearCache()61     void clearCache() {
62         // no-op. The blocking analyzer does not cache images.
63     }
64 }
65