blob: bb2db3331657197facfb7cf8e473a63cb31d5ce2 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 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 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
darkobasd7b8fa52018-08-07 13:00:17 +020030#ifdef TARGET_CAMERA_NEEDS_CLIENT_INFO
31#include <iostream>
32#include <fstream>
33#endif
Mathias Agopian65ab4712010-07-14 17:59:35 -070034#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080035#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070036#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080037#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070038
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080039#include <android/hardware/ICamera.h>
40#include <android/hardware/ICameraClient.h>
41
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070042#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070043#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080044#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000045#include <android_companion_virtualdevice_flags.h>
46#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080048#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <binder/MemoryBase.h>
51#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080052#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080053#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080054#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070055#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070057#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080058#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080059#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070061#include "hidl/HidlCameraService.h"
62#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080063#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070064#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070065#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080066#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070067#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070068#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000069#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070070#include <utils/Errors.h>
71#include <utils/Log.h>
72#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070073#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080074#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080075#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080076#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080077#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070078#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000079#include <binder/IServiceManager.h>
80#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000081#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070082#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080083
Ruben Brunkb2119af2014-05-09 19:57:56 -070084#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070085
86#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070087#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070088#include "api2/CameraDeviceClient.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070089#include "utils/CameraServiceProxyWrapper.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000090#include "utils/CameraTraces.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070091#include "utils/SessionConfigurationUtils.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000092#include "utils/TagMonitor.h"
93#include "utils/Utils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070094
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080095namespace {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080096 const char* kActivityServiceName = "activity";
97 const char* kSensorPrivacyServiceName = "sensor_privacy";
98 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070099 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +0000100 const char* kVirtualDeviceBackCameraId = "0";
101 const char* kVirtualDeviceFrontCameraId = "1";
Austin Borger23694432024-10-07 19:28:01 -0700102 const char* kUnknownPackageName = "<unknown>";
Biswarup Pal37a75182024-01-16 15:53:35 +0000103
104 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
105 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
106 return android::kDefaultDeviceId;
107 }
108
109 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
110 return deviceIdEntry.data.i32[0];
111 }
Austin Borgera0c61f12024-10-11 13:38:35 -0700112
113 static android::PermissionChecker::PermissionResult appOpModeToPermissionResult(int32_t res) {
114 switch (res) {
115 case android::AppOpsManager::MODE_ERRORED:
116 return android::PermissionChecker::PERMISSION_HARD_DENIED;
117 case android::AppOpsManager::MODE_IGNORED:
118 return android::PermissionChecker::PERMISSION_SOFT_DENIED;
119 case android::AppOpsManager::MODE_ALLOWED:
120 return android::PermissionChecker::PERMISSION_GRANTED;
121 }
122
123 ALOGE("%s: Unexpected appOpMode %d", __FUNCTION__, res);
124 return android::PermissionChecker::PERMISSION_HARD_DENIED;
125 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000126} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800127
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128namespace android {
129
Austin Borgerea931242021-12-13 23:10:41 +0000130using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700131using namespace camera3::SessionConfigurationUtils;
132
133using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000134using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700135using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700136using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800137using hardware::ICamera;
138using hardware::ICameraClient;
139using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800140using hardware::camera2::ICameraInjectionCallback;
141using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800142using hardware::camera2::utils::CameraIdAndSessionConfiguration;
143using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000144
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700145namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000146namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800147
Mathias Agopian65ab4712010-07-14 17:59:35 -0700148// ----------------------------------------------------------------------------
149// Logging support -- this is for debugging only
150// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700151volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700152
Steve Blockb8a80522011-12-20 16:23:08 +0000153#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
154#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700155
156static void setLogLevel(int level) {
157 android_atomic_write(level, &gLogLevel);
158}
159
Henri Chataingbcb99452023-11-01 17:40:30 +0000160int32_t format_as(CameraService::StatusInternal s) {
161 return fmt::underlying(s);
162}
163
Mathias Agopian65ab4712010-07-14 17:59:35 -0700164// ----------------------------------------------------------------------------
165
Austin Borger249e6592024-03-10 22:28:11 -0700166// Permission strings (references to AttributionAndPermissionUtils for brevity)
167static const std::string &sDumpPermission =
168 AttributionAndPermissionUtils::sDumpPermission;
169static const std::string &sManageCameraPermission =
170 AttributionAndPermissionUtils::sManageCameraPermission;
171static const std::string &sCameraSendSystemEventsPermission =
172 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
173static const std::string &sCameraInjectExternalCameraPermission =
174 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
175
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000176// Constant integer for FGS Logging, used to denote the API type for logger
177static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700178const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800179static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
180static constexpr int32_t kSystemNativeClientState =
181 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700182static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700183
Austin Borgered99f642023-06-01 16:51:35 -0700184const std::string CameraService::kOfflineDevice("offline-");
185const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700186
Biswarup Pal7d072862024-04-17 15:24:47 +0000187constexpr int32_t kInvalidDeviceId = -1;
188
Rucha Katakward9ea6452021-05-06 11:57:16 -0700189// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700190static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700191
Austin Borger74fca042022-05-23 12:41:21 -0700192CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700193 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
194 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
195 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
196 std::make_shared<AttributionAndPermissionUtils>()\
197 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700198 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
199 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800200 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800201 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700202 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700203 mSoundRef(0), mInitialized(false),
204 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000205 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700206 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800207 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700208 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
209 if (mMemFd == -1) {
210 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
211 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700212}
213
Charles Chena7b613c2023-01-24 21:57:33 +0000214// Enable processes with isolated AID to request the binder
215void CameraService::instantiate() {
216 CameraService::publish(true);
217}
218
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800219void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700220 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800221 return;
222 }
223
224 ALOGV("appops service registered. setting camera audio restriction");
225 mAppOps.setCameraAudioRestriction(mAudioRestriction);
226}
227
Iliyan Malchev8951a972011-04-14 16:55:59 -0700228void CameraService::onFirstRef()
229{
Ruben Brunkcc776712015-02-17 20:18:47 -0800230 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800231
Iliyan Malchev8951a972011-04-14 16:55:59 -0700232 BnCameraService::onFirstRef();
233
Ruben Brunk99e69712015-05-26 17:25:07 -0700234 // Update battery life tracking if service is restarting
235 BatteryNotifier& notifier(BatteryNotifier::getInstance());
236 notifier.noteResetCamera();
237 notifier.noteResetFlashlight();
238
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800239 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800240
Emilian Peevf53f66e2017-04-11 14:29:43 +0100241 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800242 if (res == OK) {
243 mInitialized = true;
244 }
245
Svet Ganova453d0d2018-01-11 15:37:58 -0800246 mUidPolicy = new UidPolicy(this);
247 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700248 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800249 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800250 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800251
252 // appops function setCamerAudioRestriction uses getService which
253 // is blocking till the appops service is ready. To enable early
254 // boot availability for cameraservice, use checkService which is
255 // non blocking and register for notifications
256 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700257 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800258 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700259 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800260 } else {
261 mAppOps.setCameraAudioRestriction(mAudioRestriction);
262 }
263
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700264 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
265 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000266 // Deprecated, so it will fail to register on newer devices
267 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700268 __FUNCTION__);
269 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700270
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700271 if (!AidlCameraService::registerService(this)) {
272 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
273 }
274
Shuzhen Wang24b44152019-09-20 10:38:11 -0700275 // This needs to be last call in this function, so that it's as close to
276 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700277 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700278 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800279}
280
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800281status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800282 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100283
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800284 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000285 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800286 {
287 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800288
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800289 if (nullptr == mCameraProviderManager.get()) {
290 mCameraProviderManager = new CameraProviderManager();
291 res = mCameraProviderManager->initialize(this);
292 if (res != OK) {
293 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
294 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700295 logServiceError("Unable to initialize camera provider manager",
296 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100298 }
299 }
300
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800301 // Setup vendor tags before we call get_camera_info the first time
302 // because HAL might need to setup static vendor keys in get_camera_info
303 // TODO: maybe put this into CameraProviderManager::initialize()?
304 mCameraProviderManager->setUpVendorTags();
305
306 if (nullptr == mFlashlight.get()) {
307 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700308 }
309
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800310 res = mFlashlight->findFlashUnits();
311 if (res != OK) {
312 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
313 }
314
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000315 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800316 }
317
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800318 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700319 if (getCameraState(cameraId) == nullptr) {
320 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800321 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000322 if (unavailPhysicalIds.count(cameraId) > 0) {
323 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700324 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000325 }
326 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800327 }
328
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700329 // Derive primary rear/front cameras, and filter their charactierstics.
330 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700331 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700332 // Assume internal cameras are advertised from the same
333 // provider. If multiple providers are registered at different time,
334 // and each provider contains multiple internal color cameras, the current
335 // logic may filter the characteristics of more than one front/rear color
336 // cameras.
337 Mutex::Autolock l(mServiceLock);
338 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700339 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700340
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800341 return OK;
342}
343
Austin Borgered99f642023-06-01 16:51:35 -0700344void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700345 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000346 // Get the device id and app-visible camera id for the given HAL-visible camera id.
347 auto [deviceId, mappedCameraId] =
348 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
349
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800350 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800351 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700352 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
353 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000354 ALOGV("%s: Skipping torch callback for system-only camera device %s",
355 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700356 continue;
357 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000358
Austin Borgere8e2c422022-05-12 13:45:24 -0700359 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000360 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700361 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
362 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800363 }
364}
365
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800367 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800368 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800369 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800370 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371}
372
Emilian Peevaee727d2017-05-04 16:35:48 +0100373void CameraService::onNewProviderRegistered() {
374 enumerateProviders();
375}
376
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700377void CameraService::filterAPI1SystemCameraLocked(
378 const std::vector<std::string> &normalDeviceIds) {
379 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000380 for (auto &cameraId : normalDeviceIds) {
381 if (vd_flags::camera_device_awareness()) {
382 CameraMetadata cameraInfo;
383 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000384 cameraId, false, &cameraInfo,
385 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000386 int32_t deviceId = kDefaultDeviceId;
387 if (res != OK) {
388 ALOGW("%s: Not able to get camera characteristics for camera id %s",
389 __FUNCTION__, cameraId.c_str());
390 } else {
391 deviceId = getDeviceId(cameraInfo);
392 }
393 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
394 // system cameras, so skip for non-default device id's.
395 if (deviceId != kDefaultDeviceId) {
396 continue;
397 }
398 }
399
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000401 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
402 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700403 continue;
404 }
405 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700406 // All system camera ids will necessarily come after public camera
407 // device ids as per the HAL interface contract.
408 break;
409 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000410 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700411 }
412 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
413 mNormalDeviceIdsWithoutSystemCamera.size());
414}
415
Austin Borgered99f642023-06-01 16:51:35 -0700416status_t CameraService::getSystemCameraKind(const std::string& cameraId,
417 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700418 auto state = getCameraState(cameraId);
419 if (state != nullptr) {
420 *kind = state->getSystemCameraKind();
421 return OK;
422 }
423 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700424 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700425}
426
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800427void CameraService::updateCameraNumAndIds() {
428 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700429 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
430 // Excludes hidden secure cameras
431 mNumberOfCameras =
432 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
433 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800434 mNormalDeviceIds =
435 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700436 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800437}
438
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700439void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700440 // To claim to be S Performance primary cameras, the cameras must be
441 // backward compatible. So performance class primary camera Ids must be API1
442 // compatible.
443 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
444 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
445 int facing = -1;
446 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800447 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000448 getDeviceVersion(cameraId,
449 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
450 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700451 if (facing == -1) {
452 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
453 return;
454 }
455
456 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
457 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700458 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
459 if (res == OK) {
460 mPerfClassPrimaryCameraIds.insert(cameraId);
461 } else {
462 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
463 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
464 break;
465 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700466
467 if (facing == hardware::CAMERA_FACING_BACK) {
468 firstRearCameraSeen = true;
469 }
470 if (facing == hardware::CAMERA_FACING_FRONT) {
471 firstFrontCameraSeen = true;
472 }
473 }
474
475 if (firstRearCameraSeen && firstFrontCameraSeen) {
476 break;
477 }
478 }
479}
480
Austin Borgered99f642023-06-01 16:51:35 -0700481void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700482 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100483 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
484 if (res != OK) {
485 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
486 return;
487 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000488 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700489 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
490 if (res != OK) {
491 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
492 return;
493 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000494 std::vector<std::string> physicalCameraIds;
495 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700496 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700498 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100499 }
500
501 {
502 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700503 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000504 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100505 }
506
Austin Borgered99f642023-06-01 16:51:35 -0700507 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100508 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700509 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800510
Austin Borgered99f642023-06-01 16:51:35 -0700511 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100512 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800513
514 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700515 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100516}
517
Austin Borgered99f642023-06-01 16:51:35 -0700518void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800519 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700520 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100521 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700522 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100523 }
524
525 {
526 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700527 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100528 }
529}
530
Austin Borgered99f642023-06-01 16:51:35 -0700531void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800532 CameraDeviceStatus newHalStatus) {
533 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700534 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700535
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800536 StatusInternal newStatus = mapToInternal(newHalStatus);
537
Austin Borgered99f642023-06-01 16:51:35 -0700538 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800539
540 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700541 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100542 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700543 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100544
545 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700546 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100547
Austin Borgered99f642023-06-01 16:51:35 -0700548 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700549 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700550 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700551 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700552 return;
553 }
554
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800555 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800556
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800557 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700558 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
559 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700560 return;
561 }
562
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800563 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000564 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
565 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800566 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
567 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700568 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000569 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800570
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700571 std::vector<sp<BasicClient>> clientsToDisconnectOnline, clientsToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700572 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800573 // Don't do this in updateStatus to avoid deadlock over mServiceLock
574 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700575
Ruben Brunkcc776712015-02-17 20:18:47 -0800576 // Remove cached shim parameters
577 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700578
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800579 // Remove online as well as offline client from the list of active clients,
580 // if they are present
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700581 clientsToDisconnectOnline = removeClientsLocked(cameraId);
582 clientsToDisconnectOffline = removeClientsLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700583 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800584
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700585 disconnectClients(cameraId, clientsToDisconnectOnline);
586 disconnectClients(kOfflineDevice + cameraId, clientsToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700587
Austin Borgered99f642023-06-01 16:51:35 -0700588 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800589 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800590 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000591 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
592 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700593 }
Austin Borgered99f642023-06-01 16:51:35 -0700594 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700595 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800596}
Igor Murashkincba2c162013-03-20 15:56:31 -0700597
Austin Borgered99f642023-06-01 16:51:35 -0700598void CameraService::onDeviceStatusChanged(const std::string& id,
599 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800600 CameraDeviceStatus newHalStatus) {
601 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700602 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800603
604 StatusInternal newStatus = mapToInternal(newHalStatus);
605
606 std::shared_ptr<CameraState> state = getCameraState(id);
607
608 if (state == nullptr) {
609 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700610 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800611 return;
612 }
613
614 StatusInternal logicalCameraStatus = state->getStatus();
615 if (logicalCameraStatus != StatusInternal::PRESENT &&
616 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
617 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700618 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800619 return;
620 }
621
622 bool updated = false;
623 if (newStatus == StatusInternal::PRESENT) {
624 updated = state->removeUnavailablePhysicalId(physicalId);
625 } else {
626 updated = state->addUnavailablePhysicalId(physicalId);
627 }
628
629 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700630 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800631 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000632 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800633 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000634 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800635 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700636 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
637 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
638 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700639 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700640 return;
641 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800642 Mutex::Autolock lock(mStatusListenerLock);
643 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700644 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
645 listener->getListenerPid(), listener->getListenerUid())) {
646 ALOGV("Skipping discovery callback for system-only camera device %s",
647 id.c_str());
648 continue;
649 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700650 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000651 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700652 listener->handleBinderStatus(ret,
653 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
654 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
655 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800656 }
657 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700658}
659
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700660void CameraService::disconnectClients(const std::string& id,
661 std::vector<sp<BasicClient>> clientsToDisconnect) {
662 for (auto& client : clientsToDisconnect) {
663 disconnectClient(id, client);
664 }
665}
666
Austin Borgered99f642023-06-01 16:51:35 -0700667void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800668 if (clientToDisconnect.get() != nullptr) {
669 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700670 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800671 // Notify the client of disconnection
672 clientToDisconnect->notifyError(
673 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
674 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800675 clientToDisconnect->disconnect();
676 }
677}
678
Austin Borgered99f642023-06-01 16:51:35 -0700679void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800680 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700681 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
682 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
683 if (res != OK) {
684 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700685 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700686 return;
687 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800688 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700689 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800690}
691
Austin Borgered99f642023-06-01 16:51:35 -0700692void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700693 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
694 Mutex::Autolock al(mTorchStatusMutex);
695 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
696}
697
Austin Borgered99f642023-06-01 16:51:35 -0700698void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800699 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000700 // Get the device id and app-visible camera id for the given HAL-visible camera id.
701 auto [deviceId, mappedCameraId] =
702 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
703
Rucha Katakwar38284522021-11-10 11:25:21 -0800704 Mutex::Autolock lock(mStatusListenerLock);
705 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000706 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
707 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700708 i->handleBinderStatus(ret,
709 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
710 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800711 }
712}
713
Austin Borgered99f642023-06-01 16:51:35 -0700714void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700715 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800716 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700717 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800718
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800719 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800720 status_t res = getTorchStatusLocked(cameraId, &status);
721 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700722 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700723 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800724 return;
725 }
726 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800727 return;
728 }
729
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800730 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800731 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800732 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
733 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800734 return;
735 }
736
Ruben Brunkcc776712015-02-17 20:18:47 -0800737 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700738 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700739 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700740 auto iter = mTorchUidMap.find(cameraId);
741 if (iter != mTorchUidMap.end()) {
742 int oldUid = iter->second.second;
743 int newUid = iter->second.first;
744 BatteryNotifier& notifier(BatteryNotifier::getInstance());
745 if (oldUid != newUid) {
746 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800747 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700748 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700749 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800750 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700751 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700752 }
753 iter->second.second = newUid;
754 } else {
755 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800756 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700757 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700758 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700759 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700760 }
761 }
762 }
763 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700764 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800765}
766
Austin Borger249e6592024-03-10 22:28:11 -0700767bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700768 // Returns false if this is not an automotive device type.
769 if (!isAutomotiveDevice())
770 return false;
771
772 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700773 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700774 return false;
775
776 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
777 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
778 // This isn't a known camera ID, so it's not a system camera.
779 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
780 return false;
781 }
782
783 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
784 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
785 return false;
786 }
787
788 CameraMetadata cameraInfo;
789 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000790 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700791 if (res != OK){
792 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
793 cam_id.c_str());
794 return false;
795 }
796
797 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
798 if (auto_location.count != 1)
799 return false;
800
801 uint8_t location = auto_location.data.u8[0];
802 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
803 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
804 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
805 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
806 return false;
807 }
808
809 return true;
810}
811
Austin Borger65e64642024-06-11 15:58:23 -0700812Status CameraService::getNumberOfCameras(int32_t type,
813 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000814 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700815 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700816 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000817 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700818 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000819 return Status::ok();
820 }
821
Emilian Peevaee727d2017-05-04 16:35:48 +0100822 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700823 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800824 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
825 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700826 switch (type) {
827 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700828 if (hasSystemCameraPermissions) {
829 *numCameras = static_cast<int>(mNormalDeviceIds.size());
830 } else {
831 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
832 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800833 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700834 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700835 if (hasSystemCameraPermissions) {
836 *numCameras = mNumberOfCameras;
837 } else {
838 *numCameras = mNumberOfCamerasWithoutSystemCamera;
839 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800840 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700841 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800842 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700843 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800844 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
845 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700846 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800847 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700848}
849
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700850Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700851 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700852 /* out */
853 hardware::camera2::impl::CameraMetadataNative* request) {
854 ATRACE_CALL();
855
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700856 if (!mInitialized) {
857 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
858 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
859 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
860 }
861
Austin Borger65e64642024-06-11 15:58:23 -0700862 std::optional<std::string> cameraIdOptional =
863 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000864 if (!cameraIdOptional.has_value()) {
865 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700866 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000867 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
868 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
869 }
870 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700871
872 binder::Status res;
873 if (request == nullptr) {
874 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
875 "Camera %s: Error creating default request", cameraId.c_str());
876 return res;
877 }
878 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
879 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
880 cameraId, templateId, &tempId);
881 if (!res.isOk()) {
882 ALOGE("%s: Camera %s: failed to map request Template %d",
883 __FUNCTION__, cameraId.c_str(), templateId);
884 return res;
885 }
886
887 if (shouldRejectSystemCameraConnection(cameraId)) {
888 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
889 "request for system only device %s: ", cameraId.c_str());
890 }
891
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700892 CameraMetadata metadata;
893 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
894 if (err == OK) {
895 request->swap(metadata);
896 } else if (err == BAD_VALUE) {
897 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
898 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
899 cameraId.c_str(), templateId, strerror(-err), err);
900 } else {
901 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
902 "Camera %s: Error creating default request for template %d: %s (%d)",
903 cameraId.c_str(), templateId, strerror(-err), err);
904 }
905 return res;
906}
907
908Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700909 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700910 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700911 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700912 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700913 ATRACE_CALL();
914
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700915 if (!mInitialized) {
916 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
917 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
918 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
919 }
920
Austin Borger65e64642024-06-11 15:58:23 -0700921 std::optional<std::string> cameraIdOptional =
922 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000923 if (!cameraIdOptional.has_value()) {
924 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700925 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000926 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
927 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
928 }
929 std::string cameraId = cameraIdOptional.value();
930
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700931 if (supported == nullptr) {
932 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
933 unresolvedCameraId.c_str());
934 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
935 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
936 }
937
938 if (shouldRejectSystemCameraConnection(cameraId)) {
939 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
940 "session configuration with parameters support for system only device %s: ",
941 cameraId.c_str());
942 }
943
Avichal Rakeshe005df52024-09-25 17:13:27 -0700944 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700945 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
946
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700947 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
948 sessionConfiguration, overrideForPerfClass, supported);
949 if (flags::analytics_24q3()) {
950 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
951 getCallingUid(), sessionConfiguration, ret);
952 }
953 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700954}
955
956Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
957 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
958 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700959 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700960 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
961 cameraId, sessionConfiguration, overrideForPerfClass,
962 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700963 binder::Status res;
964 switch (ret) {
965 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700966 // Expected. Do Nothing.
967 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700968 case INVALID_OPERATION: {
969 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700970 "Camera %s: Session configuration with parameters supported query not "
971 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700972 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700973 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
974 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
975 *supported = false;
976 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700977 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700978 break;
979 case NAME_NOT_FOUND: {
980 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
981 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
982 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
983 *supported = false;
984 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
985 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700986 break;
987 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700988 std::string msg = fmt::sprintf(
989 "Unable to retrieve session configuration support for camera "
990 "device %s: Error: %s (%d)",
991 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700992 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700993 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
994 *supported = false;
995 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700996 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700997 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700998 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700999}
1000
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001001Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001002 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -07001003 const SessionConfiguration& sessionConfiguration,
1004 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +00001005 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001006 ATRACE_CALL();
1007
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001008 if (outMetadata == nullptr) {
1009 std::string msg =
1010 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1011 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1012 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1013 }
1014
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001015 if (!mInitialized) {
1016 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1017 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1018 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1019 }
1020
Austin Borger65e64642024-06-11 15:58:23 -07001021 std::optional<std::string> cameraIdOptional =
1022 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001023 if (!cameraIdOptional.has_value()) {
1024 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001025 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001026 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1027 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1028 }
1029 std::string cameraId = cameraIdOptional.value();
1030
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001031 if (shouldRejectSystemCameraConnection(cameraId)) {
1032 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1033 "Unable to retrieve camera"
1034 "characteristics for system only device %s: ",
1035 cameraId.c_str());
1036 }
1037
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001038 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1039 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesheb961c72024-09-25 17:26:26 -07001040
1041 bool sessionConfigSupported;
1042 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1043 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1044 if (!res.isOk()) {
1045 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1046 // report the correct Status to send to the client. Simply forward the error to
1047 // the client.
1048 outMetadata->clear();
1049 return res;
1050 }
1051
1052 if (!sessionConfigSupported) {
1053 std::string msg = fmt::sprintf("Session configuration not supported for camera device %s.",
1054 cameraId.c_str());
1055 outMetadata->clear();
1056 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001057 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001058
1059 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001060 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001061
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001062 switch (ret) {
1063 case OK:
1064 // Expected, no handling needed.
1065 break;
1066 case INVALID_OPERATION: {
1067 std::string msg = fmt::sprintf(
1068 "Camera %s: Session characteristics query not supported!",
1069 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001070 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001071 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1072 outMetadata->clear();
1073 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1074 }
1075 break;
1076 case NAME_NOT_FOUND: {
1077 std::string msg = fmt::sprintf(
1078 "Camera %s: Unknown camera ID.",
1079 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001080 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001081 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1082 outMetadata->clear();
1083 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001084 }
1085 break;
1086 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001087 std::string msg = fmt::sprintf(
1088 "Unable to retrieve session characteristics for camera device %s: "
1089 "Error: %s (%d)",
1090 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001091 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001092 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1093 outMetadata->clear();
1094 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001095 }
1096 }
1097
Avichal Rakesheb961c72024-09-25 17:26:26 -07001098 res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001099 if (flags::analytics_24q3()) {
1100 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1101 getCallingUid(), sessionConfiguration, res);
1102 }
1103 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001104}
1105
1106Status CameraService::filterSensitiveMetadataIfNeeded(
1107 const std::string& cameraId, CameraMetadata* metadata) {
1108 int callingPid = getCallingPid();
1109 int callingUid = getCallingUid();
1110
1111 if (callingPid == getpid()) {
1112 // Caller is cameraserver; no need to remove keys
1113 return Status::ok();
1114 }
1115
1116 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1117 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1118 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1119 metadata->clear();
1120 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1121 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1122 }
1123 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1124 // Attempting to query system only camera without system camera permission would have
1125 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1126 // for a system only camera, then the caller has the required permission.
1127 // No need to remove keys
1128 return Status::ok();
1129 }
1130
1131 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001132 // Get the device id that owns this camera.
1133 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1134 cameraId);
1135 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1136 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001137 if (hasCameraPermission) {
1138 // Caller has camera permission; no need to remove keys
1139 return Status::ok();
1140 }
1141
1142 status_t ret = metadata->removePermissionEntries(
1143 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1144 if (ret != OK) {
1145 metadata->clear();
1146 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1147 "Failed to remove camera characteristics needing camera permission "
1148 "for device %s:%s (%d)",
1149 cameraId.c_str(), strerror(-ret), ret);
1150 }
1151
1152 if (!tagsRemoved.empty()) {
1153 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1154 tagsRemoved.data(), tagsRemoved.size());
1155 if (ret != OK) {
1156 metadata->clear();
1157 return STATUS_ERROR_FMT(
1158 ERROR_INVALID_OPERATION,
1159 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1160 cameraId.c_str(), strerror(-ret), ret);
1161 }
1162 }
1163 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001164}
1165
malikakash22af94c2023-12-04 18:13:14 +00001166Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001167 const std::string& cameraId,
1168 const CameraMetadata& sessionParams) {
1169 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001170 const int pid = getCallingPid();
1171 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001172 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1173 __FUNCTION__, pid, uid);
1174 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1175 "Permission Denial: no permission to inject session params");
1176 }
1177
Biswarup Pal37a75182024-01-16 15:53:35 +00001178 // Do not allow session params injection for a virtual camera.
1179 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1180 if (deviceId != kDefaultDeviceId) {
1181 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1182 "Cannot inject session params for a virtual camera");
1183 }
1184
malikakash22af94c2023-12-04 18:13:14 +00001185 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1186 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1187
1188 auto clientDescriptor = mActiveClientManager.get(cameraId);
1189 if (clientDescriptor == nullptr) {
1190 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1191 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1192 "No active client for camera id %s", cameraId.c_str());
1193 }
1194
1195 sp<BasicClient> clientSp = clientDescriptor->getValue();
1196 status_t res = clientSp->injectSessionParams(sessionParams);
1197
1198 if (res != OK) {
1199 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1200 "Error injecting session params into camera \"%s\": %s (%d)",
1201 cameraId.c_str(), strerror(-res), res);
1202 }
1203 return Status::ok();
1204}
1205
Biswarup Pal37a75182024-01-16 15:53:35 +00001206std::optional<std::string> CameraService::resolveCameraId(
1207 const std::string& inputCameraId,
1208 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001209 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001210 if ((deviceId == kDefaultDeviceId)
1211 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1212 auto [storedDeviceId, _] =
1213 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1214 if (storedDeviceId != kDefaultDeviceId) {
1215 // Trying to access a virtual camera from default-policy device context, we should fail.
1216 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1217 inputCameraId.c_str(), deviceId);
1218 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1219 return std::nullopt;
1220 }
malikakash98260df2024-05-10 23:33:57 +00001221 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001222 }
1223
1224 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1225}
1226
Austin Borger65e64642024-06-11 15:58:23 -07001227Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1228 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1229 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001230 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001231 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001232 std::string cameraIdStr =
1233 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001234 if (cameraIdStr.empty()) {
1235 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001236 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001237 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1238 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1239 }
malikakashedb38962023-09-06 00:03:35 +00001240
Austin Borgered99f642023-06-01 16:51:35 -07001241 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001242 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1243 "characteristics for system only device %s: ", cameraIdStr.c_str());
1244 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001245
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001246 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001247 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001248 return STATUS_ERROR(ERROR_DISCONNECTED,
1249 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001250 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001251 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001252 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001253 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1254 if (hasSystemCameraPermissions) {
1255 cameraIdBound = mNumberOfCameras;
1256 }
1257 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001258 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1259 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 }
1261
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001262 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001263 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001264 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001265 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001266 if (err != OK) {
1267 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1268 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1269 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001270 logServiceError(std::string("Error retrieving camera info from device ")
1271 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001272 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001273
Ruben Brunkcc776712015-02-17 20:18:47 -08001274 return ret;
1275}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001276
Biswarup Pal37a75182024-01-16 15:53:35 +00001277std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1278 int32_t deviceId, int32_t devicePolicy) {
1279 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1280 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1281 std::optional<std::string> cameraIdOptional =
1282 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1283 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1284 }
1285
1286 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001287 auto callingPid = getCallingPid();
1288 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001289 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1290 callingPid, callingUid, /* checkCameraPermissions= */ false);
1291 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001292 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001293 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001294 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1295 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1296 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001297 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001298 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001299
malikakash98260df2024-05-10 23:33:57 +00001300 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001301}
1302
Biswarup Pal37a75182024-01-16 15:53:35 +00001303std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1304 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001305 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001306 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001307}
1308
Austin Borgered99f642023-06-01 16:51:35 -07001309Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001310 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1311 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001312 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001313
Zhijun He2b59be82013-09-25 10:14:30 -07001314 if (!cameraInfo) {
1315 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001316 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001317 }
1318
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001319 if (!mInitialized) {
1320 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001321 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001322 return STATUS_ERROR(ERROR_DISCONNECTED,
1323 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001324 }
1325
Austin Borger65e64642024-06-11 15:58:23 -07001326 std::optional<std::string> cameraIdOptional =
1327 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001328 if (!cameraIdOptional.has_value()) {
1329 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001330 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001331 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1332 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1333 }
1334 std::string cameraId = cameraIdOptional.value();
1335
Austin Borgered99f642023-06-01 16:51:35 -07001336 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001337 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001338 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001339 }
1340
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001341 bool overrideForPerfClass =
1342 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001343 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001344 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001345 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001346 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001347 if (res == NAME_NOT_FOUND) {
1348 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001349 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001350 strerror(-res), res);
1351 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001352 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1353 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001354 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001355 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001356 strerror(-res), res);
1357 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001358 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001359
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001360 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001361}
1362
Austin Borger65e64642024-06-11 15:58:23 -07001363Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1364 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001365 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001366 ATRACE_CALL();
1367 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001368
Austin Borger65e64642024-06-11 15:58:23 -07001369 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1370 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001371 if (!cameraIdOptional.has_value()) {
1372 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001373 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001374 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1375 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1376 }
1377 std::string cameraId = cameraIdOptional.value();
1378
Rucha Katakwar38284522021-11-10 11:25:21 -08001379 if (!mInitialized) {
1380 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1381 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1382 }
1383
Biswarup Pal37a75182024-01-16 15:53:35 +00001384 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001385 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1386 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1387 }
1388
Austin Borgered99f642023-06-01 16:51:35 -07001389 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001390 if (res != OK) {
1391 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001392 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001393 strerror(-res), res);
1394 }
1395 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1396 return Status::ok();
1397}
1398
Austin Borgered99f642023-06-01 16:51:35 -07001399std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001400 time_t now = time(nullptr);
1401 char formattedTime[64];
1402 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001403 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001404}
1405
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001406Status CameraService::getCameraVendorTagDescriptor(
1407 /*out*/
1408 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001409 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001410 if (!mInitialized) {
1411 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001413 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001414 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1415 if (globalDescriptor != nullptr) {
1416 *desc = *(globalDescriptor.get());
1417 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001418 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001419}
1420
Emilian Peev71c73a22017-03-21 16:35:51 +00001421Status CameraService::getCameraVendorTagCache(
1422 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1423 ATRACE_CALL();
1424 if (!mInitialized) {
1425 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1426 return STATUS_ERROR(ERROR_DISCONNECTED,
1427 "Camera subsystem not available");
1428 }
1429 sp<VendorTagDescriptorCache> globalCache =
1430 VendorTagDescriptorCache::getGlobalVendorTagCache();
1431 if (globalCache != nullptr) {
1432 *cache = *(globalCache.get());
1433 }
1434 return Status::ok();
1435}
1436
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001437void CameraService::clearCachedVariables() {
1438 BasicClient::BasicClient::sCameraService = nullptr;
1439}
1440
Austin Borgered99f642023-06-01 16:51:35 -07001441std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001442 int rotationOverride, int* portraitRotation, int* facing,
1443 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001444 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001445
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001446 int deviceVersion = 0;
1447
Emilian Peevf53f66e2017-04-11 14:29:43 +01001448 status_t res;
1449 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001450 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001451 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001452 if (res != OK || transport == IPCTransport::INVALID) {
1453 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001454 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001455 return std::make_pair(-1, IPCTransport::INVALID) ;
1456 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001457 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001458
Emilian Peevf53f66e2017-04-11 14:29:43 +01001459 hardware::CameraInfo info;
1460 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001461 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001462 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001463 if (res != OK) {
1464 return std::make_pair(-1, IPCTransport::INVALID);
1465 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001466 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001467 if (orientation) {
1468 *orientation = info.orientation;
1469 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001470 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001471
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001472 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001473}
1474
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001475Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001476 switch(err) {
1477 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001478 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001479 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1481 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001482 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001483 return STATUS_ERROR(ERROR_DISCONNECTED,
1484 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001485 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001486 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1487 "Camera HAL encountered error %d: %s",
1488 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001489 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001490}
1491
Austin Borger2e772b82024-10-11 16:09:57 -07001492Status CameraService::makeClient(
1493 const sp<CameraService>& cameraService, const sp<IInterface>& cameraCb,
1494 const AttributionSourceState& clientAttribution, int callingPid, bool systemNativeClient,
1495 const std::string& cameraId, int api1CameraId, int facing, int sensorOrientation,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001496 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001497 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001498 bool forceSlowJpegMode, const std::string& originalCameraId, bool sharedMode,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00001499 bool isVendorClient,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001500 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001501 // For HIDL devices
1502 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1503 // Create CameraClient based on device version reported by the HAL.
1504 int deviceVersion = deviceVersionAndTransport.first;
1505 switch(deviceVersion) {
1506 case CAMERA_DEVICE_API_VERSION_1_0:
1507 ALOGE("Camera using old HAL version: %d", deviceVersion);
1508 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1509 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001510 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001511 break;
1512 case CAMERA_DEVICE_API_VERSION_3_0:
1513 case CAMERA_DEVICE_API_VERSION_3_1:
1514 case CAMERA_DEVICE_API_VERSION_3_2:
1515 case CAMERA_DEVICE_API_VERSION_3_3:
1516 case CAMERA_DEVICE_API_VERSION_3_4:
1517 case CAMERA_DEVICE_API_VERSION_3_5:
1518 case CAMERA_DEVICE_API_VERSION_3_6:
1519 case CAMERA_DEVICE_API_VERSION_3_7:
1520 break;
1521 default:
1522 // Should not be reachable
1523 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1524 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1525 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001526 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001527 }
1528 }
1529 if (effectiveApiLevel == API_1) { // Camera1 API route
1530 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001531 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger2e772b82024-10-11 16:09:57 -07001532 cameraService->mAttributionAndPermissionUtils,
1533 clientAttribution, callingPid, cameraId, api1CameraId, facing,
1534 sensorOrientation, servicePid, overrideForPerfClass,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001535 rotationOverride, forceSlowJpegMode, /*sharedMode*/false);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001536 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1537 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001538 } else { // Camera2 API route
1539 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1540 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger2e772b82024-10-11 16:09:57 -07001541 *client = new CameraDeviceClient(
1542 cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1543 cameraService->mAttributionAndPermissionUtils, clientAttribution, callingPid,
1544 systemNativeClient, cameraId, facing, sensorOrientation, servicePid,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00001545 overrideForPerfClass, rotationOverride, originalCameraId, sharedMode,
1546 isVendorClient);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001547 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001548 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001549 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001550}
1551
Austin Borgered99f642023-06-01 16:51:35 -07001552std::string CameraService::toString(std::set<userid_t> intSet) {
1553 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001554 bool first = true;
1555 for (userid_t i : intSet) {
1556 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001557 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001558 first = false;
1559 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001560 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001561 }
1562 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001563 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001564}
1565
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001566int32_t CameraService::mapToInterface(TorchModeStatus status) {
1567 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1568 switch (status) {
1569 case TorchModeStatus::NOT_AVAILABLE:
1570 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1571 break;
1572 case TorchModeStatus::AVAILABLE_OFF:
1573 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1574 break;
1575 case TorchModeStatus::AVAILABLE_ON:
1576 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1577 break;
1578 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001579 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001580 }
1581 return serviceStatus;
1582}
1583
1584CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1585 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1586 switch (status) {
1587 case CameraDeviceStatus::NOT_PRESENT:
1588 serviceStatus = StatusInternal::NOT_PRESENT;
1589 break;
1590 case CameraDeviceStatus::PRESENT:
1591 serviceStatus = StatusInternal::PRESENT;
1592 break;
1593 case CameraDeviceStatus::ENUMERATING:
1594 serviceStatus = StatusInternal::ENUMERATING;
1595 break;
1596 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001597 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001598 }
1599 return serviceStatus;
1600}
1601
1602int32_t CameraService::mapToInterface(StatusInternal status) {
1603 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1604 switch (status) {
1605 case StatusInternal::NOT_PRESENT:
1606 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1607 break;
1608 case StatusInternal::PRESENT:
1609 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1610 break;
1611 case StatusInternal::ENUMERATING:
1612 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1613 break;
1614 case StatusInternal::NOT_AVAILABLE:
1615 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1616 break;
1617 case StatusInternal::UNKNOWN:
1618 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1619 break;
1620 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001621 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001622 }
1623 return serviceStatus;
1624}
1625
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001627 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001628
Austin Borgered99f642023-06-01 16:51:35 -07001629 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001630 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001631 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001632
Austin Borgerb01a8702024-07-22 16:20:34 -07001633 int callingPid = getCallingPid();
1634 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001635
Austin Borger23694432024-10-07 19:28:01 -07001636 AttributionSourceState clientAttribution =
1637 buildAttributionSource(callingPid, uid, kServiceName, kDefaultDeviceId);
1638
1639 if (!(ret = connectHelper<ICameraClient, Client>(
1640 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId, clientAttribution,
1641 /*systemNativeClient*/ false, API_1, /*shimUpdateOnly*/ true,
1642 /*oomScoreOffset*/ 0,
1643 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1644 /*rotationOverride*/
1645 hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001646 /*forceSlowJpegMode*/ false, cameraIdStr, /*isNonSystemNdk*/ false,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00001647 /*sharedMode*/false, /*isVendorClient*/false,/*out*/ tmp))
Austin Borger23694432024-10-07 19:28:01 -07001648 .isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001649 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001650 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001651 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001652}
1653
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001655 /*out*/
1656 CameraParameters* parameters) {
1657
1658 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001660 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001661
1662 if (parameters == NULL) {
1663 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001664 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001665 }
1666
malikakash98260df2024-05-10 23:33:57 +00001667 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001668
1669 // Check if we already have parameters
1670 {
1671 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001672 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001673 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001674 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001675 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001676 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001677 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 }
1679 CameraParameters p = cameraState->getShimParams();
1680 if (!p.isEmpty()) {
1681 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001682 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001683 }
1684 }
1685
Austin Borger22c5c852024-03-08 13:31:36 -08001686 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001687 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001688 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001689 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001690 // Error already logged by callee
1691 return ret;
1692 }
1693
1694 // Check for parameters again
1695 {
1696 // Scope for service lock
1697 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001698 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001699 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001700 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001701 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001702 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001703 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001704 CameraParameters p = cameraState->getShimParams();
1705 if (!p.isEmpty()) {
1706 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001707 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001708 }
1709 }
1710
Ruben Brunkcc776712015-02-17 20:18:47 -08001711 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1712 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001713 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001714}
1715
Austin Borgered99f642023-06-01 16:51:35 -07001716Status CameraService::validateConnectLocked(const std::string& cameraId,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001717 const AttributionSourceState& clientAttribution,
1718 bool sharedMode) const {
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001719#ifdef __BRILLO__
Austin Borger23694432024-10-07 19:28:01 -07001720 UNUSED(clientAttribution);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001721#else
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001722 Status allowed = validateClientPermissionsLocked(cameraId, clientAttribution, sharedMode);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001723 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001724 return allowed;
1725 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001726#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001727
Austin Borger22c5c852024-03-08 13:31:36 -08001728 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001729
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001730 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001731 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1732 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001733 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001734 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001735 }
1736
Ruben Brunkcc776712015-02-17 20:18:47 -08001737 if (getCameraState(cameraId) == nullptr) {
1738 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001739 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001740 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001741 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 }
1743
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001744 status_t err = checkIfDeviceIsUsable(cameraId);
1745 if (err != NO_ERROR) {
1746 switch(err) {
1747 case -ENODEV:
1748 case -EBUSY:
1749 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001750 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001751 default:
1752 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001753 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001754 }
1755 }
1756 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001757}
1758
Austin Borger23694432024-10-07 19:28:01 -07001759Status CameraService::validateClientPermissionsLocked(
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001760 const std::string& cameraId, const AttributionSourceState& clientAttribution,
1761 bool sharedMode) const {
Austin Borgerb01a8702024-07-22 16:20:34 -07001762 int callingPid = getCallingPid();
1763 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001764
Austin Borger23694432024-10-07 19:28:01 -07001765 int clientPid = clientAttribution.pid;
1766 int clientUid = clientAttribution.uid;
1767 const std::string clientName = clientAttribution.packageName.value_or(kUnknownPackageName);
1768
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001769 if (shouldRejectSystemCameraConnection(cameraId)) {
1770 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1771 cameraId.c_str());
1772 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001773 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001774 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001775 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1776 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001777 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001778 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001779 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001780 }
1781
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001782 if (flags::camera_multi_client() && sharedMode
1783 && (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA)) {
1784 ALOGE("%s: camera id %s is not system camera. Device sharing only supported for"
1785 " system cameras.", __FUNCTION__, cameraId.c_str());
1786 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "camera device sharing not supported for "
1787 "camera ID \"%s\"", cameraId.c_str());
1788 }
1789
Biswarup Pale506e732024-03-27 13:46:20 +00001790 // Get the device id that owns this camera.
1791 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Austin Borger23694432024-10-07 19:28:01 -07001792 AttributionSourceState clientAttributionWithDeviceId = clientAttribution;
1793 clientAttributionWithDeviceId.deviceId = deviceId;
Biswarup Pale506e732024-03-27 13:46:20 +00001794
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001795 // If it's not calling from cameraserver, check the permission if the
1796 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1797 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001798 bool checkPermissionForCamera =
Austin Borger23694432024-10-07 19:28:01 -07001799 hasPermissionsForCamera(cameraId, clientAttributionWithDeviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001800 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001801 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001802 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001803 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1804 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001805 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001806 }
1807
Svet Ganova453d0d2018-01-11 15:37:58 -08001808 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001809 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001810 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001811 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1812 clientPid, clientUid);
1813 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001814 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1815 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001816 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001817 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001818 }
1819
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001820 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1821 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1822 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1823 if ((!isAutomotivePrivilegedClient(callingUid) ||
1824 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1825 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001826 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1827 return STATUS_ERROR_FMT(ERROR_DISABLED,
1828 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001829 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001830 }
1831
Austin Borger6e831c42024-07-22 13:07:56 -07001832 userid_t clientUserId = multiuser_get_user_id(clientUid);
1833
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001834 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1835 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001836
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001837 // For non-system clients : Only allow clients who are being used by the current foreground
1838 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001839 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001840 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001841 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1842 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001843 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001844 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1845 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001846 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001847 }
1848
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001849 if (flags::camera_hsum_permission()) {
1850 // If the System User tries to access the camera when the device is running in
1851 // headless system user mode, ensure that client has the required permission
1852 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001853 if (isHeadlessSystemUserMode()
1854 && (clientUserId == USER_SYSTEM)
1855 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001856 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001857 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1858 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1859 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001860 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001861 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001862 }
1863
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001864 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001865}
1866
Austin Borgered99f642023-06-01 16:51:35 -07001867status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001868 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001869 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001870 if (cameraState == nullptr) {
1871 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001872 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 return -ENODEV;
1874 }
1875
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001876 StatusInternal currentStatus = cameraState->getStatus();
1877 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001878 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001879 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001880 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001881 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001882 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001883 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001884 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001885 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001886
Ruben Brunkcc776712015-02-17 20:18:47 -08001887 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001888}
1889
Ruben Brunkcc776712015-02-17 20:18:47 -08001890void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001891 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001892
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001894 auto clientDescriptor =
1895 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001896 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001897 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1898
1899 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001900 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001901
1902 if (evicted.size() > 0) {
1903 // This should never happen - clients should already have been removed in disconnect
1904 for (auto& i : evicted) {
1905 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001906 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001907 }
1908
1909 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1910 __FUNCTION__);
1911 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001912
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001913 if (flags::camera_multi_client()) {
1914 sp<BasicClient> clientSp = clientDescriptor->getValue();
1915 auto primaryClient = mActiveClientManager.getPrimaryClient(desc->getKey());
1916 if (primaryClient == nullptr) {
1917 // There is no primary client yet. Assign this first client as
1918 // primary
1919 clientSp->setPrimaryClient(true);
1920 } else {
1921 // There is already primary client. If the incoming client has a
1922 // higher priority than the existing primary, then assign incoming
1923 // client as primary and change the existing client to secondary.
1924 // Otherwise incoming client is secondary client.
1925 if (clientDescriptor->getPriority() <= primaryClient->getPriority()) {
1926 clientSp->setPrimaryClient(true);
1927 primaryClient->getValue()->setPrimaryClient(false);
1928 primaryClient->getValue()->notifyClientSharedAccessPriorityChanged(false);
1929 } else {
1930 clientSp->setPrimaryClient(false);
1931 }
1932 }
1933 }
1934
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001935 // And register a death notification for the client callback. Do
1936 // this last to avoid Binder policy where a nested Binder
1937 // transaction might be pre-empted to service the client death
1938 // notification if the client process dies before linkToDeath is
1939 // invoked.
1940 sp<IBinder> remoteCallback = client->getRemote();
1941 if (remoteCallback != nullptr) {
1942 remoteCallback->linkToDeath(this);
1943 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001944}
1945
Austin Borgered99f642023-06-01 16:51:35 -07001946status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1947 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1948 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001949 bool sharedMode,
Ruben Brunkcc776712015-02-17 20:18:47 -08001950 /*out*/
1951 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001952 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001953 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001954 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001955 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001956 DescriptorPtr clientDescriptor;
1957 {
1958 if (effectiveApiLevel == API_1) {
1959 // If we are using API1, any existing client for this camera ID with the same remote
1960 // should be returned rather than evicted to allow MediaRecorder to work properly.
1961
1962 auto current = mActiveClientManager.get(cameraId);
1963 if (current != nullptr) {
1964 auto clientSp = current->getValue();
1965 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001966 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001967 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001968 " API level, evicting prior client...");
1969 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001970 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001971 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001972 *client = clientSp;
1973 return NO_ERROR;
1974 }
1975 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001976 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001977 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001978
Ruben Brunkcc776712015-02-17 20:18:47 -08001979 // Get state for the given cameraId
1980 auto state = getCameraState(cameraId);
1981 if (state == nullptr) {
1982 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001983 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001984 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001985 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001986 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001987
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001988 sp<IServiceManager> sm = defaultServiceManager();
1989 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001990 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001991 // If processinfo service is not available and the client is automotive privileged
1992 // client used for safety critical uses cases such as rear-view and surround-view which
1993 // needs to be available before android boot completes, then use the hardcoded values
1994 // for the process state and priority score. As this scenario is before android system
1995 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1996 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1997 // visible on the top.
1998 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1999 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2000 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002001 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient,
2002 sharedMode);
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002003 } else {
2004 // Get current active client PIDs
2005 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2006 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002007
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002008 std::vector<int> priorityScores(ownerPids.size());
2009 std::vector<int> states(ownerPids.size());
2010
2011 // Get priority scores of all active PIDs
2012 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2013 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2014 if (err != OK) {
2015 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2016 return err;
2017 }
2018
2019 // Update all active clients' priorities
2020 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2021 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2022 pidToPriorityMap.emplace(ownerPids[i],
2023 resource_policy::ClientPriority(priorityScores[i], states[i],
2024 /* isVendorClient won't get copied over*/ false,
2025 /* oomScoreOffset won't get copied over*/ 0));
2026 }
2027 mActiveClientManager.updatePriorities(pidToPriorityMap);
2028
2029 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2030 int32_t actualState = states[states.size() - 1];
2031
2032 // Make descriptor for incoming client. We store the oomScoreOffset
2033 // since we might need it later on new handleEvictionsLocked and
2034 // ProcessInfoService would not take that into account.
2035 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2036 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2037 state->getConflicting(), actualScore, clientPid, actualState,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002038 oomScoreOffset, systemNativeClient, sharedMode);
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002039 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002040
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002041 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2042
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 // Find clients that would be evicted
2044 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2045
2046 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2047 // background, so we cannot do evictions
2048 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2049 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2050 " priority).", clientPid);
2051
2052 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002053 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002054 auto incompatibleClients =
2055 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2056
Austin Borgered99f642023-06-01 16:51:35 -07002057 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2058 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2059 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002060 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002061
2062 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002063 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002064 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002065 i->getKey().c_str(),
2066 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002067 i->getOwnerId(), i->getPriority().getScore(),
2068 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002069 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002070 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2071 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002072 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002073 }
2074
2075 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002076 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002077 mEventLog.add(msg);
2078
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002079 auto current = mActiveClientManager.get(cameraId);
2080 if (current != nullptr) {
2081 return -EBUSY; // CAMERA_IN_USE
2082 } else {
2083 return -EUSERS; // MAX_CAMERAS_IN_USE
2084 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002085 }
2086
2087 for (auto& i : evicted) {
2088 sp<BasicClient> clientSp = i->getValue();
2089 if (clientSp.get() == nullptr) {
2090 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2091
2092 // TODO: Remove this
2093 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2094 __FUNCTION__);
2095 mActiveClientManager.remove(i);
2096 continue;
2097 }
2098
2099 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002100 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002101 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002102
Ruben Brunkcc776712015-02-17 20:18:47 -08002103 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002104 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002105 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2106 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002107 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002108 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002109 i->getPriority().getState(), cameraId.c_str(),
2110 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002111 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002112
2113 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002114 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002115 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002116 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002117 }
2118
Ruben Brunkcc776712015-02-17 20:18:47 -08002119 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2120 // other clients from connecting in mServiceLockWrapper if held
2121 mServiceLock.unlock();
2122
2123 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002124 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002125
2126 // Destroy evicted clients
2127 for (auto& i : evictedClients) {
2128 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002129 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002130 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002131
Austin Borger22c5c852024-03-08 13:31:36 -08002132 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002133
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002134 for (const auto& i : evictedClients) {
2135 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002136 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002137 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2138 if (ret == TIMED_OUT) {
2139 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002140 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2141 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002142 return -EBUSY;
2143 }
2144 if (ret != NO_ERROR) {
2145 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002146 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2147 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002148 return ret;
2149 }
2150 }
2151
2152 evictedClients.clear();
2153
Ruben Brunkcc776712015-02-17 20:18:47 -08002154 // Once clients have been disconnected, relock
2155 mServiceLock.lock();
2156
2157 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2158 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2159 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002160 }
2161
Ruben Brunkcc776712015-02-17 20:18:47 -08002162 *partial = clientDescriptor;
2163 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002164}
2165
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002166Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002167 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002168 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002169 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002170 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002171 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002172 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002173 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002174 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002175 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002176 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002177 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002178
Austin Borger65e64642024-06-11 15:58:23 -07002179 std::string cameraIdStr =
2180 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002181 if (cameraIdStr.empty()) {
2182 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002183 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002184 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2185 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2186 }
malikakashedb38962023-09-06 00:03:35 +00002187
Austin Borger7d2b9232024-07-22 14:17:14 -07002188 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2189 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002190
Austin Borger95a00152024-09-23 17:20:24 -07002191 AttributionSourceState resolvedClientAttribution(clientAttribution);
2192 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraIdStr);
2193 if (!ret.isOk()) {
2194 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002195 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002196 toStdString(ret.toString8()));
2197 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002198 }
2199
Austin Borger95a00152024-09-23 17:20:24 -07002200 const int clientPid = resolvedClientAttribution.pid;
2201 const int clientUid = resolvedClientAttribution.uid;
2202 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2203
2204 logConnectionAttempt(clientPid, clientPackageName, cameraIdStr, API_1);
Austin Borgerb01a8702024-07-22 16:20:34 -07002205
Ruben Brunkcc776712015-02-17 20:18:47 -08002206 sp<Client> client = nullptr;
Austin Borger23694432024-10-07 19:28:01 -07002207 ret = connectHelper<ICameraClient, Client>(
2208 cameraClient, cameraIdStr, api1CameraId, resolvedClientAttribution,
2209 /*systemNativeClient*/ false, API_1,
2210 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, rotationOverride,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002211 forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*sharedMode*/false,
2212 /*isVendorClient*/ false, /*out*/ client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002213
Biswarup Pal37a75182024-01-16 15:53:35 +00002214 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002215 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002216 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002217 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002218 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002219 }
2220
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002221 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002222
2223 const sp<IServiceManager> sm(defaultServiceManager());
2224 const auto& mActivityManager = getActivityManager();
2225 if (mActivityManager) {
2226 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002227 getCallingUid(),
2228 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002229 }
2230
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002231 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002232}
2233
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002234bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2235 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002236 // If the client is not a vendor client, don't add listener if
2237 // a) the camera is a publicly hidden secure camera OR
2238 // b) the camera is a system only camera and the client doesn't
2239 // have android.permission.SYSTEM_CAMERA permissions.
2240 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2241 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002242 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002243 return true;
2244 }
2245 return false;
2246}
2247
Austin Borgered99f642023-06-01 16:51:35 -07002248bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002249 // Rules for rejection:
2250 // 1) If cameraserver tries to access this camera device, accept the
2251 // connection.
2252 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002253 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002254 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2255 // and the serving thread is a non hwbinder thread, the client must have
2256 // android.permission.SYSTEM_CAMERA permissions to connect.
2257
Austin Borger22c5c852024-03-08 13:31:36 -08002258 int cPid = getCallingPid();
2259 int cUid = getCallingUid();
2260 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002261 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2262 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002263 // This isn't a known camera ID, so it's not a system camera
2264 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2265 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002266 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002267
2268 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002269 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002270 return false;
2271 }
2272 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002273 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002274 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2275 return true;
2276 }
2277 // (3) Here we only check for permissions if it is a system only camera device. This is since
2278 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2279 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2280 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002281 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002282 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002283 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2284 cameraId.c_str());
2285 return true;
2286 }
2287
2288 return false;
2289}
2290
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002291Status CameraService::connectDevice(
2292 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002293 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002294 int oomScoreOffset, int targetSdkVersion,
2295 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002296 bool sharedMode,
2297 /*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {
2298 return connectDeviceImpl(cameraCb, unresolvedCameraId, oomScoreOffset, targetSdkVersion,
2299 rotationOverride, clientAttribution, devicePolicy, sharedMode,
2300 /*isVendorClient*/false, device);
2301}
2302
2303Status CameraService::connectDeviceVendor(
2304 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
2305 const std::string& unresolvedCameraId,
2306 int oomScoreOffset, int targetSdkVersion,
2307 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
2308 bool sharedMode,
2309 /*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {
2310 return connectDeviceImpl(cameraCb, unresolvedCameraId, oomScoreOffset, targetSdkVersion,
2311 rotationOverride, clientAttribution, devicePolicy, sharedMode,
2312 /*isVendorClient*/true, device);
2313}
2314
2315Status CameraService::connectDeviceImpl(
2316 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
2317 const std::string& unresolvedCameraId,
2318 int oomScoreOffset, int targetSdkVersion,
2319 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
2320 bool sharedMode, bool isVendorClient,
2321 /*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002322 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002323 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002324 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002325 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002326 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002327 int callingPid = getCallingPid();
2328 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002329 bool systemNativeClient = false;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002330 AttributionSourceState resolvedClientAttribution(clientAttribution);
Austin Borger7d2b9232024-07-22 14:17:14 -07002331 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002332 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002333 clientPackageNameMaybe = systemClient;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002334 // Pass in packageName since AttributionAndPermissionUtils can't resolve vndk clients.
2335 resolvedClientAttribution.packageName = clientPackageNameMaybe;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002336 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002337 }
Austin Borger249e6592024-03-10 22:28:11 -07002338
Austin Borger65e64642024-06-11 15:58:23 -07002339 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2340 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002341 if (!cameraIdOptional.has_value()) {
2342 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002343 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002344 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2345 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2346 }
2347 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002348
Austin Borger7d2b9232024-07-22 14:17:14 -07002349 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002350
Austin Borger2a3f9a72024-11-07 12:24:49 -08002351 if (!flags::data_delivery_permission_checks()) {
Austin Borger95a00152024-09-23 17:20:24 -07002352 resolvedClientAttribution.pid = USE_CALLING_PID;
2353 }
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002354
Austin Borger95a00152024-09-23 17:20:24 -07002355 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraId);
2356 if (!ret.isOk()) {
2357 logRejected(cameraId, getCallingPid(), clientAttribution.packageName.value_or(""),
2358 toStdString(ret.toString8()));
2359 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002360 }
2361
Austin Borger95a00152024-09-23 17:20:24 -07002362 const int clientPid = resolvedClientAttribution.pid;
2363 const int clientUid = resolvedClientAttribution.uid;
2364 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2365 userid_t clientUserId = multiuser_get_user_id(resolvedClientAttribution.uid);
Austin Borgerb01a8702024-07-22 16:20:34 -07002366
Austin Borger95a00152024-09-23 17:20:24 -07002367 logConnectionAttempt(clientPid, clientPackageName, cameraId, API_2);
Austin Borgerb01a8702024-07-22 16:20:34 -07002368
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002369 if (oomScoreOffset < 0) {
Austin Borger95a00152024-09-23 17:20:24 -07002370 std::string msg = fmt::sprintf(
2371 "Cannot increase the priority of a client %s pid %d for "
2372 "camera id %s",
2373 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002374 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2375 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002376 }
2377
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002378 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2379 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002380 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2381 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002382 std::string msg = "Camera disabled by device policy";
2383 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2384 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002385 }
2386
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002387 // enforce system camera permissions
Austin Borger95a00152024-09-23 17:20:24 -07002388 if (oomScoreOffset > 0 && !hasPermissionsForSystemCamera(cameraId, clientPid, callingUid) &&
2389 !isTrustedCallingUid(callingUid)) {
2390 std::string msg = fmt::sprintf(
2391 "Cannot change the priority of a client %s pid %d for "
2392 "camera id %s without SYSTEM_CAMERA permissions",
2393 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002394 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2395 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002396 }
2397
Austin Borger95a00152024-09-23 17:20:24 -07002398 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks, CameraDeviceClient>(
Austin Borger23694432024-10-07 19:28:01 -07002399 cameraCb, cameraId, /*api1CameraId*/ -1, resolvedClientAttribution, systemNativeClient,
2400 API_2, /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002401 /*forceSlowJpegMode*/ false, unresolvedCameraId, isNonSystemNdk, sharedMode,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002402 isVendorClient, /*out*/ client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002403
Biswarup Pal37a75182024-01-16 15:53:35 +00002404 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002405 logRejected(cameraId, clientPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002406 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002407 }
2408
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002409 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002410 Mutex::Autolock lock(mServiceLock);
2411
2412 // Clear the previous cached logs and reposition the
2413 // file offset to beginning of the file to log new data.
2414 // If either truncate or lseek fails, close the previous file and create a new one.
2415 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2416 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2417 // Close the previous memfd.
2418 close(mMemFd);
2419 // If failure to wipe the data, then create a new file and
2420 // assign the new value to mMemFd.
2421 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2422 if (mMemFd == -1) {
2423 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2424 }
2425 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002426 const sp<IServiceManager> sm(defaultServiceManager());
2427 const auto& mActivityManager = getActivityManager();
2428 if (mActivityManager) {
2429 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002430 callingUid,
2431 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002432 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002433 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002434}
2435
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002436bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2437 int callingPid, int callingUid) {
2438 if (!isAutomotiveDevice()) {
2439 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2440 }
2441
2442 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2443 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2444 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2445 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2446 "using camera %s", callingUid, cam_id.c_str());
2447 return false;
2448 }
2449
2450 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2451 return true;
2452 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2453 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002454 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2455 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002456 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2457 return false;
2458 } else {
2459 return true;
2460 }
2461 }
2462 return false;
2463}
2464
Austin Borger7d2b9232024-07-22 14:17:14 -07002465void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
Austin Borger95a00152024-09-23 17:20:24 -07002466 const std::string& cameraId,
2467 apiLevel effectiveApiLevel) const {
Austin Borger7d2b9232024-07-22 14:17:14 -07002468 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borger95a00152024-09-23 17:20:24 -07002469 "Camera API version %d",
2470 clientPid, clientPackageName.c_str(), cameraId.c_str(),
2471 static_cast<int>(effectiveApiLevel));
Austin Borger7d2b9232024-07-22 14:17:14 -07002472}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002473
Austin Borger23694432024-10-07 19:28:01 -07002474template <class CALLBACK, class CLIENT>
Austin Borger7d2b9232024-07-22 14:17:14 -07002475Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
Austin Borger23694432024-10-07 19:28:01 -07002476 int api1CameraId,
2477 const AttributionSourceState& clientAttribution,
2478 bool systemNativeClient, apiLevel effectiveApiLevel,
2479 bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2480 int rotationOverride, bool forceSlowJpegMode,
2481 const std::string& originalCameraId, bool isNonSystemNdk,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002482 bool sharedMode, bool isVendorClient,
2483 /*out*/ sp<CLIENT>& device) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002484 binder::Status ret = binder::Status::ok();
2485
Shuzhen Wang316781a2020-08-18 18:11:01 -07002486 nsecs_t openTimeNs = systemTime();
2487
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002488 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002489 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002490 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002491
Austin Borger23694432024-10-07 19:28:01 -07002492 const std::string clientPackageName =
2493 clientAttribution.packageName.value_or(kUnknownPackageName);
2494
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002495 {
2496 // Acquire mServiceLock and prevent other clients from connecting
2497 std::unique_ptr<AutoConditionLock> lock =
2498 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2499
2500 if (lock == nullptr) {
Austin Borger23694432024-10-07 19:28:01 -07002501 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting).",
2502 clientAttribution.pid);
2503 return STATUS_ERROR_FMT(
2504 ERROR_MAX_CAMERAS_IN_USE,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002505 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borger23694432024-10-07 19:28:01 -07002506 cameraId.c_str(), clientPackageName.c_str(), clientAttribution.pid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002507 }
2508
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002509 // Enforce client permissions and do basic validity checks
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002510 if (!(ret = validateConnectLocked(cameraId, clientAttribution, sharedMode)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002511 return ret;
2512 }
2513
2514 // Check the shim parameters after acquiring lock, if they have already been updated and
2515 // we were doing a shim update, return immediately
2516 if (shimUpdateOnly) {
2517 auto cameraState = getCameraState(cameraId);
2518 if (cameraState != nullptr) {
2519 if (!cameraState->getShimParams().isEmpty()) return ret;
2520 }
2521 }
2522
2523 status_t err;
2524
2525 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002526 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger23694432024-10-07 19:28:01 -07002527 if ((err = handleEvictionsLocked(
2528 cameraId, clientAttribution.pid, effectiveApiLevel,
2529 IInterface::asBinder(cameraCb),
2530 clientAttribution.packageName.value_or(kUnknownPackageName), oomScoreOffset,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002531 systemNativeClient, sharedMode, /*out*/ &clientTmp,
Austin Borger23694432024-10-07 19:28:01 -07002532 /*out*/ &partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002533 switch (err) {
2534 case -ENODEV:
2535 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2536 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002537 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002538 case -EBUSY:
2539 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2540 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002541 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002542 case -EUSERS:
2543 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2544 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002545 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002546 default:
2547 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2548 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002549 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002550 }
2551 }
2552
2553 if (clientTmp.get() != nullptr) {
2554 // Handle special case for API1 MediaRecorder where the existing client is returned
2555 device = static_cast<CLIENT*>(clientTmp.get());
2556 return ret;
2557 }
2558
2559 // give flashlight a chance to close devices if necessary.
2560 mFlashlight->prepareDeviceOpen(cameraId);
2561
Austin Borger18b30a72022-10-27 12:20:29 -07002562 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002563 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002564 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002565 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002566 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002567 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002568 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002569 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002570 }
2571
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002572 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002573 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002574 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002575
Austin Borger6e831c42024-07-22 13:07:56 -07002576 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2577 // that's connected to camera service directly.
Austin Borger2e772b82024-10-11 16:09:57 -07002578 if (!(ret = makeClient(this, cameraCb, clientAttribution, getCallingPid(),
2579 systemNativeClient, cameraId, api1CameraId, facing, orientation,
2580 getpid(), deviceVersionAndTransport, effectiveApiLevel,
2581 overrideForPerfClass, rotationOverride, forceSlowJpegMode,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002582 originalCameraId, sharedMode, isVendorClient,
Austin Borger23694432024-10-07 19:28:01 -07002583 /*out*/ &tmp))
2584 .isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002585 return ret;
2586 }
2587 client = static_cast<CLIENT*>(tmp.get());
2588
2589 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2590 __FUNCTION__);
2591
Austin Borgered99f642023-06-01 16:51:35 -07002592 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002593 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002594 if (err != OK) {
2595 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002596 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002597 mServiceLock.unlock();
2598 client->disconnect();
2599 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002600 switch(err) {
2601 case BAD_VALUE:
2602 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002603 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002604 case -EBUSY:
2605 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002606 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002607 case -EUSERS:
2608 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2609 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002610 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002611 case PERMISSION_DENIED:
2612 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002613 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002614 case -EACCES:
2615 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002616 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002617 case -ENODEV:
2618 default:
2619 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002620 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002621 strerror(-err), err);
2622 }
2623 }
2624
2625 // Update shim paremeters for legacy clients
2626 if (effectiveApiLevel == API_1) {
2627 // Assume we have always received a Client subclass for API1
2628 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2629 String8 rawParams = shimClient->getParameters();
2630 CameraParameters params(rawParams);
2631
2632 auto cameraState = getCameraState(cameraId);
2633 if (cameraState != nullptr) {
2634 cameraState->setShimParams(params);
2635 } else {
2636 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002637 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002638 }
2639 }
2640
Ravneetaeb20dc2022-03-30 05:33:03 +00002641 // Enable/disable camera service watchdog
2642 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2643
Emilian Peev6d45db82024-01-18 20:11:54 +00002644 CameraMetadata chars;
2645 bool rotateAndCropSupported = true;
2646 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002647 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002648 if (err == OK) {
2649 auto availableRotateCropEntry = chars.find(
2650 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2651 if (availableRotateCropEntry.count <= 1) {
2652 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002653 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002654 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002655 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2656 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002657 }
2658
Emilian Peev6d45db82024-01-18 20:11:54 +00002659 if (rotateAndCropSupported) {
2660 // Set rotate-and-crop override behavior
2661 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2662 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002663 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2664 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002665 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2666 switch (portraitRotation) {
2667 case 90:
2668 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2669 break;
2670 case 180:
2671 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2672 break;
2673 case 270:
2674 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2675 break;
2676 default:
2677 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2678 break;
2679 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002680 // Here we're communicating to the client the chosen rotate
2681 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002682 client->setRotateAndCropOverride(rotateAndCropMode);
2683 } else {
2684 client->setRotateAndCropOverride(
Austin Borger23694432024-10-07 19:28:01 -07002685 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2686 clientPackageName, facing,
2687 multiuser_get_user_id(clientAttribution.uid)));
Emilian Peev6d45db82024-01-18 20:11:54 +00002688 }
2689 }
2690
2691 bool autoframingSupported = true;
2692 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2693 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2694 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2695 autoframingSupported = false;
2696 }
2697
2698 if (autoframingSupported) {
2699 // Set autoframing override behaviour
2700 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2701 client->setAutoframingOverride(mOverrideAutoframingMode);
2702 } else {
2703 client->setAutoframingOverride(
2704 mCameraServiceProxyWrapper->getAutoframingOverride(
2705 clientPackageName));
2706 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002707 }
2708
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002709 bool isCameraPrivacyEnabled;
2710 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002711 // Set camera muting behavior.
Austin Borger23694432024-10-07 19:28:01 -07002712 isCameraPrivacyEnabled =
2713 this->isCameraPrivacyEnabled(toString16(client->getPackageName()), cameraId,
2714 clientAttribution.pid, clientAttribution.uid);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002715 } else {
2716 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002717 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002718 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002719
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002720 if (client->supportsCameraMute()) {
2721 client->setCameraMute(
2722 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2723 } else if (isCameraPrivacyEnabled) {
2724 // no camera mute supported, but privacy is on! => disconnect
2725 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2726 client->getPackageName().c_str(), cameraId.c_str());
2727 // Do not hold mServiceLock while disconnecting clients, but
2728 // retain the condition blocking other clients from connecting
2729 // in mServiceLockWrapper if held.
2730 mServiceLock.unlock();
2731 // Clear caller identity temporarily so client disconnect PID
2732 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002733 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002734 // Note AppOp to trigger the "Unblock" dialog
2735 client->noteAppOp();
2736 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002737 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002738 // Reacquire mServiceLock
2739 mServiceLock.lock();
2740
2741 return STATUS_ERROR_FMT(ERROR_DISABLED,
2742 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002743 }
2744
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002745 if (shimUpdateOnly) {
2746 // If only updating legacy shim parameters, immediately disconnect client
2747 mServiceLock.unlock();
2748 client->disconnect();
2749 mServiceLock.lock();
2750 } else {
2751 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002752 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002753 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002754
2755 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002756 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002757 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002758 } // lock is destroyed, allow further connect calls
2759
2760 // Important: release the mutex here so the client can call back into the service from its
2761 // destructor (can be at the end of the call)
2762 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002763
2764 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002765 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002766 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002767
Cliff Wud3a05312021-04-26 23:07:31 +08002768 {
2769 Mutex::Autolock lock(mInjectionParametersLock);
2770 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2771 mInjectionInitPending = false;
2772 status_t res = NO_ERROR;
2773 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2774 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002775 sp<BasicClient> clientSp = clientDescriptor->getValue();
2776 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2777 if(res != OK) {
2778 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2779 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002780 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002781 }
2782 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002783 if (res != OK) {
2784 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2785 }
2786 } else {
2787 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002788 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002789 res = NO_INIT;
2790 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2791 }
2792 }
2793 }
2794
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002795 return ret;
2796}
2797
Austin Borgered99f642023-06-01 16:51:35 -07002798status_t CameraService::addOfflineClient(const std::string &cameraId,
2799 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002800 if (offlineClient.get() == nullptr) {
2801 return BAD_VALUE;
2802 }
2803
2804 {
2805 // Acquire mServiceLock and prevent other clients from connecting
2806 std::unique_ptr<AutoConditionLock> lock =
2807 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2808
2809 if (lock == nullptr) {
2810 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
Austin Borger2e772b82024-10-11 16:09:57 -07002811 , __FUNCTION__, offlineClient->getClientCallingPid());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002812 return TIMED_OUT;
2813 }
2814
2815 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2816 if (onlineClientDesc.get() == nullptr) {
2817 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2818 cameraId.c_str());
2819 return BAD_VALUE;
2820 }
2821
2822 // Offline clients do not evict or conflict with other online devices. Resource sharing
2823 // conflicts are handled by the camera provider which will either succeed or fail before
2824 // reaching this method.
2825 const auto& onlinePriority = onlineClientDesc->getPriority();
2826 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2827 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002828 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002829 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002830 // native clients don't have offline processing support.
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002831 /*ommScoreOffset*/ 0, /*systemNativeClient*/false, /*sharedMode*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002832 if (offlineClientDesc == nullptr) {
2833 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2834 return BAD_VALUE;
2835 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002836
2837 // Allow only one offline device per camera
2838 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2839 if (!incompatibleClients.empty()) {
2840 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2841 return BAD_VALUE;
2842 }
2843
Austin Borgered99f642023-06-01 16:51:35 -07002844 std::string monitorTags = isClientWatched(offlineClient.get())
2845 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002846 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002847 if (err != OK) {
2848 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2849 return err;
2850 }
2851
2852 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2853 if (evicted.size() > 0) {
2854 for (auto& i : evicted) {
2855 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002856 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002857 }
2858
2859 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2860 "properly", __FUNCTION__);
2861
2862 return BAD_VALUE;
2863 }
2864
2865 logConnectedOffline(offlineClientDesc->getKey(),
2866 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002867 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002868
2869 sp<IBinder> remoteCallback = offlineClient->getRemote();
2870 if (remoteCallback != nullptr) {
2871 remoteCallback->linkToDeath(this);
2872 }
2873 } // lock is destroyed, allow further connect calls
2874
2875 return OK;
2876}
2877
Austin Borgered99f642023-06-01 16:51:35 -07002878Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002879 int32_t torchStrength, const sp<IBinder>& clientBinder,
2880 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002881 Mutex::Autolock lock(mServiceLock);
2882
2883 ATRACE_CALL();
2884 if (clientBinder == nullptr) {
2885 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2886 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2887 "Torch client binder in null.");
2888 }
2889
Austin Borger22c5c852024-03-08 13:31:36 -08002890 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002891 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2892 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002893 if (!cameraIdOptional.has_value()) {
2894 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002895 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002896 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2897 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2898 }
2899 std::string cameraId = cameraIdOptional.value();
2900
Austin Borgered99f642023-06-01 16:51:35 -07002901 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002902 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002903 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002904 }
2905
2906 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002907 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002908 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002909 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002910 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002911 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002912 }
2913
2914 StatusInternal cameraStatus = state->getStatus();
2915 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2916 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002917 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 (int)cameraStatus);
2919 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002920 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 }
2922
2923 {
2924 Mutex::Autolock al(mTorchStatusMutex);
2925 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002926 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 if (err != OK) {
2928 if (err == NAME_NOT_FOUND) {
2929 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002930 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002931 }
2932 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002933 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002934 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2935 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002936 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002937 }
2938
2939 if (status == TorchModeStatus::NOT_AVAILABLE) {
2940 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2941 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002942 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002943 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2944 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002945 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002946 } else {
2947 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002948 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002949 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2950 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002951 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002952 }
2953 }
2954 }
2955
2956 {
2957 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002958 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002959 }
2960 // Check if the current torch strength level is same as the new one.
2961 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002962 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002963
Austin Borgered99f642023-06-01 16:51:35 -07002964 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002965
2966 if (err != OK) {
2967 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002968 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002969 switch (err) {
2970 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002971 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2972 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002973 errorCode = ERROR_ILLEGAL_ARGUMENT;
2974 break;
2975 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002976 msg = fmt::sprintf("Camera \"%s\" is in use",
2977 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002978 errorCode = ERROR_CAMERA_IN_USE;
2979 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002980 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002981 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002982 "valid range.", torchStrength);
2983 errorCode = ERROR_ILLEGAL_ARGUMENT;
2984 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002985 default:
Austin Borgered99f642023-06-01 16:51:35 -07002986 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002987 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002988 }
Austin Borgered99f642023-06-01 16:51:35 -07002989 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2990 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002991 }
2992
2993 {
2994 // update the link to client's death
2995 // Store the last client that turns on each camera's torch mode.
2996 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002997 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002998 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002999 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003000 } else {
3001 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3002 mTorchClientMap.replaceValueAt(index, clientBinder);
3003 }
3004 clientBinder->linkToDeath(this);
3005 }
3006
Austin Borger22c5c852024-03-08 13:31:36 -08003007 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003008 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003009 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003010 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003011 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003012 }
3013 return Status::ok();
3014}
3015
malikakash73125c62023-07-21 22:44:34 +00003016Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07003017 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
3018 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003019 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003020
3021 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003022 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003023 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003024 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3025 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003026 }
3027
Austin Borger22c5c852024-03-08 13:31:36 -08003028 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07003029 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
3030 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00003031 if (!cameraIdOptional.has_value()) {
3032 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003033 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00003034 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3035 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3036 }
3037 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003038
Austin Borgered99f642023-06-01 16:51:35 -07003039 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003040 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003041 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003042 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003043 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003044 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003045 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003046 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003047 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003048 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003049 }
3050
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003051 StatusInternal cameraStatus = state->getStatus();
3052 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003053 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003054 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3055 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003056 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003057 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003058 }
3059
3060 {
3061 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003062 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003063 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003064 if (err != OK) {
3065 if (err == NAME_NOT_FOUND) {
3066 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003067 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003068 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003069 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003070 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003072 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003073 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003074 }
3075
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003076 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003077 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003078 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003079 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3081 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003082 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003083 } else {
3084 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003085 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003086 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3087 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003088 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003089 }
3090 }
3091 }
3092
Ruben Brunk99e69712015-05-26 17:25:07 -07003093 {
3094 // Update UID map - this is used in the torch status changed callbacks, so must be done
3095 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003096 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003097 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003098 }
3099
Austin Borgered99f642023-06-01 16:51:35 -07003100 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003101
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003102 if (err != OK) {
3103 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003104 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003105 switch (err) {
3106 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003107 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3108 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003109 errorCode = ERROR_ILLEGAL_ARGUMENT;
3110 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003111 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003112 msg = fmt::sprintf("Camera \"%s\" is in use",
3113 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003114 errorCode = ERROR_CAMERA_IN_USE;
3115 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003116 default:
Austin Borgered99f642023-06-01 16:51:35 -07003117 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003118 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003119 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003120 errorCode = ERROR_INVALID_OPERATION;
3121 }
Austin Borgered99f642023-06-01 16:51:35 -07003122 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3123 logServiceError(msg, errorCode);
3124 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003125 }
3126
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003127 {
3128 // update the link to client's death
3129 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003130 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003131 if (enabled) {
3132 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003133 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003134 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003135 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003136 mTorchClientMap.replaceValueAt(index, clientBinder);
3137 }
3138 clientBinder->linkToDeath(this);
3139 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003140 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003141 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003142 }
3143
Austin Borger22c5c852024-03-08 13:31:36 -08003144 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003145 std::string torchState = enabled ? "on" : "off";
3146 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3147 torchState.c_str(), clientPid);
3148 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003149 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003150}
3151
Austin Borgered99f642023-06-01 16:51:35 -07003152void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3153 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3154 mTorchUidMap[cameraId].first = uid;
3155 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003156 } else {
3157 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003158 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003159 }
3160}
3161
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003162Status CameraService::notifySystemEvent(int32_t eventId,
3163 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003164 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003165 const int selfPid = getpid();
3166
3167 // Permission checks
3168 if (pid != selfPid) {
3169 // Ensure we're being called by system_server, or similar process with
3170 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003171 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003172 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003173 ALOGE("Permission Denial: cannot send updates to camera service about system"
3174 " events from pid=%d, uid=%d", pid, uid);
3175 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003176 "No permission to send updates to camera service about system events"
3177 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003178 }
3179 }
3180
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003181 ATRACE_CALL();
3182
Ruben Brunk36597b22015-03-20 22:15:57 -07003183 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003184 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003185 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003186 // from a system server crash
3187 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003188 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003189 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003190 break;
3191 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003192 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3193 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003194 if (args.size() != 1) {
3195 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3196 "USB Device Event requires 1 argument");
3197 }
3198
Valentin Iftime29e2e152021-08-13 15:17:33 +02003199 // Notify CameraProviderManager for lazy HALs
3200 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3201 std::to_string(args[0]));
3202 break;
3203 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003204 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003205 default: {
3206 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3207 eventId);
3208 break;
3209 }
3210 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003211 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003212}
3213
Emilian Peev53722fa2019-02-22 17:47:20 -08003214void CameraService::notifyMonitoredUids() {
3215 Mutex::Autolock lock(mStatusListenerLock);
3216
3217 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003218 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003219 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3220 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003221 }
3222}
3223
Austin Borgerdddb7552023-03-30 17:53:01 -07003224void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3225 Mutex::Autolock lock(mStatusListenerLock);
3226
3227 for (const auto& it : mListenerList) {
3228 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3229 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3230 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3231 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3232 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3233 }
3234 }
3235}
3236
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003237Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003238 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003239 const int selfPid = getpid();
3240
3241 // Permission checks
3242 if (pid != selfPid) {
3243 // Ensure we're being called by system_server, or similar process with
3244 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003245 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003246 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003247 ALOGE("Permission Denial: cannot send updates to camera service about device"
3248 " state changes from pid=%d, uid=%d", pid, uid);
3249 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3250 "No permission to send updates to camera service about device state"
3251 " changes from pid=%d, uid=%d", pid, uid);
3252 }
3253 }
3254
3255 ATRACE_CALL();
3256
Austin Borger18b30a72022-10-27 12:20:29 -07003257 {
3258 Mutex::Autolock lock(mServiceLock);
3259 mDeviceState = newState;
3260 }
3261
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003262 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003263
3264 return Status::ok();
3265}
3266
Emilian Peev8b64f282021-03-25 16:49:57 -07003267Status CameraService::notifyDisplayConfigurationChange() {
3268 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003269 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003270 const int selfPid = getpid();
3271
3272 // Permission checks
3273 if (callingPid != selfPid) {
3274 // Ensure we're being called by system_server, or similar process with
3275 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003276 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003277 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003278 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3279 " changes from pid=%d, uid=%d", callingPid, uid);
3280 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3281 "No permission to send updates to camera service about orientation"
3282 " changes from pid=%d, uid=%d", callingPid, uid);
3283 }
3284 }
3285
3286 Mutex::Autolock lock(mServiceLock);
3287
3288 // Don't do anything if rotate-and-crop override via cmd is active
3289 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3290
3291 const auto clients = mActiveClientManager.getAll();
3292 for (auto& current : clients) {
3293 if (current != nullptr) {
3294 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003295 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3296 basicClient->setRotateAndCropOverride(
3297 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3298 basicClient->getPackageName(),
3299 basicClient->getCameraFacing(),
3300 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003301 }
3302 }
3303 }
3304
3305 return Status::ok();
3306}
3307
3308Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003309 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3310 ATRACE_CALL();
3311 if (!concurrentCameraIds) {
3312 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3313 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3314 }
3315
3316 if (!mInitialized) {
3317 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003318 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003319 return STATUS_ERROR(ERROR_DISCONNECTED,
3320 "Camera subsystem is not available");
3321 }
3322 // First call into the provider and get the set of concurrent camera
3323 // combinations
3324 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003325 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003326 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003327 std::vector<std::pair<std::string, int32_t>> validCombination;
3328 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003329 for (auto &cameraId : combination) {
3330 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003331 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003332 if (state == nullptr) {
3333 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3334 continue;
3335 }
3336 StatusInternal status = state->getStatus();
3337 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3338 continue;
3339 }
Austin Borgered99f642023-06-01 16:51:35 -07003340 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003341 continue;
3342 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003343 auto [cameraOwnerDeviceId, mappedCameraId] =
3344 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3345 if (firstDeviceId == kInvalidDeviceId) {
3346 firstDeviceId = cameraOwnerDeviceId;
3347 } else if (firstDeviceId != cameraOwnerDeviceId) {
3348 // Found an invalid combination which contains cameras with different device id's,
3349 // hence discard it.
3350 validCombination.clear();
3351 break;
3352 }
3353 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003354 }
3355 if (validCombination.size() != 0) {
3356 concurrentCameraIds->push_back(std::move(validCombination));
3357 }
3358 }
3359 return Status::ok();
3360}
3361
3362Status CameraService::isConcurrentSessionConfigurationSupported(
3363 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003364 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003365 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003366 if (!isSupported) {
3367 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3368 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3369 }
3370
3371 if (!mInitialized) {
3372 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3373 return STATUS_ERROR(ERROR_DISCONNECTED,
3374 "Camera subsystem is not available");
3375 }
3376
Biswarup Pal7d072862024-04-17 15:24:47 +00003377 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3378 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003379 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3380 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003381 if (!cameraIdOptional.has_value()) {
3382 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003383 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003384 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3385 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3386 }
3387 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3388 }
3389
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003390 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003391 int callingPid = getCallingPid();
3392 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003393 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003394 hasPermissionsForCamera(callingPid, callingUid,
3395 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003396 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003397 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003398 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3399 "android.permission.CAMERA needed to call"
3400 "isConcurrentSessionConfigurationSupported");
3401 }
3402
3403 status_t res =
3404 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003405 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3406 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003407 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003408 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003409 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003410 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3411 "support %s (%d)", strerror(-res), res);
3412 }
3413 return Status::ok();
3414}
3415
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003416Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3417 /*out*/
3418 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003419 return addListenerHelper(listener, cameraStatuses);
3420}
3421
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003422binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3423 std::vector<hardware::CameraStatus>* cameraStatuses) {
3424 return addListenerHelper(listener, cameraStatuses, false, true);
3425}
3426
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003427Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3428 /*out*/
3429 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003430 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003431 ATRACE_CALL();
3432
Igor Murashkinbfc99152013-02-27 12:55:20 -08003433 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003434
Ruben Brunk3450ba72015-06-16 11:00:37 -07003435 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003436 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003437 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003438 }
3439
Austin Borger22c5c852024-03-08 13:31:36 -08003440 auto clientPid = getCallingPid();
3441 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003442 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003443
Igor Murashkinbfc99152013-02-27 12:55:20 -08003444 Mutex::Autolock lock(mServiceLock);
3445
Ruben Brunkcc776712015-02-17 20:18:47 -08003446 {
3447 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003448 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003449 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003450 ALOGW("%s: Tried to add listener %p which was already subscribed",
3451 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003452 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003453 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003454 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003455
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003456 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003457 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3458 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003459 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003460 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003461 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003462 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003463 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3464 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3465 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003466 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003467 // The listener still needs to be added to the list of listeners, regardless of what
3468 // permissions the listener process has / whether it is a vendor listener. Since it might be
3469 // eligible to listen to other camera ids.
3470 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003471 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003472 }
3473
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003474 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003475 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003476 Mutex::Autolock lock(mCameraStatesLock);
3477 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003478 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3479 auto [deviceId, mappedCameraId] =
3480 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3481
3482 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003483 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003484 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3485 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003486 }
3487 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003488 // Remove the camera statuses that should be hidden from the client, we do
3489 // this after collecting the states in order to avoid holding
3490 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3491 // the same time.
3492 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3493 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003494 std::string cameraId = s.cameraId;
3495 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003496 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003497 if (!cameraIdOptional.has_value()) {
3498 std::string msg =
3499 fmt::sprintf(
3500 "Camera %s: Invalid camera id for device id %d",
3501 s.cameraId.c_str(), s.deviceId);
3502 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3503 return true;
3504 }
3505 cameraId = cameraIdOptional.value();
3506 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3507 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3508 ALOGE("%s: Invalid camera id %s, skipping status update",
3509 __FUNCTION__, s.cameraId.c_str());
3510 return true;
3511 }
3512 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3513 clientUid);
3514 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003515
Biswarup Pal37a75182024-01-16 15:53:35 +00003516 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003517 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003518 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003519 // Add only default device cameras here, as virtual cameras currently don't support torch
3520 // anyway. Note that this is a simplification of the implementation here, and we should
3521 // change this when virtual cameras support torch.
3522 if (s.deviceId == kDefaultDeviceId) {
3523 idsChosenForCallback.insert(s.cameraId);
3524 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003525 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003526
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003527 /*
3528 * Immediately signal current torch status to this listener only
3529 * This may be a subset of all the devices, so don't include it in the response directly
3530 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003531 {
3532 Mutex::Autolock al(mTorchStatusMutex);
3533 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003534 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003535 // The camera id is visible to the client. Fine to send torch
3536 // callback.
3537 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003538 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3539 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003540 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003541 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003542 }
3543
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003544 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003545}
Ruben Brunkcc776712015-02-17 20:18:47 -08003546
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003547Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003548 ATRACE_CALL();
3549
Igor Murashkinbfc99152013-02-27 12:55:20 -08003550 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3551
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003552 if (listener == 0) {
3553 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003554 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003555 }
3556
Igor Murashkinbfc99152013-02-27 12:55:20 -08003557 Mutex::Autolock lock(mServiceLock);
3558
Ruben Brunkcc776712015-02-17 20:18:47 -08003559 {
3560 Mutex::Autolock lock(mStatusListenerLock);
3561 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003562 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003563 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003564 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003565 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003566 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003567 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003568 }
3569 }
3570
3571 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3572 __FUNCTION__, listener.get());
3573
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003574 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003575}
3576
Austin Borgered99f642023-06-01 16:51:35 -07003577Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003578
3579 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003580 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3581
3582 if (parameters == NULL) {
3583 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003584 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003585 }
3586
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003587 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003588
3589 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003590 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003591 // Error logged by caller
3592 return ret;
3593 }
3594
3595 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003596
Austin Borgered99f642023-06-01 16:51:35 -07003597 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003598
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003599 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003600}
3601
malikakash98260df2024-05-10 23:33:57 +00003602Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003603 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003604 ATRACE_CALL();
3605
Austin Borgered99f642023-06-01 16:51:35 -07003606 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003607
3608 switch (apiVersion) {
3609 case API_VERSION_1:
3610 case API_VERSION_2:
3611 break;
3612 default:
Austin Borgered99f642023-06-01 16:51:35 -07003613 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3614 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3615 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003616 }
3617
Austin Borger18b30a72022-10-27 12:20:29 -07003618 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003619 auto deviceVersionAndTransport =
3620 getDeviceVersion(cameraId,
3621 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3622 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003623 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003624 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3625 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3626 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003627 }
3628 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3629 int deviceVersion = deviceVersionAndTransport.first;
3630 switch (deviceVersion) {
3631 case CAMERA_DEVICE_API_VERSION_1_0:
3632 case CAMERA_DEVICE_API_VERSION_3_0:
3633 case CAMERA_DEVICE_API_VERSION_3_1:
3634 if (apiVersion == API_VERSION_2) {
3635 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003636 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003637 *isSupported = false;
3638 } else { // if (apiVersion == API_VERSION_1) {
3639 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003640 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003641 *isSupported = true;
3642 }
3643 break;
3644 case CAMERA_DEVICE_API_VERSION_3_2:
3645 case CAMERA_DEVICE_API_VERSION_3_3:
3646 case CAMERA_DEVICE_API_VERSION_3_4:
3647 case CAMERA_DEVICE_API_VERSION_3_5:
3648 case CAMERA_DEVICE_API_VERSION_3_6:
3649 case CAMERA_DEVICE_API_VERSION_3_7:
3650 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003651 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003652 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003653 break;
3654 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003655 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3656 deviceVersion, cameraId.c_str());
3657 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3658 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003659 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003660 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003661 } else {
3662 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003663 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003664 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003665}
3666
malikakash98260df2024-05-10 23:33:57 +00003667Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003668 /*out*/ bool *isSupported) {
3669 ATRACE_CALL();
3670
Austin Borgered99f642023-06-01 16:51:35 -07003671 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3672 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003673
3674 return Status::ok();
3675}
3676
Cliff Wud8cae102021-03-11 01:37:42 +08003677Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003678 const std::string& packageName, const std::string& internalCamId,
3679 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003680 const sp<ICameraInjectionCallback>& callback,
3681 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003682 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003683 ATRACE_CALL();
3684
Austin Borgered99f642023-06-01 16:51:35 -07003685 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003686 const int pid = getCallingPid();
3687 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003688 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3689 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003690 "Permission Denial: no permission to inject camera");
3691 }
3692
3693 // Do not allow any camera injection that injects or replaces a virtual camera.
3694 auto [deviceIdForInternalCamera, _] =
3695 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3696 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3697 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3698 "Cannot replace a virtual camera");
3699 }
3700 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3701 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3702 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3703 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3704 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003705 }
3706
3707 ALOGV(
3708 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3709 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003710 __FUNCTION__, packageName.c_str(),
3711 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003712
Cliff Wud3a05312021-04-26 23:07:31 +08003713 {
3714 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003715 mInjectionInternalCamId = internalCamId;
3716 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003717 mInjectionStatusListener->addListener(callback);
3718 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003719 status_t res = NO_ERROR;
3720 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3721 // If the client already exists, we can directly connect to the camera device through the
3722 // client's injectCamera(), otherwise we need to wait until the client is established
3723 // (execute connectHelper()) before injecting the camera to the camera device.
3724 if (clientDescriptor != nullptr) {
3725 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003726 sp<BasicClient> clientSp = clientDescriptor->getValue();
3727 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3728 if(res != OK) {
3729 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3730 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003731 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003732 }
3733 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003734 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003735 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3736 }
3737 } else {
3738 mInjectionInitPending = true;
3739 }
3740 }
Cliff Wud8cae102021-03-11 01:37:42 +08003741
Cliff Wud3a05312021-04-26 23:07:31 +08003742 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003743}
3744
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003745Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003746 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003747 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3748 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3749 return Status::ok();
3750}
3751
Ruben Brunkcc776712015-02-17 20:18:47 -08003752void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003753 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 for (auto& i : mActiveClientManager.getAll()) {
3755 auto clientSp = i->getValue();
3756 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003757 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003759 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003760 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003761 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003762}
3763
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003764bool CameraService::isOnlyClient(const BasicClient* client) {
3765 Mutex::Autolock lock(mServiceLock);
3766 bool ret = true;
3767 if (!flags::camera_multi_client()) {
3768 return ret;
3769 }
3770 if (client != nullptr) {
3771 std::string camId = client->mCameraIdStr;
3772 for (const auto& i : mActiveClientManager.getAll()) {
3773 auto clientSp = i->getValue();
3774 auto curCamId = i->getKey();
3775 if (!curCamId.compare(camId) && clientSp.get() != client) {
3776 return false;
3777 }
3778 }
3779 }
3780 return ret;
3781}
3782
Ruben Brunkcc776712015-02-17 20:18:47 -08003783bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 bool ret = false;
3785 {
3786 // Acquire mServiceLock and prevent other clients from connecting
3787 std::unique_ptr<AutoConditionLock> lock =
3788 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003789
Ruben Brunkcc776712015-02-17 20:18:47 -08003790 std::vector<sp<BasicClient>> evicted;
3791 for (auto& i : mActiveClientManager.getAll()) {
3792 auto clientSp = i->getValue();
3793 if (clientSp.get() == nullptr) {
3794 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3795 mActiveClientManager.remove(i);
3796 continue;
3797 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003798 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003799 mActiveClientManager.remove(i);
3800 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003801
Ruben Brunkcc776712015-02-17 20:18:47 -08003802 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003803 clientSp->notifyError(
3804 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003805 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003806 }
3807 }
3808
Ruben Brunkcc776712015-02-17 20:18:47 -08003809 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3810 // other clients from connecting in mServiceLockWrapper if held
3811 mServiceLock.unlock();
3812
Ruben Brunk36597b22015-03-20 22:15:57 -07003813 // Do not clear caller identity, remote caller should be client proccess
3814
Ruben Brunkcc776712015-02-17 20:18:47 -08003815 for (auto& i : evicted) {
3816 if (i.get() != nullptr) {
3817 i->disconnect();
3818 ret = true;
3819 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003820 }
3821
Ruben Brunkcc776712015-02-17 20:18:47 -08003822 // Reacquire mServiceLock
3823 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003824
Ruben Brunkcc776712015-02-17 20:18:47 -08003825 } // lock is destroyed, allow further connect calls
3826
3827 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003828}
3829
Ruben Brunkcc776712015-02-17 20:18:47 -08003830std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003831 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003832 std::shared_ptr<CameraState> state;
3833 {
3834 Mutex::Autolock lock(mCameraStatesLock);
3835 auto iter = mCameraStates.find(cameraId);
3836 if (iter != mCameraStates.end()) {
3837 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838 }
3839 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003840 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003841}
3842
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003843std::vector<sp<CameraService::BasicClient>> CameraService::removeClientsLocked(
3844 const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003845 // Remove from active clients list
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003846 std::vector<sp<CameraService::BasicClient>> clients;
Jyoti Bhayana1a586fd2024-11-20 19:54:35 -08003847 if (flags::camera_multi_client()) {
3848 std::vector<CameraService::DescriptorPtr> clientDescriptors;
3849 clientDescriptors = mActiveClientManager.removeAll(cameraId);
3850 for (const auto& clientDescriptorPtr : clientDescriptors) {
3851 if (clientDescriptorPtr != nullptr) {
3852 sp<BasicClient> client = clientDescriptorPtr->getValue();
3853 if (client.get() != nullptr) {
3854 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3855 clients.push_back(client);
3856 }
3857 }
3858 }
3859 } else {
3860 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3861 if (clientDescriptorPtr == nullptr) {
3862 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3863 cameraId.c_str());
3864 return clients;
3865 }
3866
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003867 sp<BasicClient> client = clientDescriptorPtr->getValue();
3868 if (client.get() != nullptr) {
3869 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
Jyoti Bhayana1a586fd2024-11-20 19:54:35 -08003870 clients.push_back(client);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003871 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003872 }
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003873 return clients;
Keun young Parkd8973a72012-03-28 14:13:09 -07003874}
3875
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003876void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003877 // Acquire mServiceLock and prevent other clients from connecting
3878 std::unique_ptr<AutoConditionLock> lock =
3879 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3880
Ruben Brunk6267b532015-04-30 17:44:07 -07003881 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003882 for (size_t i = 0; i < newUserIds.size(); i++) {
3883 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003884 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003885 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003886 return;
3887 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003888 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003889 }
3890
Ruben Brunka8ca9152015-04-07 14:23:40 -07003891
Ruben Brunk6267b532015-04-30 17:44:07 -07003892 if (newAllowedUsers == mAllowedUsers) {
3893 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3894 return;
3895 }
3896
3897 logUserSwitch(mAllowedUsers, newAllowedUsers);
3898
3899 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003900
3901 // Current user has switched, evict all current clients.
3902 std::vector<sp<BasicClient>> evicted;
3903 for (auto& i : mActiveClientManager.getAll()) {
3904 auto clientSp = i->getValue();
3905
3906 if (clientSp.get() == nullptr) {
3907 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3908 continue;
3909 }
3910
Ruben Brunk6267b532015-04-30 17:44:07 -07003911 // Don't evict clients that are still allowed.
3912 uid_t clientUid = clientSp->getClientUid();
3913 userid_t clientUserId = multiuser_get_user_id(clientUid);
3914 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3915 continue;
3916 }
3917
Ruben Brunk36597b22015-03-20 22:15:57 -07003918 evicted.push_back(clientSp);
3919
Ruben Brunk36597b22015-03-20 22:15:57 -07003920 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003921 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003922
Ruben Brunk36597b22015-03-20 22:15:57 -07003923 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003924 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003925 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003926 " to user switch.", i->getKey().c_str(),
3927 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003928 i->getOwnerId(), i->getPriority().getScore(),
3929 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003930
3931 }
3932
3933 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3934 // blocking other clients from connecting in mServiceLockWrapper if held.
3935 mServiceLock.unlock();
3936
3937 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003938 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003939
3940 for (auto& i : evicted) {
3941 i->disconnect();
3942 }
3943
Austin Borger22c5c852024-03-08 13:31:36 -08003944 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003945
3946 // Reacquire mServiceLock
3947 mServiceLock.lock();
3948}
Ruben Brunkcc776712015-02-17 20:18:47 -08003949
Austin Borgered99f642023-06-01 16:51:35 -07003950void CameraService::logEvent(const std::string &event) {
3951 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003952 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003953 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003954 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003955 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003956 mEventLog.add(msg);
3957 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3958 // Error event not added to the dumpsys log before
3959 mEventLog.add(msg);
3960 sServiceErrorEventSet.insert(msg);
3961 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962}
3963
Austin Borgered99f642023-06-01 16:51:35 -07003964void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3965 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003966 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003967 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3968 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003969}
3970
Austin Borgered99f642023-06-01 16:51:35 -07003971void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3972 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003973 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003974 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3975 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003976}
3977
Austin Borgered99f642023-06-01 16:51:35 -07003978void CameraService::logConnected(const std::string &cameraId, int clientPid,
3979 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003980 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003981 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3982 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003983}
3984
Austin Borgered99f642023-06-01 16:51:35 -07003985void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3986 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003987 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003988 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3989 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003990}
3991
Austin Borgered99f642023-06-01 16:51:35 -07003992void CameraService::logRejected(const std::string &cameraId, int clientPid,
3993 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003994 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003995 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3996 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003997}
3998
Austin Borgered99f642023-06-01 16:51:35 -07003999void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4000 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004001 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004002 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4003 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004004}
4005
Ruben Brunk6267b532015-04-30 17:44:07 -07004006void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4007 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004008 std::string newUsers = toString(newUserIds);
4009 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004010 if (oldUsers.size() == 0) {
4011 oldUsers = "<None>";
4012 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004013 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004014 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4015 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004016}
4017
Austin Borgered99f642023-06-01 16:51:35 -07004018void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004019 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004020 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004021}
4022
Austin Borgered99f642023-06-01 16:51:35 -07004023void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004024 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004025 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004026}
4027
Austin Borgered99f642023-06-01 16:51:35 -07004028void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004029 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004030 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004031}
4032
Austin Borgered99f642023-06-01 16:51:35 -07004033void CameraService::logServiceError(const std::string &msg, int errorCode) {
4034 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4035 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004036}
4037
Ruben Brunk36597b22015-03-20 22:15:57 -07004038status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4039 uint32_t flags) {
4040
Mathias Agopian65ab4712010-07-14 17:59:35 -07004041 // Permission checks
4042 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004043 case SHELL_COMMAND_TRANSACTION: {
4044 int in = data.readFileDescriptor();
4045 int out = data.readFileDescriptor();
4046 int err = data.readFileDescriptor();
4047 int argc = data.readInt32();
4048 Vector<String16> args;
4049 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4050 args.add(data.readString16());
4051 }
4052 sp<IBinder> unusedCallback;
4053 sp<IResultReceiver> resultReceiver;
4054 status_t status;
4055 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4056 return status;
4057 }
4058 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4059 return status;
4060 }
4061 status = shellCommand(in, out, err, args);
4062 if (resultReceiver != nullptr) {
4063 resultReceiver->send(status);
4064 }
4065 return NO_ERROR;
4066 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004067 }
4068
4069 return BnCameraService::onTransact(code, data, reply, flags);
4070}
4071
Mathias Agopian65ab4712010-07-14 17:59:35 -07004072// We share the media players for shutter and recording sound for all clients.
4073// A reference count is kept to determine when we will actually release the
4074// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004075sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4076 sp<MediaPlayer> mp = new MediaPlayer();
4077 status_t error;
4078 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004079 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004080 error = mp->prepare();
4081 }
4082 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004083 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004084 mp->disconnect();
4085 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004086 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087 }
4088 return mp;
4089}
4090
username5755fea2018-12-27 09:48:08 +08004091void CameraService::increaseSoundRef() {
4092 Mutex::Autolock lock(mSoundLock);
4093 mSoundRef++;
4094}
4095
4096void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004097 ATRACE_CALL();
4098
username5755fea2018-12-27 09:48:08 +08004099 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4100 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4101 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4102 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4103 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4104 }
4105 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4106 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4107 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4108 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004109 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004110 }
4111 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4112 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4113 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4114 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4115 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004116 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004117}
4118
username5755fea2018-12-27 09:48:08 +08004119void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004120 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004121 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004122 if (--mSoundRef) return;
4123
4124 for (int i = 0; i < NUM_SOUNDS; i++) {
4125 if (mSoundPlayer[i] != 0) {
4126 mSoundPlayer[i]->disconnect();
4127 mSoundPlayer[i].clear();
4128 }
4129 }
4130}
4131
4132void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004133 ATRACE_CALL();
4134
Mathias Agopian65ab4712010-07-14 17:59:35 -07004135 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004136 if (kind < 0 || kind >= NUM_SOUNDS) {
4137 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4138 return;
4139 }
4140
Mathias Agopian65ab4712010-07-14 17:59:35 -07004141 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004142 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 sp<MediaPlayer> player = mSoundPlayer[kind];
4144 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004145 player->seekTo(0);
4146 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147 }
4148}
4149
4150// ----------------------------------------------------------------------------
4151
Austin Borger2e772b82024-10-11 16:09:57 -07004152CameraService::Client::Client(
4153 const sp<CameraService>& cameraService, const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004154 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004155 const AttributionSourceState& clientAttribution, int callingPid, bool systemNativeClient,
4156 const std::string& cameraIdStr, int api1CameraId, int cameraFacing, int sensorOrientation,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004157 int servicePid, int rotationOverride, bool sharedMode)
Austin Borger2e772b82024-10-11 16:09:57 -07004158 : CameraService::BasicClient(cameraService, IInterface::asBinder(cameraClient),
4159 attributionAndPermissionUtils, clientAttribution, callingPid,
4160 systemNativeClient, cameraIdStr, cameraFacing, sensorOrientation,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004161 servicePid, rotationOverride, sharedMode),
Austin Borger2e772b82024-10-11 16:09:57 -07004162 mCameraId(api1CameraId) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004163 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004164
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004165 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166
username5755fea2018-12-27 09:48:08 +08004167 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004168
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004169 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004170}
4171
Mathias Agopian65ab4712010-07-14 17:59:35 -07004172// tear down the client
4173CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004174 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004175 mDestructionStarted = true;
4176
username5755fea2018-12-27 09:48:08 +08004177 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004178 // unconditionally disconnect. function is idempotent
4179 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004180}
4181
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004182sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4183
Austin Borger2e772b82024-10-11 16:09:57 -07004184CameraService::BasicClient::BasicClient(
4185 const sp<CameraService>& cameraService, const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004186 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004187 const AttributionSourceState& clientAttribution, int callingPid, bool nativeClient,
4188 const std::string& cameraIdStr, int cameraFacing, int sensorOrientation, int servicePid,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004189 int rotationOverride, bool sharedMode)
Austin Borger2e772b82024-10-11 16:09:57 -07004190 : AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
4191 mDestructionStarted(false),
4192 mCameraIdStr(cameraIdStr),
4193 mCameraFacing(cameraFacing),
4194 mOrientation(sensorOrientation),
4195 mClientAttribution(clientAttribution),
4196 mCallingPid(callingPid),
4197 mSystemNativeClient(nativeClient),
4198 mServicePid(servicePid),
4199 mDisconnected(false),
4200 mUidIsTrusted(false),
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004201 mRotationOverride(rotationOverride), mSharedMode(sharedMode),
Austin Borger2e772b82024-10-11 16:09:57 -07004202 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
4203 mRemoteBinder(remoteCallback),
Austin Borgera0c61f12024-10-11 13:38:35 -07004204 mCameraOpen(false),
4205 mCameraStreaming(false) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004206 if (sCameraService == nullptr) {
4207 sCameraService = cameraService;
4208 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004209
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004210 // There are 2 scenarios in which a client won't have AppOps operations
4211 // (both scenarios : native clients)
4212 // 1) It's an system native client*, the package name will be empty
4213 // and it will return from this function in the previous if condition
4214 // (This is the same as the previously existing behavior).
4215 // 2) It is a system native client, but its package name has been
4216 // modified for debugging, however it still must not use AppOps since
4217 // the package name is not a real one.
4218 //
4219 // * system native client - native client with UID < AID_APP_START. It
4220 // doesn't exclude clients not on the system partition.
4221 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004222 mAppOpsManager = std::make_unique<AppOpsManager>();
4223 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004224
Austin Borger32163932024-10-25 13:56:52 -07004225 mUidIsTrusted = isTrustedCallingUid(mClientAttribution.uid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004226}
4227
4228CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004229 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004230 mDestructionStarted = true;
4231}
4232
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004233binder::Status CameraService::BasicClient::disconnect() {
4234 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004235 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004236 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004237 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004238 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004239
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004240 sCameraService->removeByClient(this);
Austin Borger2e772b82024-10-11 16:09:57 -07004241 sCameraService->logDisconnected(mCameraIdStr, mCallingPid, getPackageName());
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004242 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode &&
4243 sCameraService->isOnlyClient(this))) {
4244 // Remove the HAL reference for the camera in either of the following scenarios :
4245 // 1) Camera was opened in non-shared mode.
4246 // 2) Camera was opened in shared mode and this is the last client using
4247 // the camera which is being disconnected
4248 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
4249 mCameraIdStr);
4250 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004251
4252 sp<IBinder> remote = getRemote();
4253 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004254 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004255 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004256
Austin Borgera0c61f12024-10-11 13:38:35 -07004257 notifyCameraClosing();
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004258 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode &&
4259 sCameraService->isOnlyClient(this))) {
4260 // Notify flashlight that a camera device is closed.
4261 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
4262 }
Austin Borgered99f642023-06-01 16:51:35 -07004263 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004264 mCallingPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004265
Igor Murashkincba2c162013-03-20 15:56:31 -07004266 // client shouldn't be able to call into us anymore
Austin Borger2e772b82024-10-11 16:09:57 -07004267 mCallingPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004268
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004269 const auto& mActivityManager = getActivityManager();
4270 if (mActivityManager) {
4271 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004272 getCallingUid(),
4273 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004274 }
4275
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004276 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004277}
4278
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004279status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4280 // No dumping of clients directly over Binder,
4281 // must go through CameraService::dump
4282 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004283 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004284 return OK;
4285}
4286
Austin Borgered99f642023-06-01 16:51:35 -07004287status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004288 // Can't watch tags directly, must go through CameraService::startWatchingTags
4289 return OK;
4290}
4291
4292status_t CameraService::BasicClient::stopWatchingTags(int) {
4293 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4294 return OK;
4295}
4296
4297status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4298 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4299 return OK;
4300}
4301
Austin Borgered99f642023-06-01 16:51:35 -07004302std::string CameraService::BasicClient::getPackageName() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004303 return mClientAttribution.packageName.value_or(kUnknownPackageName);
Ruben Brunkcc776712015-02-17 20:18:47 -08004304}
4305
Emilian Peev8b64f282021-03-25 16:49:57 -07004306int CameraService::BasicClient::getCameraFacing() const {
4307 return mCameraFacing;
4308}
4309
4310int CameraService::BasicClient::getCameraOrientation() const {
4311 return mOrientation;
4312}
Ruben Brunkcc776712015-02-17 20:18:47 -08004313
Austin Borger2e772b82024-10-11 16:09:57 -07004314int CameraService::BasicClient::getClientCallingPid() const {
4315 return mCallingPid;
Ruben Brunkcc776712015-02-17 20:18:47 -08004316}
4317
Ruben Brunk6267b532015-04-30 17:44:07 -07004318uid_t CameraService::BasicClient::getClientUid() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004319 return mClientAttribution.uid;
4320}
4321
4322const std::optional<std::string>& CameraService::BasicClient::getClientAttributionTag() const {
4323 return mClientAttribution.attributionTag;
Ruben Brunk6267b532015-04-30 17:44:07 -07004324}
4325
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004326bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4327 // Defaults to API2.
4328 return level == API_2;
4329}
4330
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004331status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004332 {
4333 Mutex::Autolock l(mAudioRestrictionLock);
4334 mAudioRestriction = mode;
4335 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004336 sCameraService->updateAudioRestriction();
4337 return OK;
4338}
4339
4340int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004341 return sCameraService->updateAudioRestriction();
4342}
4343
4344int32_t CameraService::BasicClient::getAudioRestriction() const {
4345 Mutex::Autolock l(mAudioRestrictionLock);
4346 return mAudioRestriction;
4347}
4348
4349bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4350 switch (mode) {
4351 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4352 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4353 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4354 return true;
4355 default:
4356 return false;
4357 }
4358}
4359
Austin Borgera0c61f12024-10-11 13:38:35 -07004360status_t CameraService::BasicClient::handlePermissionResult(
4361 PermissionChecker::PermissionResult result) {
4362 if (result == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004363 ALOGI("Camera %s: Access for \"%s\" has been revoked", mCameraIdStr.c_str(),
4364 getPackageName().c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004365 return PERMISSION_DENIED;
Austin Borgera0c61f12024-10-11 13:38:35 -07004366 } else if (!mUidIsTrusted && result == PermissionChecker::PERMISSION_SOFT_DENIED) {
4367 // If the calling Uid is trusted (a native service), the AppOpsManager/PermissionChecker
4368 // could return MODE_IGNORED/PERMISSION_SOFT_DENIED. Do not treat such case as error.
Austin Borger2e772b82024-10-11 16:09:57 -07004369 bool isUidActive =
4370 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004371
4372 bool isCameraPrivacyEnabled;
4373 if (flags::camera_privacy_allowlist()) {
4374 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004375 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004376 } else {
4377 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004378 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004379 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004380 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4381 // We prefer to successfully open the camera and perform camera muting
4382 // or blocking in connectHelper as handleAppOpMode can be called before the
4383 // connection has been fully established and at that time camera muting
4384 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004385 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004386 ALOGI("Camera %s: Access for \"%s\" has been restricted."
Austin Borger2e772b82024-10-11 16:09:57 -07004387 "uid active: %s, privacy enabled: %s",
4388 mCameraIdStr.c_str(), getPackageName().c_str(), isUidActive ? "true" : "false",
4389 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004390 // Return the same error as for device policy manager rejection
4391 return -EACCES;
4392 }
4393 }
4394 return OK;
4395}
4396
Austin Borgera0c61f12024-10-11 13:38:35 -07004397status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4398 return handlePermissionResult(appOpModeToPermissionResult(mode));
4399}
4400
4401status_t CameraService::BasicClient::notifyCameraOpening() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004402 ATRACE_CALL();
4403
Austin Borgera0c61f12024-10-11 13:38:35 -07004404 // Don't start watching until we're streaming when using permissionChecker for data delivery
Austin Borger2a3f9a72024-11-07 12:24:49 -08004405 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004406 ALOGD("%s: Start camera ops, package name = %s, client UID = %d", __FUNCTION__,
Austin Borger2e772b82024-10-11 16:09:57 -07004407 getPackageName().c_str(), getClientUid());
Austin Borgerca1e0062023-06-28 11:32:55 -07004408
Austin Borgera0c61f12024-10-11 13:38:35 -07004409 if (mAppOpsManager != nullptr) {
4410 // Notify app ops that the camera is not available
4411 mOpsCallback = new OpsCallback(this);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004412
Austin Borgera0c61f12024-10-11 13:38:35 -07004413 mAppOpsManager->startWatchingMode(
4414 AppOpsManager::OP_CAMERA, toString16(getPackageName()),
4415 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4416
4417 // Just check for camera access here on open - delay startOp until
4418 // camera frames start streaming in startCameraStreamingOps
4419 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4420 toString16(getPackageName()));
4421 status_t res = handleAppOpMode(mode);
4422 if (res != OK) {
4423 return res;
4424 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004425 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004426 } else {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004427 // TODO: Remove when removing the data_delivery_permission_checks flag
Austin Borgera0c61f12024-10-11 13:38:35 -07004428 ALOGD("%s: Bypassing checkOp for uid %d", __FUNCTION__, getClientUid());
Svetoslav28e8ef72015-05-11 19:21:31 -07004429 }
4430
Austin Borgera0c61f12024-10-11 13:38:35 -07004431 mCameraOpen = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004432
4433 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004434 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004435
Austin Borger2e772b82024-10-11 16:09:57 -07004436 sCameraService->mUidPolicy->registerMonitorUid(getClientUid(), /*openCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004437
Shuzhen Wang695044d2020-03-06 09:02:23 -08004438 // Notify listeners of camera open/close status
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004439 sCameraService->updateOpenCloseStatus(mCameraIdStr, true /*open*/, getPackageName(),
4440 mSharedMode);
Shuzhen Wang695044d2020-03-06 09:02:23 -08004441
darkobasd7b8fa52018-08-07 13:00:17 +02004442#ifdef TARGET_CAMERA_NEEDS_CLIENT_INFO
4443 std::ofstream cpf("/data/misc/omni/client_package_name");
4444 std::string cpn = mClientPackageName.c_str();
4445 cpf << cpn;
4446#endif
4447
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004448 return OK;
4449}
4450
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004451status_t CameraService::BasicClient::startCameraStreamingOps() {
4452 ATRACE_CALL();
4453
Austin Borgera0c61f12024-10-11 13:38:35 -07004454 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004455 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4456 return INVALID_OPERATION;
4457 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004458
4459 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004460 ALOGV("%s: Streaming already active!", __FUNCTION__);
4461 return OK;
4462 }
4463
Austin Borger2e772b82024-10-11 16:09:57 -07004464 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d", __FUNCTION__,
4465 getPackageName().c_str(), getClientUid());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004466
4467 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004468 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004469 ALOGD("%s: Start data delivery for uid %d", __FUNCTION__, getClientUid());
4470
4471 const PermissionChecker::PermissionResult result =
4472 checkPermissionsForCameraForStartDataDelivery(mCameraIdStr, mClientAttribution);
4473 status_t res = handlePermissionResult(result);
4474 if (res != OK) {
4475 return res;
4476 }
4477
4478 mOpsCallback = new OpsCallback(this);
4479 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4480 [&](const auto& attr) {
4481 mAppOpsManager->startWatchingMode(
4482 AppOpsManager::OP_CAMERA,
4483 toString16(attr.packageName.value_or("")),
4484 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4485 });
4486 } else {
4487 ALOGD("%s: startOp for uid %d", __FUNCTION__, getClientUid());
4488 int32_t mode = mAppOpsManager->startOpNoThrow(
4489 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4490 /*startIfModeDefault*/ false, toString16(getClientAttributionTag()),
4491 toString16("start camera ") + toString16(mCameraIdStr));
4492 status_t res = handleAppOpMode(mode);
4493 if (res != OK) {
4494 return res;
4495 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004496 }
4497 }
4498
Austin Borgera0c61f12024-10-11 13:38:35 -07004499 mCameraStreaming = true;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004500
4501 return OK;
4502}
4503
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004504status_t CameraService::BasicClient::noteAppOp() {
4505 ATRACE_CALL();
4506
Austin Borger2e772b82024-10-11 16:09:57 -07004507 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d", __FUNCTION__,
4508 getPackageName().c_str(), getClientUid());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004509
4510 // noteAppOp is only used for when camera mute is not supported, in order
4511 // to trigger the sensor privacy "Unblock" dialog
Austin Borger2a3f9a72024-11-07 12:24:49 -08004512 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004513 // Ignore the result, since we're only triggering the dialog
4514 ALOGD("%s: Check data delivery permissions for uid %d", __FUNCTION__, getClientUid());
4515 hasPermissionsForCameraForDataDelivery(std::string(), mClientAttribution);
4516 } else if (mAppOpsManager != nullptr) {
4517 ALOGD("%s: noteOp for uid %d", __FUNCTION__, getClientUid());
Austin Borger2e772b82024-10-11 16:09:57 -07004518 int32_t mode = mAppOpsManager->noteOp(
4519 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4520 toString16(getClientAttributionTag()),
Austin Borgered99f642023-06-01 16:51:35 -07004521 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004522 status_t res = handleAppOpMode(mode);
4523 if (res != OK) {
4524 return res;
4525 }
4526 }
4527
4528 return OK;
4529}
4530
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004531status_t CameraService::BasicClient::finishCameraStreamingOps() {
4532 ATRACE_CALL();
4533
Austin Borgera0c61f12024-10-11 13:38:35 -07004534 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004535 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4536 return INVALID_OPERATION;
4537 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004538 if (!mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004539 ALOGV("%s: Streaming not active!", __FUNCTION__);
4540 return OK;
4541 }
4542
4543 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004544 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004545 ALOGD("%s: finishDataDelivery for uid %d", __FUNCTION__, getClientUid());
4546 finishDataDelivery(mClientAttribution);
4547
4548 // Stop watching app op changes after stop streaming
4549 if (mOpsCallback != nullptr) {
4550 mAppOpsManager->stopWatchingMode(mOpsCallback);
4551 mOpsCallback.clear();
4552 }
4553 } else {
4554 ALOGD("%s: finishOp for uid %d", __FUNCTION__, getClientUid());
4555 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, getClientUid(),
4556 toString16(getPackageName()),
4557 toString16(getClientAttributionTag()));
4558 }
4559 mCameraStreaming = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004560 }
4561
4562 return OK;
4563}
4564
Austin Borgera0c61f12024-10-11 13:38:35 -07004565status_t CameraService::BasicClient::notifyCameraClosing() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004566 ATRACE_CALL();
4567
Austin Borgera0c61f12024-10-11 13:38:35 -07004568 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004569 // Make sure we've notified everyone about camera stopping
4570 finishCameraStreamingOps();
4571 }
4572
Austin Borgera0c61f12024-10-11 13:38:35 -07004573 // Check if notifyCameraOpening succeeded, and if so, finish the camera op if necessary
4574 if (mCameraOpen) {
4575 mCameraOpen = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004576
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004577 // This function is called when a client disconnects. This should
4578 // release the camera, but actually only if it was in a proper
4579 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004580 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004581 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004582
Ruben Brunkcc776712015-02-17 20:18:47 -08004583 // Transition to PRESENT if the camera is not in either of the rejected states
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004584 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode
4585 && sCameraService->isOnlyClient(this))) {
4586 sCameraService->updateStatus(StatusInternal::PRESENT,
4587 mCameraIdStr, rejected);
4588 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004589 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004590
4591 // When using the data delivery permission checks, the open state does not involve AppOps
Austin Borger2a3f9a72024-11-07 12:24:49 -08004592 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004593 // Always stop watching, even if no camera op is active
4594 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4595 mAppOpsManager->stopWatchingMode(mOpsCallback);
4596 }
4597 mOpsCallback.clear();
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004598 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004599
Austin Borger2e772b82024-10-11 16:09:57 -07004600 sCameraService->mUidPolicy->unregisterMonitorUid(getClientUid(), /*closeCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004601
Shuzhen Wang695044d2020-03-06 09:02:23 -08004602 // Notify listeners of camera open/close status
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004603 sCameraService->updateOpenCloseStatus(mCameraIdStr, false /*open*/, getPackageName(),
4604 mSharedMode);
Shuzhen Wang695044d2020-03-06 09:02:23 -08004605
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004606 return OK;
4607}
4608
Austin Borgerf2da9c72024-11-12 13:45:28 -08004609int32_t CameraService::getUidProcessState(int32_t uid) {
4610 const auto& activityManager = getActivityManager();
4611 int32_t procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
4612 if (activityManager != nullptr) {
4613 procState = activityManager->getUidProcessState(uid, toString16(kServiceName));
4614 } else {
4615 ALOGE("%s: getActivityManager returned nullptr.", __FUNCTION__);
4616 }
4617 return procState;
4618}
4619
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004620void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004621 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004622 if (mAppOpsManager == nullptr) {
4623 return;
4624 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004625 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004626 if (op != AppOpsManager::OP_CAMERA) {
4627 ALOGW("Unexpected app ops notification received: %d", op);
4628 return;
4629 }
4630
Austin Borgera0c61f12024-10-11 13:38:35 -07004631 PermissionChecker::PermissionResult res;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004632 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004633 int32_t appOpMode = AppOpsManager::MODE_ALLOWED;
4634 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4635 [&](const auto& attr) {
4636 appOpMode = std::max(appOpMode, mAppOpsManager->checkOp(
4637 AppOpsManager::OP_CAMERA, attr.uid,
4638 toString16(attr.packageName.value_or(""))));
4639 });
4640 ALOGV("checkOp returns: %d, %s ", res,
4641 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4642 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4643 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4644 : "UNKNOWN");
4645 res = appOpModeToPermissionResult(appOpMode);
4646 } else {
4647 int32_t appOpMode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4648 toString16(getPackageName()));
4649 ALOGV("checkOp returns: %d, %s ", res,
4650 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4651 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4652 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4653 : "UNKNOWN");
4654 res = appOpModeToPermissionResult(appOpMode);
4655 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004656
Austin Borgera0c61f12024-10-11 13:38:35 -07004657 if (res == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borgered99f642023-06-01 16:51:35 -07004658 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004659 getPackageName().c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004660 block();
Austin Borgera0c61f12024-10-11 13:38:35 -07004661 } else if (res == PermissionChecker::PERMISSION_SOFT_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004662 bool isUidActive =
4663 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004664
Austin Borgerca1e0062023-06-28 11:32:55 -07004665 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4666 // If not visible, but still active, then we want to block instead of muting the camera.
Austin Borgera0c61f12024-10-11 13:38:35 -07004667 int32_t procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004668 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004669 // Use the proc state of the last uid in the chain (ultimately receiving the data)
4670 // when determining whether to mute or block
4671 int32_t uid = -1;
4672 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4673 [&](const auto& attr) {
4674 uid = static_cast<uid_t>(attr.uid);
4675 });
Austin Borgerf2da9c72024-11-12 13:45:28 -08004676 procState = getUidProcessState(uid);
4677 } else if (flags::query_process_state()) {
4678 procState = getUidProcessState(getClientUid());
Austin Borgera0c61f12024-10-11 13:38:35 -07004679 } else {
4680 procState = sCameraService->mUidPolicy->getProcState(getClientUid());
4681 }
Austin Borgerca1e0062023-06-28 11:32:55 -07004682 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4683
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004684 bool isCameraPrivacyEnabled;
4685 if (flags::camera_privacy_allowlist()) {
4686 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004687 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004688 } else {
4689 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004690 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004691 }
4692
4693 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgera0c61f12024-10-11 13:38:35 -07004694 " isUidVisible %d, isCameraPrivacyEnabled %d procState %d",
Austin Borger2e772b82024-10-11 16:09:57 -07004695 mCameraIdStr.c_str(), getPackageName().c_str(), mUidIsTrusted, isUidActive,
Austin Borgera0c61f12024-10-11 13:38:35 -07004696 isUidVisible, isCameraPrivacyEnabled, procState);
Austin Borgerca1e0062023-06-28 11:32:55 -07004697 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4698 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4699 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004700 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004701 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4702 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004703 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004704 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004705 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004706 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004707 } else if (res == PermissionChecker::PERMISSION_GRANTED) {
Evan Severson09ab4002021-02-10 14:15:19 -08004708 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004709 }
4710}
4711
Svet Ganova453d0d2018-01-11 15:37:58 -08004712void CameraService::BasicClient::block() {
4713 ATRACE_CALL();
4714
4715 // Reset the client PID to allow server-initiated disconnect,
4716 // and to prevent further calls by client.
Austin Borger2e772b82024-10-11 16:09:57 -07004717 mCallingPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004718 CaptureResultExtras resultExtras; // a dummy result (invalid)
4719 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4720 disconnect();
4721}
4722
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004723status_t CameraService::BasicClient::isPrimaryClient(bool* isPrimary) {
4724 ATRACE_CALL();
4725 if (!flags::camera_multi_client()) {
4726 return INVALID_OPERATION;
4727 }
4728
4729 if (!mSharedMode) {
4730 ALOGW("%s: Invalid operation when camera is not opened in shared mode", __FUNCTION__);
4731 return INVALID_OPERATION;
4732 }
4733 *isPrimary = mIsPrimaryClient;
4734 return OK;
4735}
4736
4737status_t CameraService::BasicClient::setPrimaryClient(bool isPrimary) {
4738 ATRACE_CALL();
4739
4740 if (!flags::camera_multi_client()) {
4741 return INVALID_OPERATION;
4742 }
4743
4744 if (!mSharedMode) {
4745 ALOGW("%s:Invalid operation when camera is not opened in shared mode", __FUNCTION__);
4746 return INVALID_OPERATION;
4747 }
4748 mIsPrimaryClient = isPrimary;
4749 return OK;
4750}
4751
Mathias Agopian65ab4712010-07-14 17:59:35 -07004752// ----------------------------------------------------------------------------
4753
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004754void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004755 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004756 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004757 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4758 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4759 api1ErrorCode = CAMERA_ERROR_DISABLED;
4760 }
4761 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004762 } else {
4763 ALOGE("mRemoteCallback is NULL!!");
4764 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004765}
4766
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004767// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004768binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004769 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004770 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004771}
4772
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004773bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4774 return level == API_1;
4775}
4776
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004777CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4778 mClient(client) {
4779}
4780
4781void CameraService::Client::OpsCallback::opChanged(int32_t op,
4782 const String16& packageName) {
4783 sp<BasicClient> client = mClient.promote();
4784 if (client != NULL) {
4785 client->opChanged(op, packageName);
4786 }
4787}
4788
Mathias Agopian65ab4712010-07-14 17:59:35 -07004789// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004790// UidPolicy
4791// ----------------------------------------------------------------------------
4792
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004793void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004794 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004795 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004796
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004797 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004798 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004799 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004800 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004801 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4802 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004803 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004804 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004805 if (res == OK) {
4806 mRegistered = true;
4807 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004808 } else {
4809 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004810 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004811}
4812
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004813void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004814 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004815 return;
4816 }
4817
4818 registerWithActivityManager();
4819}
4820
4821void CameraService::UidPolicy::registerSelf() {
4822 // Use check service to see if the activity service is available
4823 // If not available then register for notifications, instead of blocking
4824 // till the service is ready
4825 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004826 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004827 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004828 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004829 } else {
4830 registerWithActivityManager();
4831 }
4832}
4833
Svet Ganova453d0d2018-01-11 15:37:58 -08004834void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004835 Mutex::Autolock _l(mUidLock);
4836
Steven Moreland2f348142019-07-02 15:59:07 -07004837 mAm.unregisterUidObserver(this);
4838 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004839 mRegistered = false;
4840 mActiveUids.clear();
4841 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004842}
4843
4844void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4845 onUidIdle(uid, disabled);
4846}
4847
4848void CameraService::UidPolicy::onUidActive(uid_t uid) {
4849 Mutex::Autolock _l(mUidLock);
4850 mActiveUids.insert(uid);
4851}
4852
4853void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4854 bool deleted = false;
4855 {
4856 Mutex::Autolock _l(mUidLock);
4857 if (mActiveUids.erase(uid) > 0) {
4858 deleted = true;
4859 }
4860 }
4861 if (deleted) {
4862 sp<CameraService> service = mService.promote();
4863 if (service != nullptr) {
4864 service->blockClientsForUid(uid);
4865 }
4866 }
4867}
4868
Emilian Peev53722fa2019-02-22 17:47:20 -08004869void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004870 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004871 bool procStateChange = false;
4872 {
4873 Mutex::Autolock _l(mUidLock);
4874 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4875 mMonitoredUids[uid].procState != procState) {
4876 mMonitoredUids[uid].procState = procState;
4877 procStateChange = true;
4878 }
4879 }
4880
4881 if (procStateChange) {
4882 sp<CameraService> service = mService.promote();
4883 if (service != nullptr) {
4884 service->notifyMonitoredUids();
4885 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004886 }
4887}
4888
Austin Borgerdddb7552023-03-30 17:53:01 -07004889/**
4890 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4891 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4892 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4893 * monitoredUids. If it is revised above some other monitoredUid, signal
4894 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4895 * foreground apps in split screen - state changes will capture all other cases.
4896 */
4897void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4898 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004899 {
4900 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004901 auto it = mMonitoredUids.find(uid);
4902
4903 if (it != mMonitoredUids.end()) {
4904 if (it->second.hasCamera) {
4905 for (auto &monitoredUid : mMonitoredUids) {
4906 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004907 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004908 notifyUidSet.emplace(monitoredUid.first);
4909 }
4910 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004911 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004912 notifyUidSet.emplace(uid);
4913 } else {
4914 for (auto &monitoredUid : mMonitoredUids) {
4915 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004916 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004917 notifyUidSet.emplace(uid);
4918 }
4919 }
4920 }
4921 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004922 }
4923 }
4924
Austin Borgerdddb7552023-03-30 17:53:01 -07004925 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004926 sp<CameraService> service = mService.promote();
4927 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004928 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004929 }
4930 }
4931}
4932
Austin Borgerdddb7552023-03-30 17:53:01 -07004933/**
4934 * Register a uid for monitoring, and note whether it owns a camera.
4935 */
4936void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004937 Mutex::Autolock _l(mUidLock);
4938 auto it = mMonitoredUids.find(uid);
4939 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004940 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004941 } else {
Austin Borger65577682022-02-17 00:25:43 +00004942 MonitoredUid monitoredUid;
4943 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004944 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004945 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004946 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004947 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004948 if (res != OK) {
4949 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4950 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004951 }
4952
4953 if (openCamera) {
4954 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004955 }
4956}
4957
Austin Borgerdddb7552023-03-30 17:53:01 -07004958/**
4959 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4960 */
4961void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004962 Mutex::Autolock _l(mUidLock);
4963 auto it = mMonitoredUids.find(uid);
4964 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004965 it->second.refCount--;
4966 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004967 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004968 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004969 if (res != OK) {
4970 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4971 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004972 } else if (closeCamera) {
4973 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004974 }
4975 } else {
4976 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4977 }
4978}
4979
Austin Borgered99f642023-06-01 16:51:35 -07004980bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004981 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004982 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004983}
4984
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004985static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4986static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004987
Austin Borgered99f642023-06-01 16:51:35 -07004988bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004989 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004990 // If activity manager is unreachable, assume everything is active
4991 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004992 return true;
4993 }
4994 auto it = mOverrideUids.find(uid);
4995 if (it != mOverrideUids.end()) {
4996 return it->second;
4997 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004998 bool active = mActiveUids.find(uid) != mActiveUids.end();
4999 if (!active) {
5000 // We want active UIDs to always access camera with their first attempt since
5001 // there is no guarantee the app is robustly written and would retry getting
5002 // the camera on failure. The inverse case is not a problem as we would take
5003 // camera away soon once we get the callback that the uid is no longer active.
5004 ActivityManager am;
5005 // Okay to access with a lock held as UID changes are dispatched without
5006 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07005007 int64_t startTimeMillis = 0;
5008 do {
5009 // TODO: Fix this b/109950150!
5010 // Okay this is a hack. There is a race between the UID turning active and
5011 // activity being resumed. The proper fix is very risky, so we temporary add
5012 // some polling which should happen pretty rarely anyway as the race is hard
5013 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005014 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07005015 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07005016 if (active) {
5017 break;
5018 }
5019 if (startTimeMillis <= 0) {
5020 startTimeMillis = uptimeMillis();
5021 }
5022 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005023 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07005024 if (remainingTimeMillis <= 0) {
5025 break;
5026 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005027 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
5028
5029 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07005030 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005031 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07005032 } while (true);
5033
Svet Ganov7b4ab782018-03-25 12:48:10 -07005034 if (active) {
5035 // Now that we found out the UID is actually active, cache that
5036 mActiveUids.insert(uid);
5037 }
5038 }
5039 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08005040}
5041
Varun Shahb42f1eb2019-04-16 14:45:13 -07005042int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
5043 Mutex::Autolock _l(mUidLock);
5044 return getProcStateLocked(uid);
5045}
5046
5047int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
5048 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
5049 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00005050 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07005051 }
5052 return procState;
5053}
5054
Austin Borgered99f642023-06-01 16:51:35 -07005055void CameraService::UidPolicy::addOverrideUid(uid_t uid,
5056 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005057 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08005058}
5059
Austin Borgered99f642023-06-01 16:51:35 -07005060void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005061 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005062}
5063
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005064void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5065 Mutex::Autolock _l(mUidLock);
5066 ALOGV("UidPolicy: ActivityManager has died");
5067 mRegistered = false;
5068 mActiveUids.clear();
5069}
5070
Austin Borgered99f642023-06-01 16:51:35 -07005071void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005072 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005073 bool wasActive = false;
5074 bool isActive = false;
5075 {
5076 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005077 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005078 mOverrideUids.erase(uid);
5079 if (insert) {
5080 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5081 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005082 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005083 }
5084 if (wasActive != isActive && !isActive) {
5085 sp<CameraService> service = mService.promote();
5086 if (service != nullptr) {
5087 service->blockClientsForUid(uid);
5088 }
5089 }
5090}
5091
5092// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005093// SensorPrivacyPolicy
5094// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005095
5096void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5097{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005098 Mutex::Autolock _l(mSensorPrivacyLock);
5099 if (mRegistered) {
5100 return;
5101 }
Evan Severson09ab4002021-02-10 14:15:19 -08005102 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005103 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005104 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005105 mSpm.addToggleSensorPrivacyListener(this);
5106 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005107 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005108 if (flags::camera_privacy_allowlist()) {
5109 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5110 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5111 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5112 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005113 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005114 if (res == OK) {
5115 mRegistered = true;
5116 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5117 }
5118}
5119
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005120void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5121 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005122 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005123 return;
5124 }
5125
5126 registerWithSensorPrivacyManager();
5127}
5128
5129void CameraService::SensorPrivacyPolicy::registerSelf() {
5130 // Use checkservice to see if the sensor_privacy service is available
5131 // If service is not available then register for notification
5132 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005133 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005134 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005135 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005136 } else {
5137 registerWithSensorPrivacyManager();
5138 }
5139}
5140
Michael Grooverd1d435a2018-12-18 17:39:42 -08005141void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5142 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005143 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005144 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005145 mSpm.removeToggleSensorPrivacyListener(this);
5146 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005147 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005148 mRegistered = false;
5149 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5150}
5151
5152bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005153 if (!mRegistered) {
5154 registerWithSensorPrivacyManager();
5155 }
5156
Michael Grooverd1d435a2018-12-18 17:39:42 -08005157 Mutex::Autolock _l(mSensorPrivacyLock);
5158 return mSensorPrivacyEnabled;
5159}
5160
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005161int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5162 if (!mRegistered) {
5163 registerWithSensorPrivacyManager();
5164 }
5165
5166 Mutex::Autolock _l(mSensorPrivacyLock);
5167 return mCameraPrivacyState;
5168}
5169
Evan Seversond0b69922022-01-27 10:47:34 -08005170bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005171 if (!hasCameraPrivacyFeature()) {
5172 return false;
5173 }
Evan Seversond0b69922022-01-27 10:47:34 -08005174 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005175}
5176
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005177bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5178 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07005179 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005180 }
5181 return mSpm.isCameraPrivacyEnabled(packageName);
5182}
5183
Evan Seversond0b69922022-01-27 10:47:34 -08005184binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005185 int toggleType, int sensor, bool enabled) {
5186 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5187 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5188 {
5189 Mutex::Autolock _l(mSensorPrivacyLock);
5190 mSensorPrivacyEnabled = enabled;
5191 }
5192 // if sensor privacy is enabled then block all clients from accessing the camera
5193 if (enabled) {
5194 sp<CameraService> service = mService.promote();
5195 if (service != nullptr) {
5196 service->blockAllClients();
5197 }
5198 }
5199 }
5200 return binder::Status::ok();
5201}
5202
5203binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5204 int, int sensor, int state) {
5205 if (!flags::camera_privacy_allowlist()
5206 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5207 return binder::Status::ok();
5208 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005209 {
5210 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005211 mCameraPrivacyState = state;
5212 }
5213 sp<CameraService> service = mService.promote();
5214 if (!service) {
5215 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005216 }
5217 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005218 if (state == SensorPrivacyManager::ENABLED) {
5219 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005220 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005221 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005222 }
5223 return binder::Status::ok();
5224}
5225
5226void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5227 Mutex::Autolock _l(mSensorPrivacyLock);
5228 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5229 mRegistered = false;
5230}
5231
Evan Severson09ab4002021-02-10 14:15:19 -08005232bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005233 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5234 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5235 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5236 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5237 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005238}
5239
Michael Grooverd1d435a2018-12-18 17:39:42 -08005240// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005241// CameraState
5242// ----------------------------------------------------------------------------
5243
Austin Borgered99f642023-06-01 16:51:35 -07005244CameraService::CameraState::CameraState(const std::string& id, int cost,
5245 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005246 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005247 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005248 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005249
5250CameraService::CameraState::~CameraState() {}
5251
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005252CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005253 Mutex::Autolock lock(mStatusLock);
5254 return mStatus;
5255}
5256
Austin Borgered99f642023-06-01 16:51:35 -07005257std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005258 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005259 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005260 return res;
5261}
5262
Ruben Brunkcc776712015-02-17 20:18:47 -08005263CameraParameters CameraService::CameraState::getShimParams() const {
5264 return mShimParams;
5265}
5266
5267void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5268 mShimParams = params;
5269}
5270
5271int CameraService::CameraState::getCost() const {
5272 return mCost;
5273}
5274
Austin Borgered99f642023-06-01 16:51:35 -07005275std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005276 return mConflicting;
5277}
5278
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005279SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5280 return mSystemCameraKind;
5281}
5282
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005283bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5284 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5285 != mPhysicalCameras.end();
5286}
5287
Austin Borgered99f642023-06-01 16:51:35 -07005288bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005289 Mutex::Autolock lock(mStatusLock);
5290 auto result = mUnavailablePhysicalIds.insert(physicalId);
5291 return result.second;
5292}
5293
Austin Borgered99f642023-06-01 16:51:35 -07005294bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005295 Mutex::Autolock lock(mStatusLock);
5296 auto count = mUnavailablePhysicalIds.erase(physicalId);
5297 return count > 0;
5298}
5299
Austin Borgered99f642023-06-01 16:51:35 -07005300void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005301 Mutex::Autolock lock(mStatusLock);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005302 mClientPackages.clear();
5303 mClientPackages.insert(clientPackage);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005304}
5305
Austin Borgered99f642023-06-01 16:51:35 -07005306std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005307 Mutex::Autolock lock(mStatusLock);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005308 if (!mClientPackages.empty()) {
5309 std::set<std::string>::iterator it = mClientPackages.begin();
5310 return *it;
5311 }
5312 return std::string();
5313}
5314
5315void CameraService::CameraState::addClientPackage(const std::string& clientPackage) {
5316 Mutex::Autolock lock(mStatusLock);
5317 mClientPackages.insert(clientPackage);
5318}
5319
5320void CameraService::CameraState::removeClientPackage(const std::string& clientPackage) {
5321 Mutex::Autolock lock(mStatusLock);
5322 mClientPackages.erase(clientPackage);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005323}
5324
Ruben Brunkcc776712015-02-17 20:18:47 -08005325// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005326// ClientEventListener
5327// ----------------------------------------------------------------------------
5328
5329void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005330 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005331 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005332 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005333 if (basicClient.get() != nullptr) {
5334 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005335 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005336 static_cast<int>(basicClient->getClientUid()));
5337 }
5338}
5339
5340void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005341 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005342 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005343 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005344 if (basicClient.get() != nullptr) {
5345 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005346 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005347 static_cast<int>(basicClient->getClientUid()));
5348 }
5349}
5350
Ruben Brunk99e69712015-05-26 17:25:07 -07005351// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005352// CameraClientManager
5353// ----------------------------------------------------------------------------
5354
Ruben Brunk99e69712015-05-26 17:25:07 -07005355CameraService::CameraClientManager::CameraClientManager() {
5356 setListener(std::make_shared<ClientEventListener>());
5357}
5358
Ruben Brunkcc776712015-02-17 20:18:47 -08005359CameraService::CameraClientManager::~CameraClientManager() {}
5360
5361sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005362 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005363 auto descriptor = get(id);
5364 if (descriptor == nullptr) {
5365 return sp<BasicClient>{nullptr};
5366 }
5367 return descriptor->getValue();
5368}
5369
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005370void CameraService::CameraClientManager::remove(const CameraService::DescriptorPtr& value) {
5371 ClientManager::remove(value);
5372 if (!flags::camera_multi_client()) {
5373 return;
5374 }
5375 auto clientToRemove = value->getValue();
5376 if ((clientToRemove.get() != nullptr) && clientToRemove->mSharedMode) {
5377 bool primaryClient = false;
5378 status_t ret = clientToRemove->isPrimaryClient(&primaryClient);
5379 if ((ret == OK) && primaryClient) {
5380 // Primary client is being removed. Find the next higher priority
5381 // client to become primary client.
5382 auto clientDescriptor = get(value->getKey());
5383 if (clientDescriptor == nullptr) {
5384 ALOGV("CameraService::CameraClientManager::no other clients are using same camera");
5385 return;
5386 }
5387 resource_policy::ClientPriority highestPriority = clientDescriptor->getPriority();
5388 sp<BasicClient> highestPriorityClient = clientDescriptor->getValue();
5389 if (highestPriorityClient.get() != nullptr) {
5390 for (auto& i : getAll()) {
5391 if ((i->getKey() == value->getKey()) && (i->getPriority() < highestPriority)) {
5392 highestPriority = i->getPriority();
5393 highestPriorityClient = i->getValue();
5394 }
5395 }
5396 highestPriorityClient->setPrimaryClient(true);
5397 highestPriorityClient->notifyClientSharedAccessPriorityChanged(true);
5398 }
5399 }
5400 }
5401}
5402
Austin Borgered99f642023-06-01 16:51:35 -07005403std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005404 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005405 std::ostringstream ret;
5406 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005407 bool hasAny = false;
5408 for (auto& i : all) {
5409 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005410 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005411 int32_t cost = i->getCost();
5412 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005413 int32_t score = i->getPriority().getScore();
5414 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005415 auto conflicting = i->getConflicting();
5416 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005417 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005418 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005419 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005420 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005421 uid_t clientUid = clientSp->getClientUid();
5422 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005423 }
Austin Borgered99f642023-06-01 16:51:35 -07005424 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5425 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005426
Ruben Brunk6267b532015-04-30 17:44:07 -07005427 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005428 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005429 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005430 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005431 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005432 }
5433
Austin Borgered99f642023-06-01 16:51:35 -07005434 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005435 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005436 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005437 }
Austin Borgered99f642023-06-01 16:51:35 -07005438 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005439 }
Austin Borgered99f642023-06-01 16:51:35 -07005440 if (hasAny) ret << "\n";
5441 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005442 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005443}
5444
5445CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005446 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5447 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005448 int32_t state, int32_t oomScoreOffset, bool systemNativeClient, bool sharedMode) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005449
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005450 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005451 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005452
Austin Borgered99f642023-06-01 16:51:35 -07005453 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005454 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005455 systemNativeClient, oomScoreOffset, sharedMode);
Ruben Brunkcc776712015-02-17 20:18:47 -08005456}
5457
5458CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005459 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005460 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005461 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005462 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005463 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005464 systemNativeClient, partial->getSharedMode());
Ruben Brunkcc776712015-02-17 20:18:47 -08005465}
5466
5467// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005468// InjectionStatusListener
5469// ----------------------------------------------------------------------------
5470
5471void CameraService::InjectionStatusListener::addListener(
5472 const sp<ICameraInjectionCallback>& callback) {
5473 Mutex::Autolock lock(mListenerLock);
5474 if (mCameraInjectionCallback) return;
5475 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5476 if (res == OK) {
5477 mCameraInjectionCallback = callback;
5478 }
5479}
5480
5481void CameraService::InjectionStatusListener::removeListener() {
5482 Mutex::Autolock lock(mListenerLock);
5483 if (mCameraInjectionCallback == nullptr) {
5484 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5485 return;
5486 }
5487 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5488 mCameraInjectionCallback = nullptr;
5489}
5490
5491void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005492 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005493 if (mCameraInjectionCallback == nullptr) {
5494 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5495 return;
5496 }
Cliff Wud3a05312021-04-26 23:07:31 +08005497
5498 switch (err) {
5499 case -ENODEV:
5500 mCameraInjectionCallback->onInjectionError(
5501 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5502 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005503 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005504 break;
5505 case -EBUSY:
5506 mCameraInjectionCallback->onInjectionError(
5507 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5508 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005509 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005510 break;
5511 case DEAD_OBJECT:
5512 mCameraInjectionCallback->onInjectionError(
5513 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5514 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005515 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005516 break;
5517 case INVALID_OPERATION:
5518 mCameraInjectionCallback->onInjectionError(
5519 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5520 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005521 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005522 break;
5523 case UNKNOWN_TRANSACTION:
5524 mCameraInjectionCallback->onInjectionError(
5525 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5526 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005527 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005528 break;
5529 default:
5530 mCameraInjectionCallback->onInjectionError(
5531 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5532 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005533 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005534 }
Cliff Wud8cae102021-03-11 01:37:42 +08005535}
5536
5537void CameraService::InjectionStatusListener::binderDied(
5538 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005539 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5540 auto parent = mParent.promote();
5541 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005542 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5543 if (clientDescriptor != nullptr) {
5544 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5545 baseClientPtr->stopInjection();
5546 }
Cliff Wu3b268182021-07-06 15:44:43 +08005547 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005548 }
5549}
5550
5551// ----------------------------------------------------------------------------
5552// CameraInjectionSession
5553// ----------------------------------------------------------------------------
5554
5555binder::Status CameraService::CameraInjectionSession::stopInjection() {
5556 Mutex::Autolock lock(mInjectionSessionLock);
5557 auto parent = mParent.promote();
5558 if (parent == nullptr) {
5559 ALOGE("CameraInjectionSession: Parent is gone");
5560 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5561 "Camera service encountered error");
5562 }
Cliff Wud3a05312021-04-26 23:07:31 +08005563
5564 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005565 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5566 if (clientDescriptor != nullptr) {
5567 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5568 res = baseClientPtr->stopInjection();
5569 if (res != OK) {
5570 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5571 " ret != NO_ERROR: %d", res);
5572 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5573 "Camera session encountered error");
5574 }
5575 }
Cliff Wu3b268182021-07-06 15:44:43 +08005576 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005577 return binder::Status::ok();
5578}
5579
5580// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581
5582static const int kDumpLockRetries = 50;
5583static const int kDumpLockSleep = 60000;
5584
5585static bool tryLock(Mutex& mutex)
5586{
5587 bool locked = false;
5588 for (int i = 0; i < kDumpLockRetries; ++i) {
5589 if (mutex.tryLock() == NO_ERROR) {
5590 locked = true;
5591 break;
5592 }
5593 usleep(kDumpLockSleep);
5594 }
5595 return locked;
5596}
5597
Rucha Katakwardf223072021-06-15 10:21:00 -07005598void CameraService::cacheDump() {
5599 if (mMemFd != -1) {
5600 const Vector<String16> args;
5601 ATRACE_CALL();
5602 // Acquiring service lock here will avoid the deadlock since
5603 // cacheDump will not be called during the second disconnect.
5604 Mutex::Autolock lock(mServiceLock);
5605
5606 Mutex::Autolock l(mCameraStatesLock);
5607 // Start collecting the info for open sessions and store it in temp file.
5608 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005609 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005610 auto clientDescriptor = mActiveClientManager.get(cameraId);
5611 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005612 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005613 // Log the current open session info before device is disconnected.
5614 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5615 }
5616 }
5617 }
5618}
5619
Mathias Agopian65ab4712010-07-14 17:59:35 -07005620status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005621 ATRACE_CALL();
5622
Austin Borgered99f642023-06-01 16:51:35 -07005623 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005624 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005625 getCallingPid(),
5626 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005627 return NO_ERROR;
5628 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005629 bool locked = tryLock(mServiceLock);
5630 // failed to lock - CameraService is probably deadlocked
5631 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005632 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005633 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005634
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005635 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005636 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005637
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005638 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005639 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005640
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005641 if (locked) mServiceLock.unlock();
5642 return NO_ERROR;
5643 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005644 dprintf(fd, "\n== Service global info: ==\n\n");
5645 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005646 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005647 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5648 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005649 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5650 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5651 }
Austin Borgered99f642023-06-01 16:51:35 -07005652 std::string activeClientString = mActiveClientManager.toString();
5653 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5654 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005655 if (mStreamUseCaseOverrides.size() > 0) {
5656 dprintf(fd, "Active stream use case overrides:");
5657 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5658 dprintf(fd, " %" PRId64, useCaseOverride);
5659 }
5660 dprintf(fd, "\n");
5661 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005662
5663 dumpEventLog(fd);
5664
5665 bool stateLocked = tryLock(mCameraStatesLock);
5666 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005667 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005668 }
5669
Emilian Peevbd8c5032018-02-14 23:05:40 +00005670 int argSize = args.size();
5671 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005672 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005673 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005674 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005675 }
5676 break;
5677 }
5678 }
5679
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005680 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005681 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005682
Austin Borgered99f642023-06-01 16:51:35 -07005683 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005684
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005685 CameraParameters p = state.second->getShimParams();
5686 if (!p.isEmpty()) {
5687 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5688 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005689 }
5690
5691 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005692 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005693 // log the current open session info
5694 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005695 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005696 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005697 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005698
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005699 }
5700
5701 if (stateLocked) mCameraStatesLock.unlock();
5702
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005703 if (locked) mServiceLock.unlock();
5704
Emilian Peevf53f66e2017-04-11 14:29:43 +01005705 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005706
5707 dprintf(fd, "\n== Vendor tags: ==\n\n");
5708
5709 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5710 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005711 sp<VendorTagDescriptorCache> cache =
5712 VendorTagDescriptorCache::getGlobalVendorTagCache();
5713 if (cache == NULL) {
5714 dprintf(fd, "No vendor tags.\n");
5715 } else {
5716 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5717 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005718 } else {
5719 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5720 }
5721
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005722 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005723 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005724 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005725
5726 // Process dump arguments, if any
5727 int n = args.size();
5728 String16 verboseOption("-v");
5729 String16 unreachableOption("--unreachable");
5730 for (int i = 0; i < n; i++) {
5731 if (args[i] == verboseOption) {
5732 // change logging level
5733 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005734 std::string levelStr = toStdString(args[i+1]);
5735 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005736 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005737 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005738 } else if (args[i] == unreachableOption) {
5739 // Dump memory analysis
5740 // TODO - should limit be an argument parameter?
5741 UnreachableMemoryInfo info;
5742 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5743 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005744 dprintf(fd, "\n== Unable to dump unreachable memory. "
5745 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005746 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005747 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005748 std::string s = info.ToString(/*log_contents*/ true);
5749 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005750 }
5751 }
5752 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005753
5754 bool serviceLocked = tryLock(mServiceLock);
5755
5756 // Dump info from previous open sessions.
5757 // Reposition the offset to beginning of the file before reading
5758
5759 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5760 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5761 ssize_t size_read;
5762 char buf[4096];
5763 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5764 // Read data from file to a small buffer and write it to fd.
5765 write(fd, buf, size_read);
5766 if (size_read == -1) {
5767 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5768 break;
5769 }
5770 }
5771 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5772 } else {
5773 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5774 }
5775
5776 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005777 return NO_ERROR;
5778}
5779
Rucha Katakwardf223072021-06-15 10:21:00 -07005780void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005781 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005782 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005783 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005784 getFormattedCurrentTime().c_str(),
5785 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005786 dprintf(fd, " Client priority score: %d state: %d\n",
5787 clientDescriptor->getPriority().getScore(),
5788 clientDescriptor->getPriority().getState());
5789 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5790
5791 auto client = clientDescriptor->getValue();
5792 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005793 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005794
5795 client->dumpClient(fd, args);
5796}
5797
Austin Borgered99f642023-06-01 16:51:35 -07005798void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005799 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005800 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005801}
5802
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005803void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005804 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005805
5806 Mutex::Autolock l(mLogLock);
5807 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005808 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005809 }
5810
5811 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005812 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005813 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005814 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005815 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005816 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005817}
5818
Austin Borgered99f642023-06-01 16:51:35 -07005819void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005820 Mutex::Autolock lock(mLogLock);
5821 if (!isClientWatchedLocked(client)) { return; }
5822
5823 std::vector<std::string> dumpVector;
5824 client->dumpWatchedEventsToVector(dumpVector);
5825
5826 if (dumpVector.empty()) { return; }
5827
Austin Borgered99f642023-06-01 16:51:35 -07005828 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005829
Austin Borgered99f642023-06-01 16:51:35 -07005830 std::string currentTime = getFormattedCurrentTime();
5831 dumpString << "Cached @ ";
5832 dumpString << currentTime;
5833 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005834
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005835 size_t i = dumpVector.size();
5836
5837 // Store the string in reverse order (latest last)
5838 while (i > 0) {
5839 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005840 dumpString << cameraId;
5841 dumpString << ":";
5842 dumpString << client->getPackageName();
5843 dumpString << " ";
5844 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005845 }
5846
Austin Borgered99f642023-06-01 16:51:35 -07005847 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005848}
5849
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005850void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005851 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005852 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5853 if (mTorchClientMap[i] == who) {
5854 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005855 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005856 status_t res = mFlashlight->setTorchMode(cameraId, false);
5857 if (res) {
5858 ALOGE("%s: torch client died but couldn't turn off torch: "
5859 "%s (%d)", __FUNCTION__, strerror(-res), res);
5860 return;
5861 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005862 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005863 break;
5864 }
5865 }
5866}
5867
Ruben Brunkcc776712015-02-17 20:18:47 -08005868/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005869
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005870 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005871 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5872 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005873 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005874 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005875 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005876
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005877 // check torch client
5878 handleTorchClientBinderDied(who);
5879
5880 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005881 if(!evictClientIdByRemote(who)) {
5882 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005883 return;
5884 }
5885
Ruben Brunkcc776712015-02-17 20:18:47 -08005886 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5887 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005888}
5889
Austin Borgered99f642023-06-01 16:51:35 -07005890void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005891 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005892}
5893
Austin Borgered99f642023-06-01 16:51:35 -07005894void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005895 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005896 // Do not lock mServiceLock here or can get into a deadlock from
5897 // connect() -> disconnect -> updateStatus
5898
5899 auto state = getCameraState(cameraId);
5900
5901 if (state == nullptr) {
5902 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005903 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005904 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005905 }
5906
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005907 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5908 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5909 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005910 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005911 return;
5912 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005913
Biswarup Pal37a75182024-01-16 15:53:35 +00005914 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5915 CameraMetadata cameraInfo;
5916 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005917 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005918 if (res != OK) {
5919 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5920 __FUNCTION__, cameraId.c_str());
5921 } else {
5922 int32_t deviceId = getDeviceId(cameraInfo);
5923 if (deviceId != kDefaultDeviceId) {
5924 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5925 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5926 static_cast<camera_metadata_enum_android_lens_facing_t>(
5927 lensFacingEntry.data.u8[0]);
5928 std::string mappedCameraId;
5929 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5930 mappedCameraId = kVirtualDeviceBackCameraId;
5931 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5932 mappedCameraId = kVirtualDeviceFrontCameraId;
5933 } else {
5934 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5935 __func__);
5936 }
5937 if (!mappedCameraId.empty()) {
5938 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5939 }
5940 }
5941 }
5942 }
5943
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005944 // Collect the logical cameras without holding mStatusLock in updateStatus
5945 // as that can lead to a deadlock(b/162192331).
5946 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005947 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005948 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005949 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005950 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005951 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005952 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5953 auto [deviceId, mappedCameraId] =
5954 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005955
Biswarup Pal37a75182024-01-16 15:53:35 +00005956 if (status != StatusInternal::ENUMERATING) {
5957 // Update torch status if it has a flash unit.
5958 Mutex::Autolock al(mTorchStatusMutex);
5959 TorchModeStatus torchStatus;
5960 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5961 NAME_NOT_FOUND) {
5962 TorchModeStatus newTorchStatus =
5963 status == StatusInternal::PRESENT ?
5964 TorchModeStatus::AVAILABLE_OFF :
5965 TorchModeStatus::NOT_AVAILABLE;
5966 if (torchStatus != newTorchStatus) {
5967 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5968 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005969 }
5970 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005971
Biswarup Pal37a75182024-01-16 15:53:35 +00005972 Mutex::Autolock lock(mStatusListenerLock);
5973 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5974 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005975
Biswarup Pal37a75182024-01-16 15:53:35 +00005976 for (auto& listener : mListenerList) {
5977 bool isVendorListener = listener->isVendorListener();
5978 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5979 listener->getListenerPid(), listener->getListenerUid())) {
5980 ALOGV("Skipping discovery callback for system-only camera device %s",
5981 cameraId.c_str());
5982 continue;
5983 }
5984
5985 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5986 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005987 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005988 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005989 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5990 ret.exceptionCode());
5991 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005992 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005993}
5994
Austin Borgered99f642023-06-01 16:51:35 -07005995void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005996 const std::string& clientPackageName, bool sharedMode) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005997 auto state = getCameraState(cameraId);
5998 if (state == nullptr) {
5999 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07006000 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07006001 return;
6002 }
6003 if (open) {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07006004 if (flags::camera_multi_client() && sharedMode) {
6005 state->addClientPackage(clientPackageName);
6006 } else {
6007 state->setClientPackage(clientPackageName);
6008 }
Shuzhen Wange7aa0342021-08-03 11:29:47 -07006009 } else {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07006010 if (flags::camera_multi_client() && sharedMode) {
6011 state->removeClientPackage(clientPackageName);
6012 } else {
6013 state->setClientPackage(std::string());
6014 }
Shuzhen Wange7aa0342021-08-03 11:29:47 -07006015 }
6016
Biswarup Pal37a75182024-01-16 15:53:35 +00006017 // Get the device id and app-visible camera id for the given HAL-visible camera id.
6018 auto [deviceId, mappedCameraId] =
6019 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
6020
Shuzhen Wang695044d2020-03-06 09:02:23 -08006021 Mutex::Autolock lock(mStatusListenerLock);
6022
6023 for (const auto& it : mListenerList) {
6024 if (!it->isOpenCloseCallbackAllowed()) {
6025 continue;
6026 }
6027
6028 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08006029 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00006030 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
6031 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08006032 } else {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07006033 if (!flags::camera_multi_client() || !sharedMode || (sharedMode &&
6034 mActiveClientManager.getCameraClient(cameraId) == nullptr)) {
6035 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
6036 }
Shuzhen Wang695044d2020-03-06 09:02:23 -08006037 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006038
6039 it->handleBinderStatus(ret,
6040 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
6041 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08006042 }
6043}
6044
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006045template<class Func>
6046void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07006047 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006048 std::initializer_list<StatusInternal> rejectSourceStates,
6049 Func onStatusUpdatedLocked) {
6050 Mutex::Autolock lock(mStatusLock);
6051 StatusInternal oldStatus = mStatus;
6052 mStatus = status;
6053
6054 if (oldStatus == status) {
6055 return;
6056 }
6057
6058 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07006059 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006060
6061 if (oldStatus == StatusInternal::NOT_PRESENT &&
6062 (status != StatusInternal::PRESENT &&
6063 status != StatusInternal::ENUMERATING)) {
6064
6065 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
6066 __FUNCTION__);
6067 mStatus = oldStatus;
6068 return;
6069 }
6070
6071 /**
6072 * Sometimes we want to conditionally do a transition.
6073 * For example if a client disconnects, we want to go to PRESENT
6074 * only if we weren't already in NOT_PRESENT or ENUMERATING.
6075 */
6076 for (auto& rejectStatus : rejectSourceStates) {
6077 if (oldStatus == rejectStatus) {
6078 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07006079 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006080 mStatus = oldStatus;
6081 return;
6082 }
6083 }
6084
6085 onStatusUpdatedLocked(cameraId, status);
6086}
6087
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006088status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07006089 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006090 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006091 if (!status) {
6092 return BAD_VALUE;
6093 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006094 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6095 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006096 // invalid camera ID or the camera doesn't have a flash unit
6097 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006098 }
6099
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006100 *status = mTorchStatusMap.valueAt(index);
6101 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006102}
6103
Austin Borgered99f642023-06-01 16:51:35 -07006104status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006105 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006106 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6107 if (index == NAME_NOT_FOUND) {
6108 return BAD_VALUE;
6109 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006110 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006111
6112 return OK;
6113}
6114
Austin Borgered99f642023-06-01 16:51:35 -07006115std::list<std::string> CameraService::getLogicalCameras(
6116 const std::string& physicalCameraId) {
6117 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006118 Mutex::Autolock lock(mCameraStatesLock);
6119 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006120 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6121 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006122 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006123 }
6124 return retList;
6125}
6126
6127void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006128 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006129 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006130 // mStatusListenerLock is expected to be locked
6131 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006132 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006133 // Note: we check only the deviceKind of the physical camera id
6134 // since, logical camera ids and their physical camera ids are
6135 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006136 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6137 listener->getListenerPid(), listener->getListenerUid())) {
6138 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006139 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006140 continue;
6141 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006142 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006143 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006144 listener->handleBinderStatus(ret,
6145 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6146 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6147 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006148 }
6149 }
6150}
6151
Svet Ganova453d0d2018-01-11 15:37:58 -08006152void CameraService::blockClientsForUid(uid_t uid) {
6153 const auto clients = mActiveClientManager.getAll();
6154 for (auto& current : clients) {
6155 if (current != nullptr) {
6156 const auto basicClient = current->getValue();
6157 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6158 basicClient->block();
6159 }
6160 }
6161 }
6162}
6163
Michael Grooverd1d435a2018-12-18 17:39:42 -08006164void CameraService::blockAllClients() {
6165 const auto clients = mActiveClientManager.getAll();
6166 for (auto& current : clients) {
6167 if (current != nullptr) {
6168 const auto basicClient = current->getValue();
6169 if (basicClient.get() != nullptr) {
6170 basicClient->block();
6171 }
6172 }
6173 }
6174}
6175
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006176void CameraService::blockPrivacyEnabledClients() {
6177 const auto clients = mActiveClientManager.getAll();
6178 for (auto& current : clients) {
6179 if (current != nullptr) {
6180 const auto basicClient = current->getValue();
6181 if (basicClient.get() != nullptr) {
6182 std::string pkgName = basicClient->getPackageName();
6183 bool cameraPrivacyEnabled =
6184 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6185 if (cameraPrivacyEnabled) {
6186 basicClient->block();
6187 }
6188 }
6189 }
6190 }
6191}
6192
Svet Ganova453d0d2018-01-11 15:37:58 -08006193// NOTE: This is a remote API - make sure all args are validated
6194status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006195 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006196 return PERMISSION_DENIED;
6197 }
6198 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6199 return BAD_VALUE;
6200 }
Austin Borgered99f642023-06-01 16:51:35 -07006201 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006202 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006203 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006204 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006205 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006206 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006207 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006208 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006209 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006210 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006211 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006212 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006213 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006214 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006215 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006216 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006217 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006218 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006219 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006220 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006221 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006222 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006223 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006224 handleClearStreamUseCaseOverrides();
6225 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006226 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006227 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006228 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006229 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006230 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006231 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006232 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006233 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006234 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006235 }
6236 printHelp(err);
6237 return BAD_VALUE;
6238}
6239
6240status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006241 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006242
Svet Ganova453d0d2018-01-11 15:37:58 -08006243 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006244 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006245 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006246 } else if ((args[2] != toString16("idle"))) {
6247 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006248 return BAD_VALUE;
6249 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006250
6251 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006252 if (args.size() >= 5 && args[3] == toString16("--user")) {
6253 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006254 }
6255
6256 uid_t uid;
6257 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6258 return BAD_VALUE;
6259 }
6260
6261 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006262 return NO_ERROR;
6263}
6264
6265status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006266 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006267
6268 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006269 if (args.size() >= 4 && args[2] == toString16("--user")) {
6270 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006271 }
6272
6273 uid_t uid;
6274 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006275 return BAD_VALUE;
6276 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006277
6278 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006279 return NO_ERROR;
6280}
6281
6282status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006283 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006284
6285 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006286 if (args.size() >= 4 && args[2] == toString16("--user")) {
6287 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006288 }
6289
6290 uid_t uid;
6291 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006292 return BAD_VALUE;
6293 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006294
6295 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006296 return dprintf(out, "active\n");
6297 } else {
6298 return dprintf(out, "idle\n");
6299 }
6300}
6301
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006302status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006303 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006304 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6305 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6306 Mutex::Autolock lock(mServiceLock);
6307
6308 mOverrideRotateAndCropMode = rotateValue;
6309
6310 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6311
6312 const auto clients = mActiveClientManager.getAll();
6313 for (auto& current : clients) {
6314 if (current != nullptr) {
6315 const auto basicClient = current->getValue();
6316 if (basicClient.get() != nullptr) {
6317 basicClient->setRotateAndCropOverride(rotateValue);
6318 }
6319 }
6320 }
6321
6322 return OK;
6323}
6324
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006325status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6326 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006327 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006328 if ((*end != '\0') ||
6329 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6330 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6331 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6332 return BAD_VALUE;
6333 }
6334
6335 Mutex::Autolock lock(mServiceLock);
6336 mOverrideAutoframingMode = autoframingValue;
6337
6338 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6339
6340 const auto clients = mActiveClientManager.getAll();
6341 for (auto& current : clients) {
6342 if (current != nullptr) {
6343 const auto basicClient = current->getValue();
6344 if (basicClient.get() != nullptr) {
6345 basicClient->setAutoframingOverride(autoframingValue);
6346 }
6347 }
6348 }
6349
6350 return OK;
6351}
6352
Ravneetaeb20dc2022-03-30 05:33:03 +00006353status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006354 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006355
6356 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6357
6358 Mutex::Autolock lock(mServiceLock);
6359
6360 mCameraServiceWatchdogEnabled = enableWatchdog;
6361
6362 const auto clients = mActiveClientManager.getAll();
6363 for (auto& current : clients) {
6364 if (current != nullptr) {
6365 const auto basicClient = current->getValue();
6366 if (basicClient.get() != nullptr) {
6367 basicClient->setCameraServiceWatchdog(enableWatchdog);
6368 }
6369 }
6370 }
6371
6372 return OK;
6373}
6374
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006375status_t CameraService::handleGetRotateAndCrop(int out) {
6376 Mutex::Autolock lock(mServiceLock);
6377
6378 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6379}
6380
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006381status_t CameraService::handleGetAutoframing(int out) {
6382 Mutex::Autolock lock(mServiceLock);
6383
6384 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6385}
6386
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006387status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6388 char *endPtr;
6389 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006390 std::string maskString = toStdString(args[1]);
6391 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006392
6393 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006394 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006395 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6396
6397 Mutex::Autolock lock(mServiceLock);
6398
6399 mImageDumpMask = maskValue;
6400
6401 return OK;
6402}
6403
6404status_t CameraService::handleGetImageDumpMask(int out) {
6405 Mutex::Autolock lock(mServiceLock);
6406
6407 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6408}
6409
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006410status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006411 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006412 if (errno != 0) return BAD_VALUE;
6413
6414 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6415 Mutex::Autolock lock(mServiceLock);
6416
6417 mOverrideCameraMuteMode = (muteValue == 1);
6418
6419 const auto clients = mActiveClientManager.getAll();
6420 for (auto& current : clients) {
6421 if (current != nullptr) {
6422 const auto basicClient = current->getValue();
6423 if (basicClient.get() != nullptr) {
6424 if (basicClient->supportsCameraMute()) {
6425 basicClient->setCameraMute(mOverrideCameraMuteMode);
6426 }
6427 }
6428 }
6429 }
6430
6431 return OK;
6432}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006433
Shuzhen Wang16610a62022-12-15 22:38:07 -08006434status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6435 std::vector<int64_t> useCasesOverride;
6436 for (size_t i = 1; i < args.size(); i++) {
6437 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006438 std::string arg = toStdString(args[i]);
6439 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006440 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006441 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006442 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006443 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006444 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006445 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006446 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006447 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006448 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006449 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006450 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006451 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006452 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6453 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006454 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006455 return BAD_VALUE;
6456 }
6457 useCasesOverride.push_back(useCase);
6458 }
6459
6460 Mutex::Autolock lock(mServiceLock);
6461 mStreamUseCaseOverrides = std::move(useCasesOverride);
6462
6463 return OK;
6464}
6465
6466void CameraService::handleClearStreamUseCaseOverrides() {
6467 Mutex::Autolock lock(mServiceLock);
6468 mStreamUseCaseOverrides.clear();
6469}
6470
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006471status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6472 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006473 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006474 if ((*end != '\0') ||
6475 (zoomOverrideValue != -1 &&
6476 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6477 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6478 return BAD_VALUE;
6479 }
6480
6481 Mutex::Autolock lock(mServiceLock);
6482 mZoomOverrideValue = zoomOverrideValue;
6483
6484 const auto clients = mActiveClientManager.getAll();
6485 for (auto& current : clients) {
6486 if (current != nullptr) {
6487 const auto basicClient = current->getValue();
6488 if (basicClient.get() != nullptr) {
6489 if (basicClient->supportsZoomOverride()) {
6490 basicClient->setZoomOverride(mZoomOverrideValue);
6491 }
6492 }
6493 }
6494 }
6495
6496 return OK;
6497}
6498
Avichal Rakesh84147132021-11-11 17:47:11 -08006499status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006500 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006501 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006502 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006503 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006504 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006505 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006506 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006507 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006508 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006509 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006510 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006511 dprintf(outFd, "Camera service watch commands:\n"
6512 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6513 " starts watching the provided tags for clients with provided package\n"
6514 " recognizes tag shorthands like '3a'\n"
6515 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006516 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006517 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006518 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006519 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006520 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006521 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006522 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006523}
6524
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006525status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6526 Mutex::Autolock lock(mLogLock);
6527 size_t tagsIdx; // index of '-m'
6528 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006529 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006530 if (tagsIdx < args.size() - 1) {
6531 tags = args[tagsIdx + 1];
6532 } else {
6533 dprintf(outFd, "No tags provided.\n");
6534 return BAD_VALUE;
6535 }
6536
6537 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006538 // watch all clients if no clients are provided
6539 String16 clients = toString16(kWatchAllClientsFlag);
6540 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006541 clientsIdx++);
6542 if (clientsIdx < args.size() - 1) {
6543 clients = args[clientsIdx + 1];
6544 }
Austin Borgered99f642023-06-01 16:51:35 -07006545 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006546
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006547 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006548 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006549
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006550 bool serviceLock = tryLock(mServiceLock);
6551 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006552 auto cameraClients = mActiveClientManager.getAll();
6553 for (const auto &clientDescriptor: cameraClients) {
6554 if (clientDescriptor == nullptr) { continue; }
6555 sp<BasicClient> client = clientDescriptor->getValue();
6556 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006557
6558 if (isClientWatchedLocked(client.get())) {
6559 client->startWatchingTags(mMonitorTags, outFd);
6560 numWatchedClients++;
6561 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006562 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006563 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6564
6565 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006566 return OK;
6567}
6568
6569status_t CameraService::stopWatchingTags(int outFd) {
6570 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006571 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006572 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006573
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006574 mWatchedClientPackages.clear();
6575 mWatchedClientsDumpCache.clear();
6576
6577 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006578 auto cameraClients = mActiveClientManager.getAll();
6579 for (const auto &clientDescriptor : cameraClients) {
6580 if (clientDescriptor == nullptr) { continue; }
6581 sp<BasicClient> client = clientDescriptor->getValue();
6582 if (client.get() == nullptr) { continue; }
6583 client->stopWatchingTags(outFd);
6584 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006585 dprintf(outFd, "Stopped watching all clients.\n");
6586 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006587 return OK;
6588}
6589
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006590status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6591 Mutex::Autolock lock(mLogLock);
6592 size_t clearedSize = mWatchedClientsDumpCache.size();
6593 mWatchedClientsDumpCache.clear();
6594 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6595 return OK;
6596}
6597
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006598status_t CameraService::printWatchedTags(int outFd) {
6599 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006600 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006601
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006602 bool printedSomething = false; // tracks if any monitoring information was printed
6603 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006604
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006605 bool serviceLock = tryLock(mServiceLock);
6606 // get all watched clients that are currently connected
6607 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6608 if (clientDescriptor == nullptr) { continue; }
6609
6610 sp<BasicClient> client = clientDescriptor->getValue();
6611 if (client.get() == nullptr) { continue; }
6612 if (!isClientWatchedLocked(client.get())) { continue; }
6613
6614 std::vector<std::string> dumpVector;
6615 client->dumpWatchedEventsToVector(dumpVector);
6616
6617 size_t printIdx = dumpVector.size();
6618 if (printIdx == 0) {
6619 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006620 }
6621
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006622 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006623 const std::string &cameraId = clientDescriptor->getKey();
6624 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006625 while(printIdx > 0) {
6626 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006627 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006628 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006629 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006630 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006631 printedSomething = true;
6632
6633 connectedMonitoredClients.emplace(client->getPackageName());
6634 }
6635 if (serviceLock) { mServiceLock.unlock(); }
6636
6637 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6638 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006639 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006640 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6641 continue;
6642 }
6643
Austin Borgered99f642023-06-01 16:51:35 -07006644 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006645 dprintf(outFd, "%s\n", kv.second.c_str());
6646 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006647 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006648
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006649 if (!printedSomething) {
6650 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006651 }
6652
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006653 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006654}
6655
Avichal Rakesh84147132021-11-11 17:47:11 -08006656// Print all events in vector `events' that came after lastPrintedEvent
6657void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006658 const std::string &cameraId,
6659 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006660 const std::vector<std::string> &events,
6661 const std::string &lastPrintedEvent) {
6662 if (events.empty()) { return; }
6663
6664 // index of lastPrintedEvent in events.
6665 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6666 size_t lastPrintedIdx;
6667 for (lastPrintedIdx = 0;
6668 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6669 lastPrintedIdx++);
6670
6671 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6672
Avichal Rakesh84147132021-11-11 17:47:11 -08006673 // print events in chronological order (latest event last)
6674 size_t idxToPrint = lastPrintedIdx;
6675 do {
6676 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006677 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6678 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006679 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006680}
6681
6682// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6683// command should be interrupted if the user presses the return key, or if user loses any way to
6684// signal interrupt.
6685// If timeoutMs == 0, this function will always return false
6686bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6687 struct timeval startTime;
6688 int startTimeError = gettimeofday(&startTime, nullptr);
6689 if (startTimeError) {
6690 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6691 return true;
6692 }
6693
6694 const nfds_t numFds = 1;
6695 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6696
6697 struct timeval currTime;
6698 char buffer[2];
6699 while(true) {
6700 int currTimeError = gettimeofday(&currTime, nullptr);
6701 if (currTimeError) {
6702 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6703 return true;
6704 }
6705
6706 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6707 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6708 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6709
6710 if (remainingTimeMs <= 0) {
6711 // No user interrupt within timeoutMs, don't interrupt watch command
6712 return false;
6713 }
6714
6715 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6716 if (numFdsUpdated < 0) {
6717 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6718 return true;
6719 }
6720
6721 if (numFdsUpdated == 0) {
6722 // No user input within timeoutMs, don't interrupt watch command
6723 return false;
6724 }
6725
6726 if (!(pollFd.revents & POLLIN)) {
6727 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6728 return true;
6729 }
6730
6731 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6732 if (sizeRead < 0) {
6733 dprintf(outFd, "Error reading user input. Exiting.\n");
6734 return true;
6735 }
6736
6737 if (sizeRead == 0) {
6738 // Reached end of input fd (can happen if input is piped)
6739 // User has no way to signal an interrupt, so interrupt here
6740 return true;
6741 }
6742
6743 if (buffer[0] == '\n') {
6744 // User pressed return, interrupt watch command.
6745 return true;
6746 }
6747 }
6748}
6749
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006750status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6751 int inFd, int outFd) {
6752 // Figure out refresh interval, if present in args
6753 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006754 if (args.size() > 2) {
6755 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006756 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006757 intervalIdx++);
6758
6759 size_t intervalValIdx = intervalIdx + 1;
6760 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006761 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006762 if (errno) { return BAD_VALUE; }
6763 }
6764 }
6765
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006766 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6767 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006768
Avichal Rakesh84147132021-11-11 17:47:11 -08006769 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006770 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006771
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006772 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006773 bool serviceLock = tryLock(mServiceLock);
6774 auto cameraClients = mActiveClientManager.getAll();
6775 if (serviceLock) { mServiceLock.unlock(); }
6776
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006777 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006778 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006779 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006780
6781 sp<BasicClient> client = clientDescriptor->getValue();
6782 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006783 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006784
Austin Borgered99f642023-06-01 16:51:35 -07006785 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006786 // This also initializes the map entries with an empty string
6787 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6788
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006789 std::vector<std::string> latestEvents;
6790 client->dumpWatchedEventsToVector(latestEvents);
6791
6792 if (!latestEvents.empty()) {
6793 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006794 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006795 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006796 latestEvents,
6797 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006798 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006799 }
6800 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006801 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006802 break;
6803 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006804 }
6805 return OK;
6806}
6807
Austin Borgered99f642023-06-01 16:51:35 -07006808void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006809 mWatchedClientPackages.clear();
6810
Austin Borgered99f642023-06-01 16:51:35 -07006811 std::istringstream iss(clients);
6812 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006813
Austin Borgered99f642023-06-01 16:51:35 -07006814 while (std::getline(iss, nextClient, ',')) {
6815 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006816 // Don't need to track any other package if 'all' is present
6817 mWatchedClientPackages.clear();
6818 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6819 break;
6820 }
6821
6822 // track package names
6823 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006824 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006825}
6826
Svet Ganova453d0d2018-01-11 15:37:58 -08006827status_t CameraService::printHelp(int out) {
6828 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006829 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6830 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6831 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006832 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6833 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6834 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006835 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6836 " Valid values 0=false, 1=true, 2=auto\n"
6837 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006838 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6839 " Valid values 0=OFF, 1=ON for JPEG\n"
6840 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006841 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006842 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6843 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6844 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6845 " on. In case the number of usecases is smaller than the number of streams, the\n"
6846 " last use case is assigned to all the remaining streams. In case of multiple\n"
6847 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6848 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6849 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6850 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006851 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6852 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006853 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6854 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006855 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006856 " help print this message\n");
6857}
6858
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006859bool CameraService::isClientWatched(const BasicClient *client) {
6860 Mutex::Autolock lock(mLogLock);
6861 return isClientWatchedLocked(client);
6862}
6863
6864bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6865 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6866 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6867}
6868
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006869int32_t CameraService::updateAudioRestriction() {
6870 Mutex::Autolock lock(mServiceLock);
6871 return updateAudioRestrictionLocked();
6872}
6873
6874int32_t CameraService::updateAudioRestrictionLocked() {
6875 int32_t mode = 0;
6876 // iterate through all active client
6877 for (const auto& i : mActiveClientManager.getAll()) {
6878 const auto clientSp = i->getValue();
6879 mode |= clientSp->getAudioRestriction();
6880 }
6881
6882 bool modeChanged = (mAudioRestriction != mode);
6883 mAudioRestriction = mode;
6884 if (modeChanged) {
6885 mAppOps.setCameraAudioRestriction(mode);
6886 }
6887 return mode;
6888}
6889
Austin Borgered99f642023-06-01 16:51:35 -07006890status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006891 sp<BasicClient> clientSp) {
6892 std::unique_ptr<AutoConditionLock> lock =
6893 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6894 status_t res = NO_ERROR;
6895 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006896 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006897 mInjectionStatusListener->notifyInjectionError(
6898 externalCamId, UNKNOWN_TRANSACTION);
6899 clientSp->notifyError(
6900 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6901 CaptureResultExtras());
6902
6903 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6904 // other clients from connecting in mServiceLockWrapper if held
6905 mServiceLock.unlock();
6906
6907 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006908 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006909 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006910 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006911
6912 // Reacquire mServiceLock
6913 mServiceLock.lock();
6914 }
6915
6916 return res;
6917}
6918
Cliff Wud3a05312021-04-26 23:07:31 +08006919void CameraService::clearInjectionParameters() {
6920 {
6921 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006922 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006923 mInjectionInternalCamId = "";
6924 }
6925 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006926 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006927}
6928
Biswarup Pal37a75182024-01-16 15:53:35 +00006929} // namespace android