1 /*
<lambda>null2  * Copyright 2021 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.integration.extensions.utils
18 
19 import android.annotation.SuppressLint
20 import android.content.Context
21 import android.hardware.camera2.CameraAccessException
22 import android.hardware.camera2.CameraManager
23 import androidx.camera.core.CameraFilter
24 import androidx.camera.core.CameraInfo
25 import androidx.camera.core.CameraSelector
26 import androidx.camera.core.impl.CameraInfoInternal
27 import androidx.camera.extensions.ExtensionMode
28 import androidx.camera.extensions.ExtensionsManager
29 
30 object CameraSelectorUtil {
31 
32     @JvmStatic
33     @SuppressLint("RestrictedApiAndroidX")
34     fun createCameraSelectorById(cameraId: String) =
35         CameraSelector.Builder()
36             .addCameraFilter(
37                 CameraFilter { cameraInfos ->
38                     cameraInfos.forEach {
39                         if ((it as CameraInfoInternal).cameraId.equals(cameraId)) {
40                             return@CameraFilter listOf<CameraInfo>(it)
41                         }
42                     }
43 
44                     return@CameraFilter emptyList()
45                 }
46             )
47             .build()
48 
49     @JvmStatic
50     fun findNextSupportedCameraId(
51         context: Context,
52         extensionsManager: ExtensionsManager,
53         currentCameraId: String,
54         @ExtensionMode.Mode extensionsMode: Int
55     ): String? {
56         val cameraManager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
57         try {
58             val supportedCameraIdList =
59                 cameraManager.cameraIdList.filter {
60                     extensionsManager.isExtensionAvailable(
61                         createCameraSelectorById(it),
62                         extensionsMode
63                     )
64                 }
65 
66             if (supportedCameraIdList.size == 1) {
67                 return null
68             }
69 
70             supportedCameraIdList.forEachIndexed { index, id ->
71                 if (currentCameraId == id) {
72                     return supportedCameraIdList[(index + 1) % supportedCameraIdList.size]
73                 }
74             }
75         } catch (e: CameraAccessException) {}
76         return null
77     }
78 }
79