blob: dd2e2d823f2c3245a3b78e38b05d50b671e10226 [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>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Joanne Chung02c13d02023-01-16 12:58:05 +000041#include <android/permission/PermissionChecker.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080042#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080043#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/MemoryBase.h>
46#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080049#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070051#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080052#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080053#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070055#include "hidl/HidlCameraService.h"
56#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080057#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070058#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080060#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070062#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000063#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070064#include <utils/Errors.h>
65#include <utils/Log.h>
66#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070067#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080069#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080070#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080071#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070072#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000073#include <binder/IServiceManager.h>
74#include <binder/IActivityManager.h>
Austin Borgered99f642023-06-01 16:51:35 -070075#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080076
Ruben Brunkb2119af2014-05-09 19:57:56 -070077#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
79#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070080#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070081#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070082#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000083#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070084#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080087namespace {
88 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080089 const char* kActivityServiceName = "activity";
90 const char* kSensorPrivacyServiceName = "sensor_privacy";
91 const char* kAppopsServiceName = "appops";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080092}; // namespace anonymous
93
Mathias Agopian65ab4712010-07-14 17:59:35 -070094namespace android {
95
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000097using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070098using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070099using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800100using hardware::ICamera;
101using hardware::ICameraClient;
102using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800103using hardware::camera2::ICameraInjectionCallback;
104using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800105using hardware::camera2::utils::CameraIdAndSessionConfiguration;
106using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108// ----------------------------------------------------------------------------
109// Logging support -- this is for debugging only
110// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700111volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112
Steve Blockb8a80522011-12-20 16:23:08 +0000113#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
114#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115
116static void setLogLevel(int level) {
117 android_atomic_write(level, &gLogLevel);
118}
119
120// ----------------------------------------------------------------------------
121
Austin Borgered99f642023-06-01 16:51:35 -0700122static const std::string sDumpPermission("android.permission.DUMP");
123static const std::string sManageCameraPermission("android.permission.MANAGE_CAMERA");
124static const std::string sCameraPermission("android.permission.CAMERA");
125static const std::string sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
126static const std::string
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700127 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Austin Borgered99f642023-06-01 16:51:35 -0700128static const std::string sCameraOpenCloseListenerPermission(
Shuzhen Wang695044d2020-03-06 09:02:23 -0800129 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Austin Borgered99f642023-06-01 16:51:35 -0700130static const std::string
Cliff Wud8cae102021-03-11 01:37:42 +0800131 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000132// Constant integer for FGS Logging, used to denote the API type for logger
133static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700134const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800135static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
136static constexpr int32_t kSystemNativeClientState =
137 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700138static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700139
Austin Borgered99f642023-06-01 16:51:35 -0700140const std::string CameraService::kOfflineDevice("offline-");
141const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700142
Rucha Katakward9ea6452021-05-06 11:57:16 -0700143// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700144static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700145
Austin Borger74fca042022-05-23 12:41:21 -0700146CameraService::CameraService(
147 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
148 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
149 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800150 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800151 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700152 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700153 mSoundRef(0), mInitialized(false),
154 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000155 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800156 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700157 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
158 if (mMemFd == -1) {
159 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
160 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161}
162
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800163// The word 'System' here does not refer to clients only on the system
164// partition. They just need to have a android system uid.
165static bool doesClientHaveSystemUid() {
166 return (CameraThreadState::getCallingUid() < AID_APP_START);
167}
168
Charles Chena7b613c2023-01-24 21:57:33 +0000169// Enable processes with isolated AID to request the binder
170void CameraService::instantiate() {
171 CameraService::publish(true);
172}
173
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800174void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700175 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800176 return;
177 }
178
179 ALOGV("appops service registered. setting camera audio restriction");
180 mAppOps.setCameraAudioRestriction(mAudioRestriction);
181}
182
Iliyan Malchev8951a972011-04-14 16:55:59 -0700183void CameraService::onFirstRef()
184{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700185
Ruben Brunkcc776712015-02-17 20:18:47 -0800186 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800187
Iliyan Malchev8951a972011-04-14 16:55:59 -0700188 BnCameraService::onFirstRef();
189
Ruben Brunk99e69712015-05-26 17:25:07 -0700190 // Update battery life tracking if service is restarting
191 BatteryNotifier& notifier(BatteryNotifier::getInstance());
192 notifier.noteResetCamera();
193 notifier.noteResetFlashlight();
194
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800195 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800196
Emilian Peevf53f66e2017-04-11 14:29:43 +0100197 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800198 if (res == OK) {
199 mInitialized = true;
200 }
201
Svet Ganova453d0d2018-01-11 15:37:58 -0800202 mUidPolicy = new UidPolicy(this);
203 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800204 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
205 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800206 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800207
208 // appops function setCamerAudioRestriction uses getService which
209 // is blocking till the appops service is ready. To enable early
210 // boot availability for cameraservice, use checkService which is
211 // non blocking and register for notifications
212 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700213 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800214 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700215 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800216 } else {
217 mAppOps.setCameraAudioRestriction(mAudioRestriction);
218 }
219
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700220 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
221 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000222 // Deprecated, so it will fail to register on newer devices
223 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700224 __FUNCTION__);
225 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700226
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700227 if (!AidlCameraService::registerService(this)) {
228 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
229 }
230
Shuzhen Wang24b44152019-09-20 10:38:11 -0700231 // This needs to be last call in this function, so that it's as close to
232 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700233 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700234 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800235}
236
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800237status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800238 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100239
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800240 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000241 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800242 {
243 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800244
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800245 if (nullptr == mCameraProviderManager.get()) {
246 mCameraProviderManager = new CameraProviderManager();
247 res = mCameraProviderManager->initialize(this);
248 if (res != OK) {
249 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
250 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700251 logServiceError("Unable to initialize camera provider manager",
252 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800253 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100254 }
255 }
256
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800257
258 // Setup vendor tags before we call get_camera_info the first time
259 // because HAL might need to setup static vendor keys in get_camera_info
260 // TODO: maybe put this into CameraProviderManager::initialize()?
261 mCameraProviderManager->setUpVendorTags();
262
263 if (nullptr == mFlashlight.get()) {
264 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700265 }
266
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 res = mFlashlight->findFlashUnits();
268 if (res != OK) {
269 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
270 }
271
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000272 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800273 }
274
275
276 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700277 if (getCameraState(cameraId) == nullptr) {
278 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800279 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000280 if (unavailPhysicalIds.count(cameraId) > 0) {
281 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700282 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000283 }
284 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800285 }
286
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700287 // Derive primary rear/front cameras, and filter their charactierstics.
288 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700289 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700290 // Assume internal cameras are advertised from the same
291 // provider. If multiple providers are registered at different time,
292 // and each provider contains multiple internal color cameras, the current
293 // logic may filter the characteristics of more than one front/rear color
294 // cameras.
295 Mutex::Autolock l(mServiceLock);
296 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700297 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700298
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800299 return OK;
300}
301
Austin Borgered99f642023-06-01 16:51:35 -0700302void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700303 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800304 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800305 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700306 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
307 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000308 ALOGV("%s: Skipping torch callback for system-only camera device %s",
309 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700310 continue;
311 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700312 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700313 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700314 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
315 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000316 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
317 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700318 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000319 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
320 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700321 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000322 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
323 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
324 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800325 }
326}
327
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800329 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800330 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800331 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800332 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700333}
334
Emilian Peevaee727d2017-05-04 16:35:48 +0100335void CameraService::onNewProviderRegistered() {
336 enumerateProviders();
337}
338
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700339void CameraService::filterAPI1SystemCameraLocked(
340 const std::vector<std::string> &normalDeviceIds) {
341 mNormalDeviceIdsWithoutSystemCamera.clear();
342 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700343 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700344 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700345 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
346 continue;
347 }
348 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700349 // All system camera ids will necessarily come after public camera
350 // device ids as per the HAL interface contract.
351 break;
352 }
353 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
354 }
355 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
356 mNormalDeviceIdsWithoutSystemCamera.size());
357}
358
Austin Borgered99f642023-06-01 16:51:35 -0700359status_t CameraService::getSystemCameraKind(const std::string& cameraId,
360 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700361 auto state = getCameraState(cameraId);
362 if (state != nullptr) {
363 *kind = state->getSystemCameraKind();
364 return OK;
365 }
366 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700367 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700368}
369
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800370void CameraService::updateCameraNumAndIds() {
371 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700372 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
373 // Excludes hidden secure cameras
374 mNumberOfCameras =
375 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
376 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800377 mNormalDeviceIds =
378 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700379 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800380}
381
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700382void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700383 // To claim to be S Performance primary cameras, the cameras must be
384 // backward compatible. So performance class primary camera Ids must be API1
385 // compatible.
386 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
387 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
388 int facing = -1;
389 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800390 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700391 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800392 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700393 if (facing == -1) {
394 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
395 return;
396 }
397
398 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
399 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700400 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
401 if (res == OK) {
402 mPerfClassPrimaryCameraIds.insert(cameraId);
403 } else {
404 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
405 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
406 break;
407 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700408
409 if (facing == hardware::CAMERA_FACING_BACK) {
410 firstRearCameraSeen = true;
411 }
412 if (facing == hardware::CAMERA_FACING_FRONT) {
413 firstFrontCameraSeen = true;
414 }
415 }
416
417 if (firstRearCameraSeen && firstFrontCameraSeen) {
418 break;
419 }
420 }
421}
422
Austin Borgered99f642023-06-01 16:51:35 -0700423void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700424 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100425 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
426 if (res != OK) {
427 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
428 return;
429 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000430 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700431 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
432 if (res != OK) {
433 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
434 return;
435 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000436 std::vector<std::string> physicalCameraIds;
437 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700438 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100439 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700440 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100441 }
442
443 {
444 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700445 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000446 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100447 }
448
Austin Borgered99f642023-06-01 16:51:35 -0700449 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100450 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700451 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800452
Austin Borgered99f642023-06-01 16:51:35 -0700453 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100454 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800455
456 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700457 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100458}
459
Austin Borgered99f642023-06-01 16:51:35 -0700460void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800461 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700462 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100463 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700464 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100465 }
466
467 {
468 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700469 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100470 }
471}
472
Austin Borgered99f642023-06-01 16:51:35 -0700473void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800474 CameraDeviceStatus newHalStatus) {
475 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700476 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700477
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800478 StatusInternal newStatus = mapToInternal(newHalStatus);
479
Austin Borgered99f642023-06-01 16:51:35 -0700480 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800481
482 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700483 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100484 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700485 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100486
487 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700488 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100489
Austin Borgered99f642023-06-01 16:51:35 -0700490 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700491 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700492 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700493 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700494 return;
495 }
496
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800497 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800498
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800499 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800500 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700501 return;
502 }
503
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800504 if (newStatus == StatusInternal::NOT_PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -0700505 logDeviceRemoved(cameraId, fmt::sprintf("Device status changed from %d to %d", oldStatus,
Ruben Brunka8ca9152015-04-07 14:23:40 -0700506 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800507
508 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
509 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700510 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800511
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800512 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700513 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800514 // Don't do this in updateStatus to avoid deadlock over mServiceLock
515 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700516
Ruben Brunkcc776712015-02-17 20:18:47 -0800517 // Remove cached shim parameters
518 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700519
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800520 // Remove online as well as offline client from the list of active clients,
521 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700522 clientToDisconnectOnline = removeClientLocked(cameraId);
523 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700524 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800525
Austin Borgered99f642023-06-01 16:51:35 -0700526 disconnectClient(cameraId, clientToDisconnectOnline);
527 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700528
Austin Borgered99f642023-06-01 16:51:35 -0700529 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800530 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800531 if (oldStatus == StatusInternal::NOT_PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -0700532 logDeviceAdded(cameraId, fmt::sprintf("Device status changed from %d to %d", oldStatus,
Ruben Brunka8ca9152015-04-07 14:23:40 -0700533 newStatus));
534 }
Austin Borgered99f642023-06-01 16:51:35 -0700535 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700536 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800537}
Igor Murashkincba2c162013-03-20 15:56:31 -0700538
Austin Borgered99f642023-06-01 16:51:35 -0700539void CameraService::onDeviceStatusChanged(const std::string& id,
540 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800541 CameraDeviceStatus newHalStatus) {
542 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700543 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800544
545 StatusInternal newStatus = mapToInternal(newHalStatus);
546
547 std::shared_ptr<CameraState> state = getCameraState(id);
548
549 if (state == nullptr) {
550 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700551 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800552 return;
553 }
554
555 StatusInternal logicalCameraStatus = state->getStatus();
556 if (logicalCameraStatus != StatusInternal::PRESENT &&
557 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
558 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700559 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800560 return;
561 }
562
563 bool updated = false;
564 if (newStatus == StatusInternal::PRESENT) {
565 updated = state->removeUnavailablePhysicalId(physicalId);
566 } else {
567 updated = state->addUnavailablePhysicalId(physicalId);
568 }
569
570 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700571 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800572 if (newStatus == StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -0700573 logDeviceAdded(idCombo, fmt::sprintf("Device status changed to %d", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800574 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700575 logDeviceRemoved(idCombo, fmt::sprintf("Device status changed to %d", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800576 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700577 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
578 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
579 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700580 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700581 return;
582 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800583 Mutex::Autolock lock(mStatusListenerLock);
584 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700585 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
586 listener->getListenerPid(), listener->getListenerUid())) {
587 ALOGV("Skipping discovery callback for system-only camera device %s",
588 id.c_str());
589 continue;
590 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700591 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700592 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700593 listener->handleBinderStatus(ret,
594 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
595 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
596 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800597 }
598 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700599}
600
Austin Borgered99f642023-06-01 16:51:35 -0700601void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800602 if (clientToDisconnect.get() != nullptr) {
603 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700604 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800605 // Notify the client of disconnection
606 clientToDisconnect->notifyError(
607 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
608 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800609 clientToDisconnect->disconnect();
610 }
611}
612
Austin Borgered99f642023-06-01 16:51:35 -0700613void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800614 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700615 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
616 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
617 if (res != OK) {
618 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700619 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700620 return;
621 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800622 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700623 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800624}
625
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700626
Austin Borgered99f642023-06-01 16:51:35 -0700627void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700628 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
629 Mutex::Autolock al(mTorchStatusMutex);
630 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
631}
632
Austin Borgered99f642023-06-01 16:51:35 -0700633void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800634 int32_t newStrengthLevel) {
635 Mutex::Autolock lock(mStatusListenerLock);
636 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700637 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700638 i->handleBinderStatus(ret,
639 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
640 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800641 }
642}
643
Austin Borgered99f642023-06-01 16:51:35 -0700644void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700645 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800646 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700647 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800648
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800649 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800650 status_t res = getTorchStatusLocked(cameraId, &status);
651 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700652 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700653 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800654 return;
655 }
656 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800657 return;
658 }
659
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800660 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800661 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800662 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
663 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664 return;
665 }
666
Ruben Brunkcc776712015-02-17 20:18:47 -0800667 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700668 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700669 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700670 auto iter = mTorchUidMap.find(cameraId);
671 if (iter != mTorchUidMap.end()) {
672 int oldUid = iter->second.second;
673 int newUid = iter->second.first;
674 BatteryNotifier& notifier(BatteryNotifier::getInstance());
675 if (oldUid != newUid) {
676 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800677 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700678 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700679 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800680 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700681 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700682 }
683 iter->second.second = newUid;
684 } else {
685 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800686 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700687 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700688 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700689 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700690 }
691 }
692 }
693 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700694 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800695}
696
Joanne Chung02c13d02023-01-16 12:58:05 +0000697static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
698 permission::PermissionChecker permissionChecker;
699 AttributionSourceState attributionSource{};
700 attributionSource.pid = callingPid;
701 attributionSource.uid = callingUid;
702 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700703 toString16(sSystemCameraPermission), attributionSource, String16(),
704 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000705 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700706 toString16(sCameraPermission), attributionSource, String16(),
707 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000708 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700709}
710
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800711Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700712 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100713 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700714 bool hasSystemCameraPermissions =
715 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
716 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700717 switch (type) {
718 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700719 if (hasSystemCameraPermissions) {
720 *numCameras = static_cast<int>(mNormalDeviceIds.size());
721 } else {
722 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
723 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800724 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700725 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700726 if (hasSystemCameraPermissions) {
727 *numCameras = mNumberOfCameras;
728 } else {
729 *numCameras = mNumberOfCamerasWithoutSystemCamera;
730 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800731 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700732 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800733 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700734 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800735 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
736 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700737 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800738 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739}
740
malikakash82ed4352023-07-21 22:44:34 +0000741Status CameraService::remapCameraIds(const hardware::CameraIdRemapping&
742 cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700743 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000744 const int pid = CameraThreadState::getCallingPid();
745 const int uid = CameraThreadState::getCallingUid();
746 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
747 __FUNCTION__, pid, uid);
748 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
749 "Permission Denial: no permission to configure camera id mapping");
750 }
751 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000752 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000753 if (!parseStatus.isOk()) {
754 return parseStatus;
755 }
756 remapCameraIds(cameraIdRemappingMap);
757 return Status::ok();
758}
759
760Status CameraService::parseCameraIdRemapping(
761 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +0000762 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700763 std::string packageName;
764 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +0000765 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +0000766 packageName = packageIdRemapping.packageName;
Austin Borgered99f642023-06-01 16:51:35 -0700767 if (packageName == "") {
malikakash82ed4352023-07-21 22:44:34 +0000768 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
769 "CameraIdRemapping: Package name cannot be empty");
770 }
malikakash214f6e62023-08-10 23:50:56 +0000771
772 if (packageIdRemapping.cameraIdsToReplace.size()
773 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +0000774 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
775 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700776 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +0000777 }
malikakash214f6e62023-08-10 23:50:56 +0000778 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700779 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
780 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
781 if (cameraIdToReplace == "" || updatedCameraId == "") {
malikakash214f6e62023-08-10 23:50:56 +0000782 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
783 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700784 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000785 }
786 if (cameraIdToReplace == updatedCameraId) {
787 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
788 "CameraIdRemapping: CameraIdToReplace cannot be the same"
789 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -0700790 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000791 }
792 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +0000793 }
794 }
795 return Status::ok();
796}
797
798void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
799 // Acquire mServiceLock and prevent other clients from connecting
800 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
801 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
802
malikakashedb38962023-09-06 00:03:35 +0000803 // Collect all existing clients for camera Ids that are being
804 // remapped in the new cameraIdRemapping, but only if they were being used by a
805 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +0000806 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -0700807 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +0000808 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
809 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700810 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +0000811 id0.c_str(), id1.c_str());
812 auto clientDescriptor = mActiveClientManager.get(id0);
813 if (clientDescriptor != nullptr) {
814 sp<BasicClient> clientSp = clientDescriptor->getValue();
815 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +0000816 // This camera is being used by a targeted packageName and
817 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +0000818 clientsToDisconnect.push_back(clientSp);
819 cameraIdsToUpdate.push_back(id0);
820 }
821 }
822 }
823 }
824
malikakashedb38962023-09-06 00:03:35 +0000825 for (auto& clientSp : clientsToDisconnect) {
826 // We send up ERROR_CAMERA_DEVICE so that the app attempts to reconnect
827 // automatically. Note that this itself can cause clientSp->disconnect() based on the
828 // app's response.
829 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
830 CaptureResultExtras{});
831 }
malikakash82ed4352023-07-21 22:44:34 +0000832
833 // Do not hold mServiceLock while disconnecting clients, but retain the condition
834 // blocking other clients from connecting in mServiceLockWrapper if held.
835 mServiceLock.unlock();
836
malikakashedb38962023-09-06 00:03:35 +0000837 // Clear calling identity for disconnect() PID checks.
838 int64_t token = CameraThreadState::clearCallingIdentity();
839
malikakash82ed4352023-07-21 22:44:34 +0000840 // Disconnect clients.
841 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +0000842 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
843 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +0000844 clientSp->disconnect();
845 }
846
malikakashedb38962023-09-06 00:03:35 +0000847 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
848 clientsToDisconnect.clear();
849
850 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +0000851 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +0000852
853 {
854 Mutex::Autolock lock(mCameraIdRemappingLock);
855 // Update mCameraIdRemapping.
856 mCameraIdRemapping.clear();
857 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
858 }
malikakash82ed4352023-07-21 22:44:34 +0000859}
860
Austin Borgered99f642023-06-01 16:51:35 -0700861std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
862 const std::string& inputCameraId, int clientUid) {
863 std::string packageName = getPackageNameFromUid(clientUid);
864 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +0000865 Mutex::Autolock lock(mCameraIdRemappingLock);
866 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
867 packageMapIter != mCameraIdRemapping.end()) {
868 for (auto& [id0, id1]: packageMapIter->second) {
869 if (id1 == inputCameraId) {
870 cameraIds.push_back(id0);
871 }
872 }
873 }
874 return cameraIds;
875}
876
Austin Borgered99f642023-06-01 16:51:35 -0700877std::string CameraService::resolveCameraId(
878 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +0000879 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -0700880 const std::string& packageName) {
881 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +0000882 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +0000883 packageNameVal = getPackageNameFromUid(clientUid);
884 }
malikakashedb38962023-09-06 00:03:35 +0000885 if (clientUid < AID_APP_START || packageNameVal.empty()) {
886 // We shouldn't remap cameras for processes with system/vendor UIDs.
887 return inputCameraId;
888 }
malikakash82ed4352023-07-21 22:44:34 +0000889 Mutex::Autolock lock(mCameraIdRemappingLock);
890 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
891 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +0000892 auto packageMap = packageMapIter->second;
893 if (auto replacementIdIter = packageMap.find(inputCameraId);
894 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +0000895 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +0000896 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +0000897 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +0000898 replacementIdIter->second.c_str());
899 return replacementIdIter->second;
900 }
901 }
902 return inputCameraId;
903}
904
Austin Borger18b30a72022-10-27 12:20:29 -0700905Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800906 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700907 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100908 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +0000909 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
910 std::string cameraIdStr = resolveCameraId(
911 unresolvedCameraId, CameraThreadState::getCallingUid());
912
Austin Borgered99f642023-06-01 16:51:35 -0700913 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700914 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
915 "characteristics for system only device %s: ", cameraIdStr.c_str());
916 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100917
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800918 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -0700919 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800920 return STATUS_ERROR(ERROR_DISCONNECTED,
921 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700922 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700923 bool hasSystemCameraPermissions =
924 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
925 CameraThreadState::getCallingUid());
926 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
927 if (hasSystemCameraPermissions) {
928 cameraIdBound = mNumberOfCameras;
929 }
930 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800931 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
932 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700933 }
934
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800935 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700936 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800937 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -0700938 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100939 if (err != OK) {
940 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
941 "Error retrieving camera info from device %d: %s (%d)", cameraId,
942 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -0700943 logServiceError(std::string("Error retrieving camera info from device ")
944 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800945 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100946
Ruben Brunkcc776712015-02-17 20:18:47 -0800947 return ret;
948}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700949
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800950std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700951 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
952 auto callingPid = CameraThreadState::getCallingPid();
953 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +0000954 permission::PermissionChecker permissionChecker;
955 AttributionSourceState attributionSource{};
956 attributionSource.pid = callingPid;
957 attributionSource.uid = callingUid;
958 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700959 toString16(sSystemCameraPermission), attributionSource, String16(),
960 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000961 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700962 deviceIds = &mNormalDeviceIds;
963 }
964 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800965 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700966 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800967 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800968 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800969
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700970 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800971}
972
Austin Borgered99f642023-06-01 16:51:35 -0700973std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800974 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -0700975 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800976}
977
Austin Borgered99f642023-06-01 16:51:35 -0700978Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700979 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700980 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -0700981
malikakashedb38962023-09-06 00:03:35 +0000982 const std::string cameraId = resolveCameraId(unresolvedCameraId,
983 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -0700984
Zhijun He2b59be82013-09-25 10:14:30 -0700985 if (!cameraInfo) {
986 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800987 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700988 }
989
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800990 if (!mInitialized) {
991 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -0700992 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800993 return STATUS_ERROR(ERROR_DISCONNECTED,
994 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700995 }
996
Austin Borgered99f642023-06-01 16:51:35 -0700997 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700998 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -0700999 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001000 }
1001
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001002 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001003
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001004 bool overrideForPerfClass =
1005 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001006 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001007 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001008 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001009 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001010 if (res == NAME_NOT_FOUND) {
1011 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001012 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001013 strerror(-res), res);
1014 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001015 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1016 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001017 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001018 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001019 strerror(-res), res);
1020 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001021 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001022 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001023 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1024 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001025 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001026 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001027 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001028 int callingPid = CameraThreadState::getCallingPid();
1029 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001030 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001031 // If it's not calling from cameraserver, check the permission only if
1032 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1033 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +00001034 permission::PermissionChecker permissionChecker;
1035 AttributionSourceState attributionSource{};
1036 attributionSource.pid = callingPid;
1037 attributionSource.uid = callingUid;
1038 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001039 toString16(sCameraPermission), attributionSource, String16(),
1040 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Emilian Peeve20c6372018-08-14 18:45:53 +01001041 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001042 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001043 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001044 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001045 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001046 &tagsRemoved);
1047 if (res != OK) {
1048 cameraInfo->clear();
1049 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1050 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001051 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001052 }
1053 }
1054
1055 if (!tagsRemoved.empty()) {
1056 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1057 tagsRemoved.data(), tagsRemoved.size());
1058 if (res != OK) {
1059 cameraInfo->clear();
1060 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001061 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001062 strerror(-res), res);
1063 }
1064 }
1065
Zhijun He2b59be82013-09-25 10:14:30 -07001066 return ret;
1067}
1068
malikakashedb38962023-09-06 00:03:35 +00001069Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001070 int32_t* torchStrength) {
1071 ATRACE_CALL();
1072 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001073 const std::string cameraId = resolveCameraId(
1074 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001075 if (!mInitialized) {
1076 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1077 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1078 }
1079
1080 if(torchStrength == NULL) {
1081 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1082 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1083 }
1084
Austin Borgered99f642023-06-01 16:51:35 -07001085 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001086 if (res != OK) {
1087 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001088 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001089 strerror(-res), res);
1090 }
1091 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1092 return Status::ok();
1093}
1094
Austin Borgered99f642023-06-01 16:51:35 -07001095std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001096 time_t now = time(nullptr);
1097 char formattedTime[64];
1098 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001099 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001100}
1101
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001102Status CameraService::getCameraVendorTagDescriptor(
1103 /*out*/
1104 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001105 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001106 if (!mInitialized) {
1107 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001108 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001109 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001110 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1111 if (globalDescriptor != nullptr) {
1112 *desc = *(globalDescriptor.get());
1113 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001114 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001115}
1116
Emilian Peev71c73a22017-03-21 16:35:51 +00001117Status CameraService::getCameraVendorTagCache(
1118 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1119 ATRACE_CALL();
1120 if (!mInitialized) {
1121 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1122 return STATUS_ERROR(ERROR_DISCONNECTED,
1123 "Camera subsystem not available");
1124 }
1125 sp<VendorTagDescriptorCache> globalCache =
1126 VendorTagDescriptorCache::getGlobalVendorTagCache();
1127 if (globalCache != nullptr) {
1128 *cache = *(globalCache.get());
1129 }
1130 return Status::ok();
1131}
1132
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001133void CameraService::clearCachedVariables() {
1134 BasicClient::BasicClient::sCameraService = nullptr;
1135}
1136
Austin Borgered99f642023-06-01 16:51:35 -07001137std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001138 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001139 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001140
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001141 int deviceVersion = 0;
1142
Emilian Peevf53f66e2017-04-11 14:29:43 +01001143 status_t res;
1144 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001145 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001146 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001147 if (res != OK || transport == IPCTransport::INVALID) {
1148 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001149 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001150 return std::make_pair(-1, IPCTransport::INVALID) ;
1151 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001152 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001153
Emilian Peevf53f66e2017-04-11 14:29:43 +01001154 hardware::CameraInfo info;
1155 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001156 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001157 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001158 if (res != OK) {
1159 return std::make_pair(-1, IPCTransport::INVALID);
1160 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001161 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001162 if (orientation) {
1163 *orientation = info.orientation;
1164 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001165 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001166
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001167 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001168}
1169
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001170Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001171 switch(err) {
1172 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001173 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001174 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1176 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001177 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001178 return STATUS_ERROR(ERROR_DISCONNECTED,
1179 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001180 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001181 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1182 "Camera HAL encountered error %d: %s",
1183 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001184 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001185}
1186
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001187Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001188 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1189 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001190 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001191 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001192 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
Austin Borgered99f642023-06-01 16:51:35 -07001193 bool forceSlowJpegMode, const std::string& originalCameraId, /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001194 // For HIDL devices
1195 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1196 // Create CameraClient based on device version reported by the HAL.
1197 int deviceVersion = deviceVersionAndTransport.first;
1198 switch(deviceVersion) {
1199 case CAMERA_DEVICE_API_VERSION_1_0:
1200 ALOGE("Camera using old HAL version: %d", deviceVersion);
1201 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1202 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001203 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001204 break;
1205 case CAMERA_DEVICE_API_VERSION_3_0:
1206 case CAMERA_DEVICE_API_VERSION_3_1:
1207 case CAMERA_DEVICE_API_VERSION_3_2:
1208 case CAMERA_DEVICE_API_VERSION_3_3:
1209 case CAMERA_DEVICE_API_VERSION_3_4:
1210 case CAMERA_DEVICE_API_VERSION_3_5:
1211 case CAMERA_DEVICE_API_VERSION_3_6:
1212 case CAMERA_DEVICE_API_VERSION_3_7:
1213 break;
1214 default:
1215 // Should not be reachable
1216 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1217 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1218 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001219 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001220 }
1221 }
1222 if (effectiveApiLevel == API_1) { // Camera1 API route
1223 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001224 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borgered99f642023-06-01 16:51:35 -07001225 packageName, featureId, cameraId,
1226 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001227 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1228 forceSlowJpegMode);
1229 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1230 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001231 } else { // Camera2 API route
1232 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1233 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001234 *client = new CameraDeviceClient(cameraService, tmp,
1235 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1236 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001237 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001238 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001239 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001240 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001241}
1242
Austin Borgered99f642023-06-01 16:51:35 -07001243std::string CameraService::toString(std::set<userid_t> intSet) {
1244 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001245 bool first = true;
1246 for (userid_t i : intSet) {
1247 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001248 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001249 first = false;
1250 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001251 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001252 }
1253 }
Austin Borgered99f642023-06-01 16:51:35 -07001254 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001255}
1256
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001257int32_t CameraService::mapToInterface(TorchModeStatus status) {
1258 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1259 switch (status) {
1260 case TorchModeStatus::NOT_AVAILABLE:
1261 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1262 break;
1263 case TorchModeStatus::AVAILABLE_OFF:
1264 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1265 break;
1266 case TorchModeStatus::AVAILABLE_ON:
1267 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1268 break;
1269 default:
1270 ALOGW("Unknown new flash status: %d", status);
1271 }
1272 return serviceStatus;
1273}
1274
1275CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1276 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1277 switch (status) {
1278 case CameraDeviceStatus::NOT_PRESENT:
1279 serviceStatus = StatusInternal::NOT_PRESENT;
1280 break;
1281 case CameraDeviceStatus::PRESENT:
1282 serviceStatus = StatusInternal::PRESENT;
1283 break;
1284 case CameraDeviceStatus::ENUMERATING:
1285 serviceStatus = StatusInternal::ENUMERATING;
1286 break;
1287 default:
1288 ALOGW("Unknown new HAL device status: %d", status);
1289 }
1290 return serviceStatus;
1291}
1292
1293int32_t CameraService::mapToInterface(StatusInternal status) {
1294 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1295 switch (status) {
1296 case StatusInternal::NOT_PRESENT:
1297 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1298 break;
1299 case StatusInternal::PRESENT:
1300 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1301 break;
1302 case StatusInternal::ENUMERATING:
1303 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1304 break;
1305 case StatusInternal::NOT_AVAILABLE:
1306 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1307 break;
1308 case StatusInternal::UNKNOWN:
1309 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1310 break;
1311 default:
1312 ALOGW("Unknown new internal device status: %d", status);
1313 }
1314 return serviceStatus;
1315}
1316
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001317Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001318 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001319
Austin Borgered99f642023-06-01 16:51:35 -07001320 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001321 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001322 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001323 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001324 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1325 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001326 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001327 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001328 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001329 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001330 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001331 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001332 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001333}
1334
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001335Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001336 /*out*/
1337 CameraParameters* parameters) {
1338
1339 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1340
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001341 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001342
1343 if (parameters == NULL) {
1344 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001345 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001346 }
1347
malikakashedb38962023-09-06 00:03:35 +00001348 std::string unresolvedCameraId = std::to_string(cameraId);
1349 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1350 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001351
1352 // Check if we already have parameters
1353 {
1354 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001355 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001356 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001357 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001358 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001359 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001360 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001361 }
1362 CameraParameters p = cameraState->getShimParams();
1363 if (!p.isEmpty()) {
1364 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001365 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001366 }
1367 }
1368
Jayant Chowdhary12361932018-08-27 14:46:13 -07001369 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001370 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001371 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001372 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001373 // Error already logged by callee
1374 return ret;
1375 }
1376
1377 // Check for parameters again
1378 {
1379 // Scope for service lock
1380 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001381 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001382 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001383 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001384 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001385 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001386 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001387 CameraParameters p = cameraState->getShimParams();
1388 if (!p.isEmpty()) {
1389 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001390 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001391 }
1392 }
1393
Ruben Brunkcc776712015-02-17 20:18:47 -08001394 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1395 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001396 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001397}
1398
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001399// Can camera service trust the caller based on the calling UID?
1400static bool isTrustedCallingUid(uid_t uid) {
1401 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001402 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001403 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001404 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001405 return true;
1406 default:
1407 return false;
1408 }
1409}
1410
Austin Borgered99f642023-06-01 16:51:35 -07001411static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
1412 int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07001413 PermissionController pc;
Austin Borgered99f642023-06-01 16:51:35 -07001414 uid = pc.getPackageUid(toString16(packageName), 0);
Nicholas Sauera3620332019-04-03 14:05:17 -07001415 if (uid <= 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001416 ALOGE("Unknown package: '%s'", packageName.c_str());
1417 dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07001418 return BAD_VALUE;
1419 }
1420
1421 if (userId < 0) {
1422 ALOGE("Invalid user: %d", userId);
1423 dprintf(err, "Invalid user: %d\n", userId);
1424 return BAD_VALUE;
1425 }
1426
1427 uid = multiuser_get_uid(userId, uid);
1428 return NO_ERROR;
1429}
1430
Austin Borgered99f642023-06-01 16:51:35 -07001431Status CameraService::validateConnectLocked(const std::string& cameraId,
1432 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001433 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001434
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001435#ifdef __BRILLO__
1436 UNUSED(clientName8);
1437 UNUSED(clientUid);
1438 UNUSED(clientPid);
1439 UNUSED(originalClientPid);
1440#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001441 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1442 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001443 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001444 return allowed;
1445 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001446#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001447
Jayant Chowdhary12361932018-08-27 14:46:13 -07001448 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001449
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001450 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001451 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1452 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001453 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001454 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001455 }
1456
Ruben Brunkcc776712015-02-17 20:18:47 -08001457 if (getCameraState(cameraId) == nullptr) {
1458 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001459 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001460 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001461 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001462 }
1463
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001464 status_t err = checkIfDeviceIsUsable(cameraId);
1465 if (err != NO_ERROR) {
1466 switch(err) {
1467 case -ENODEV:
1468 case -EBUSY:
1469 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001470 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001471 default:
1472 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001473 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001474 }
1475 }
1476 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001477}
1478
Austin Borgered99f642023-06-01 16:51:35 -07001479Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1480 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001481 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001482 permission::PermissionChecker permissionChecker;
1483 AttributionSourceState attributionSource{};
1484
Jayant Chowdhary12361932018-08-27 14:46:13 -07001485 int callingPid = CameraThreadState::getCallingPid();
1486 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001488 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001489 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001490 clientUid = callingUid;
1491 } else if (!isTrustedCallingUid(callingUid)) {
1492 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1493 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001494 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1495 "Untrusted caller (calling PID %d, UID %d) trying to "
1496 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001497 callingPid, callingUid, cameraId.c_str(),
1498 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001499 }
1500
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001501 // Check if we can trust clientPid
1502 if (clientPid == USE_CALLING_PID) {
1503 clientPid = callingPid;
1504 } else if (!isTrustedCallingUid(callingUid)) {
1505 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1506 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001507 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1508 "Untrusted caller (calling PID %d, UID %d) trying to "
1509 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001510 callingPid, callingUid, cameraId.c_str(),
1511 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001512 }
1513
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001514 if (shouldRejectSystemCameraConnection(cameraId)) {
1515 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1516 cameraId.c_str());
1517 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001518 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001519 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001520 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1521 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001522 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001523 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001524 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001525
1526 }
1527
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001528 // If it's not calling from cameraserver, check the permission if the
1529 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1530 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001531 attributionSource.pid = clientPid;
1532 attributionSource.uid = clientUid;
Austin Borgered99f642023-06-01 16:51:35 -07001533 attributionSource.packageName = clientName;
Joanne Chung02c13d02023-01-16 12:58:05 +00001534 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001535 toString16(sCameraPermission), attributionSource, String16(), AppOpsManager::OP_NONE)
Joanne Chung02c13d02023-01-16 12:58:05 +00001536 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001537 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001538 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001539 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001540 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1541 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001542 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001543 }
1544
Svet Ganova453d0d2018-01-11 15:37:58 -08001545 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001546 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001547 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001548 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1549 clientPid, clientUid);
1550 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001551 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1552 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001553 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001554 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001555 }
1556
Michael Grooverd1d435a2018-12-18 17:39:42 -08001557 // If sensor privacy is enabled then prevent access to the camera
1558 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1559 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1560 return STATUS_ERROR_FMT(ERROR_DISABLED,
1561 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001562 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001563 }
1564
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001565 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1566 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001567 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001568 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001569
Ruben Brunk6267b532015-04-30 17:44:07 -07001570 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001571
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001572 // For non-system clients : Only allow clients who are being used by the current foreground
1573 // device user, unless calling from our own process.
1574 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001575 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001576 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1577 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001578 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001579 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1580 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001581 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001582 }
1583
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001584 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001585}
1586
Austin Borgered99f642023-06-01 16:51:35 -07001587status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001588 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001589 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001590 if (cameraState == nullptr) {
1591 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001592 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001593 return -ENODEV;
1594 }
1595
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001596 StatusInternal currentStatus = cameraState->getStatus();
1597 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001598 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001599 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001600 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001601 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001602 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001603 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001604 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001605 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001606
Ruben Brunkcc776712015-02-17 20:18:47 -08001607 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001608}
1609
Ruben Brunkcc776712015-02-17 20:18:47 -08001610void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001611 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001612
Ruben Brunkcc776712015-02-17 20:18:47 -08001613 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001614 auto clientDescriptor =
1615 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001616 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001617 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1618
1619 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001620 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001621
1622 if (evicted.size() > 0) {
1623 // This should never happen - clients should already have been removed in disconnect
1624 for (auto& i : evicted) {
1625 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001626 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001627 }
1628
1629 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1630 __FUNCTION__);
1631 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001632
1633 // And register a death notification for the client callback. Do
1634 // this last to avoid Binder policy where a nested Binder
1635 // transaction might be pre-empted to service the client death
1636 // notification if the client process dies before linkToDeath is
1637 // invoked.
1638 sp<IBinder> remoteCallback = client->getRemote();
1639 if (remoteCallback != nullptr) {
1640 remoteCallback->linkToDeath(this);
1641 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001642}
1643
Austin Borgered99f642023-06-01 16:51:35 -07001644status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1645 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1646 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001647 /*out*/
1648 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001649 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001650 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001651 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001652 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001653 DescriptorPtr clientDescriptor;
1654 {
1655 if (effectiveApiLevel == API_1) {
1656 // If we are using API1, any existing client for this camera ID with the same remote
1657 // should be returned rather than evicted to allow MediaRecorder to work properly.
1658
1659 auto current = mActiveClientManager.get(cameraId);
1660 if (current != nullptr) {
1661 auto clientSp = current->getValue();
1662 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001663 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001664 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001665 " API level, evicting prior client...");
1666 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001668 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001669 *client = clientSp;
1670 return NO_ERROR;
1671 }
1672 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001673 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001674 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001675
Ruben Brunkcc776712015-02-17 20:18:47 -08001676 // Get current active client PIDs
1677 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1678 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001679
Emilian Peev8131a262017-02-01 12:33:43 +00001680 std::vector<int> priorityScores(ownerPids.size());
1681 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001682
Emilian Peev8131a262017-02-01 12:33:43 +00001683 // Get priority scores of all active PIDs
1684 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1685 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1686 /*out*/&priorityScores[0]);
1687 if (err != OK) {
1688 ALOGE("%s: Priority score query failed: %d",
1689 __FUNCTION__, err);
1690 return err;
1691 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001692
Ruben Brunkcc776712015-02-17 20:18:47 -08001693 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001694 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001695 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001696 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001697 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001698 /* isVendorClient won't get copied over*/ false,
1699 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001700 }
1701 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001702
Ruben Brunkcc776712015-02-17 20:18:47 -08001703 // Get state for the given cameraId
1704 auto state = getCameraState(cameraId);
1705 if (state == nullptr) {
1706 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001707 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001708 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001709 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001710 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001711
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001712 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1713 int32_t actualState = states[states.size() - 1];
1714
1715 // Make descriptor for incoming client. We store the oomScoreOffset
1716 // since we might need it later on new handleEvictionsLocked and
1717 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001718 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001719 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001720 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001721 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001722
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001723 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1724
Ruben Brunkcc776712015-02-17 20:18:47 -08001725 // Find clients that would be evicted
1726 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1727
1728 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1729 // background, so we cannot do evictions
1730 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1731 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1732 " priority).", clientPid);
1733
1734 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001735 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001736 auto incompatibleClients =
1737 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1738
Austin Borgered99f642023-06-01 16:51:35 -07001739 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1740 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1741 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001742 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001743
1744 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001745 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001746 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001747 i->getKey().c_str(),
1748 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001749 i->getOwnerId(), i->getPriority().getScore(),
1750 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001751 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07001752 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
1753 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001754 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001755 }
1756
1757 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001758 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001759 mEventLog.add(msg);
1760
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001761 auto current = mActiveClientManager.get(cameraId);
1762 if (current != nullptr) {
1763 return -EBUSY; // CAMERA_IN_USE
1764 } else {
1765 return -EUSERS; // MAX_CAMERAS_IN_USE
1766 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001767 }
1768
1769 for (auto& i : evicted) {
1770 sp<BasicClient> clientSp = i->getValue();
1771 if (clientSp.get() == nullptr) {
1772 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1773
1774 // TODO: Remove this
1775 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1776 __FUNCTION__);
1777 mActiveClientManager.remove(i);
1778 continue;
1779 }
1780
1781 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07001782 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001783 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001784
Ruben Brunkcc776712015-02-17 20:18:47 -08001785 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07001786 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001787 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1788 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001789 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001790 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07001791 i->getPriority().getState(), cameraId.c_str(),
1792 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001793 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001794
1795 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001796 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001797 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001798 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001799 }
1800
Ruben Brunkcc776712015-02-17 20:18:47 -08001801 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1802 // other clients from connecting in mServiceLockWrapper if held
1803 mServiceLock.unlock();
1804
1805 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001806 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001807
1808 // Destroy evicted clients
1809 for (auto& i : evictedClients) {
1810 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001811 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001812 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001813
Jayant Chowdhary12361932018-08-27 14:46:13 -07001814 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001815
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001816 for (const auto& i : evictedClients) {
1817 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001818 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001819 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1820 if (ret == TIMED_OUT) {
1821 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07001822 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
1823 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001824 return -EBUSY;
1825 }
1826 if (ret != NO_ERROR) {
1827 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07001828 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
1829 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001830 return ret;
1831 }
1832 }
1833
1834 evictedClients.clear();
1835
Ruben Brunkcc776712015-02-17 20:18:47 -08001836 // Once clients have been disconnected, relock
1837 mServiceLock.lock();
1838
1839 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1840 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1841 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001842 }
1843
Ruben Brunkcc776712015-02-17 20:18:47 -08001844 *partial = clientDescriptor;
1845 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001846}
1847
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001848Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001849 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001850 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001851 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001852 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001853 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001854 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001855 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00001856 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001857 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001859
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001860 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001861 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001862
malikakashedb38962023-09-06 00:03:35 +00001863 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
1864 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1865 CameraThreadState::getCallingUid());
1866
Ruben Brunkcc776712015-02-17 20:18:47 -08001867 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001868 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
1869 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001870 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07001871 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001872
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001873 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07001874 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
1875 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001877 }
1878
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001879 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00001880
1881 const sp<IServiceManager> sm(defaultServiceManager());
1882 const auto& mActivityManager = getActivityManager();
1883 if (mActivityManager) {
1884 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
1885 CameraThreadState::getCallingUid(),
1886 CameraThreadState::getCallingPid());
1887 }
1888
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001889 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001890}
1891
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001892bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1893 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001894 // If the client is not a vendor client, don't add listener if
1895 // a) the camera is a publicly hidden secure camera OR
1896 // b) the camera is a system only camera and the client doesn't
1897 // have android.permission.SYSTEM_CAMERA permissions.
1898 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1899 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1900 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001901 return true;
1902 }
1903 return false;
1904}
1905
Austin Borgered99f642023-06-01 16:51:35 -07001906bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001907 // Rules for rejection:
1908 // 1) If cameraserver tries to access this camera device, accept the
1909 // connection.
1910 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001911 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001912 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1913 // and the serving thread is a non hwbinder thread, the client must have
1914 // android.permission.SYSTEM_CAMERA permissions to connect.
1915
1916 int cPid = CameraThreadState::getCallingPid();
1917 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001918 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001919 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1920 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001921 // This isn't a known camera ID, so it's not a system camera
1922 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1923 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001924 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001925
1926 // (1) Cameraserver trying to connect, accept.
1927 if (CameraThreadState::getCallingPid() == getpid()) {
1928 return false;
1929 }
1930 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001931 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001932 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1933 return true;
1934 }
1935 // (3) Here we only check for permissions if it is a system only camera device. This is since
1936 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1937 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1938 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001939 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001940 !hasPermissionsForSystemCamera(cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001941 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1942 cameraId.c_str());
1943 return true;
1944 }
1945
1946 return false;
1947}
1948
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001949Status CameraService::connectDevice(
1950 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07001951 const std::string& unresolvedCameraId,
1952 const std::string& clientPackageName,
1953 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001954 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001955 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001956 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001957 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001958
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001959 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001960 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001961 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001962 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001963 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001964 bool systemNativeClient = false;
1965 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1966 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07001967 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
1968 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001969 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001970 }
malikakashedb38962023-09-06 00:03:35 +00001971 const std::string cameraId = resolveCameraId(
1972 unresolvedCameraId,
1973 CameraThreadState::getCallingUid(),
1974 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001975
1976 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001977 std::string msg =
1978 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
1979 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
1980 cameraId.c_str());
1981 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1982 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001983 }
1984
Austin Borger9bfa0a72022-08-03 17:50:40 -07001985 userid_t clientUserId = multiuser_get_user_id(clientUid);
1986 int callingUid = CameraThreadState::getCallingUid();
1987 if (clientUid == USE_CALLING_UID) {
1988 clientUserId = multiuser_get_user_id(callingUid);
1989 }
1990
1991 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07001992 std::string msg = "Camera disabled by device policy";
1993 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1994 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07001995 }
1996
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001997 // enforce system camera permissions
1998 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001999 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
2000 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07002001 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002002 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002003 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2004 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2005 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002006 }
2007
Austin Borgered99f642023-06-01 16:51:35 -07002008 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2009 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002010 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Chengfei Taobe683db2023-01-31 18:52:49 +00002011 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false,
Austin Borgered99f642023-06-01 16:51:35 -07002012 unresolvedCameraId, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002013
Austin Borgered99f642023-06-01 16:51:35 -07002014 if (!ret.isOk()) {
2015 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002017 }
2018
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002019 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002020 Mutex::Autolock lock(mServiceLock);
2021
2022 // Clear the previous cached logs and reposition the
2023 // file offset to beginning of the file to log new data.
2024 // If either truncate or lseek fails, close the previous file and create a new one.
2025 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2026 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2027 // Close the previous memfd.
2028 close(mMemFd);
2029 // If failure to wipe the data, then create a new file and
2030 // assign the new value to mMemFd.
2031 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2032 if (mMemFd == -1) {
2033 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2034 }
2035 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002036 const sp<IServiceManager> sm(defaultServiceManager());
2037 const auto& mActivityManager = getActivityManager();
2038 if (mActivityManager) {
2039 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2040 CameraThreadState::getCallingUid(),
2041 CameraThreadState::getCallingPid());
2042 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002043 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002044}
2045
Austin Borgered99f642023-06-01 16:51:35 -07002046std::string CameraService::getPackageNameFromUid(int clientUid) {
2047 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002048
2049 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002050 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002051 if (binder == 0) {
2052 ALOGE("Cannot get permission service");
2053 // Return empty package name and the further interaction
2054 // with camera will likely fail
2055 return packageName;
2056 }
2057
2058 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2059 Vector<String16> packages;
2060
2061 permCtrl->getPackagesForUid(clientUid, packages);
2062
2063 if (packages.isEmpty()) {
2064 ALOGE("No packages for calling UID %d", clientUid);
2065 // Return empty package name and the further interaction
2066 // with camera will likely fail
2067 return packageName;
2068 }
2069
2070 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002071 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002072
2073 return packageName;
2074}
2075
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002076template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002077Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2078 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2079 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002080 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002081 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002082 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002083 binder::Status ret = binder::Status::ok();
2084
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002085 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002086 std::string clientPackageName;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002087 if (clientPackageNameMaybe.size() <= 0) {
2088 // NDK calls don't come with package names, but we need one for various cases.
2089 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2090 // do exist. For all authentication cases, all packages under the same UID get the
2091 // same permissions, so picking any associated package name is sufficient. For some
2092 // other cases, this may give inaccurate names for clients in logs.
2093 isNonSystemNdk = true;
2094 int packageUid = (clientUid == USE_CALLING_UID) ?
2095 CameraThreadState::getCallingUid() : clientUid;
2096 clientPackageName = getPackageNameFromUid(packageUid);
2097 } else {
2098 clientPackageName = clientPackageNameMaybe;
2099 }
2100
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002101 int originalClientPid = 0;
2102
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002103 int packagePid = (clientPid == USE_CALLING_PID) ?
2104 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002105 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002106 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002107 static_cast<int>(effectiveApiLevel));
2108
Shuzhen Wang316781a2020-08-18 18:11:01 -07002109 nsecs_t openTimeNs = systemTime();
2110
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002111 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002112 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002113 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002114
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002115 {
2116 // Acquire mServiceLock and prevent other clients from connecting
2117 std::unique_ptr<AutoConditionLock> lock =
2118 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2119
2120 if (lock == nullptr) {
2121 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2122 , clientPid);
2123 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2124 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002125 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002126 }
2127
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002128 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002129 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002130 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2131 return ret;
2132 }
2133
2134 // Check the shim parameters after acquiring lock, if they have already been updated and
2135 // we were doing a shim update, return immediately
2136 if (shimUpdateOnly) {
2137 auto cameraState = getCameraState(cameraId);
2138 if (cameraState != nullptr) {
2139 if (!cameraState->getShimParams().isEmpty()) return ret;
2140 }
2141 }
2142
2143 status_t err;
2144
2145 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002146 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002147 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002148 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2149 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002150 switch (err) {
2151 case -ENODEV:
2152 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2153 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002154 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002155 case -EBUSY:
2156 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2157 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002158 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002159 case -EUSERS:
2160 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2161 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002162 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002163 default:
2164 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2165 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002166 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002167 }
2168 }
2169
2170 if (clientTmp.get() != nullptr) {
2171 // Handle special case for API1 MediaRecorder where the existing client is returned
2172 device = static_cast<CLIENT*>(clientTmp.get());
2173 return ret;
2174 }
2175
2176 // give flashlight a chance to close devices if necessary.
2177 mFlashlight->prepareDeviceOpen(cameraId);
2178
Austin Borger18b30a72022-10-27 12:20:29 -07002179 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002180 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002181 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2182 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002183 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002184 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002185 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002186 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002187 }
2188
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002189 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002190 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002191 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002192 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002193 clientFeatureId, cameraId, api1CameraId, facing,
2194 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002195 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002196 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002197 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002198 return ret;
2199 }
2200 client = static_cast<CLIENT*>(tmp.get());
2201
2202 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2203 __FUNCTION__);
2204
Austin Borgered99f642023-06-01 16:51:35 -07002205 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002206 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002207 if (err != OK) {
2208 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002209 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002210 mServiceLock.unlock();
2211 client->disconnect();
2212 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002213 switch(err) {
2214 case BAD_VALUE:
2215 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002216 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002217 case -EBUSY:
2218 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002219 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002220 case -EUSERS:
2221 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2222 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002223 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002224 case PERMISSION_DENIED:
2225 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002226 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002227 case -EACCES:
2228 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002229 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002230 case -ENODEV:
2231 default:
2232 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002233 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002234 strerror(-err), err);
2235 }
2236 }
2237
2238 // Update shim paremeters for legacy clients
2239 if (effectiveApiLevel == API_1) {
2240 // Assume we have always received a Client subclass for API1
2241 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2242 String8 rawParams = shimClient->getParameters();
2243 CameraParameters params(rawParams);
2244
2245 auto cameraState = getCameraState(cameraId);
2246 if (cameraState != nullptr) {
2247 cameraState->setShimParams(params);
2248 } else {
2249 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002250 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002251 }
2252 }
2253
Ravneetaeb20dc2022-03-30 05:33:03 +00002254 // Enable/disable camera service watchdog
2255 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2256
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002257 // Set rotate-and-crop override behavior
2258 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2259 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002260 } else if (overrideToPortrait && portraitRotation != 0) {
2261 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2262 switch (portraitRotation) {
2263 case 90:
2264 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2265 break;
2266 case 180:
2267 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2268 break;
2269 case 270:
2270 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2271 break;
2272 default:
2273 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2274 break;
2275 }
2276 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002277 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002278 client->setRotateAndCropOverride(
2279 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2280 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2281 }
2282
2283 // Set autoframing override behaviour
2284 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2285 client->setAutoframingOverride(mOverrideAutoframingMode);
2286 } else {
2287 client->setAutoframingOverride(
2288 mCameraServiceProxyWrapper->getAutoframingOverride(
2289 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002290 }
2291
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002292 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002293 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002294 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002295 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002296 client->setCameraMute(
2297 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2298 } else if (isCameraPrivacyEnabled) {
2299 // no camera mute supported, but privacy is on! => disconnect
2300 ALOGI("Camera mute not supported for package: %s, camera id: %s",
Austin Borgered99f642023-06-01 16:51:35 -07002301 client->getPackageName().c_str(), cameraId.c_str());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002302 // Do not hold mServiceLock while disconnecting clients, but
2303 // retain the condition blocking other clients from connecting
2304 // in mServiceLockWrapper if held.
2305 mServiceLock.unlock();
2306 // Clear caller identity temporarily so client disconnect PID
2307 // checks work correctly
2308 int64_t token = CameraThreadState::clearCallingIdentity();
2309 // Note AppOp to trigger the "Unblock" dialog
2310 client->noteAppOp();
2311 client->disconnect();
2312 CameraThreadState::restoreCallingIdentity(token);
2313 // Reacquire mServiceLock
2314 mServiceLock.lock();
2315
2316 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002317 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002318 }
2319
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002320 if (shimUpdateOnly) {
2321 // If only updating legacy shim parameters, immediately disconnect client
2322 mServiceLock.unlock();
2323 client->disconnect();
2324 mServiceLock.lock();
2325 } else {
2326 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002327 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002328 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002329
2330 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002331 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002332 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002333 } // lock is destroyed, allow further connect calls
2334
2335 // Important: release the mutex here so the client can call back into the service from its
2336 // destructor (can be at the end of the call)
2337 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002338
2339 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002340 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002341 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002342
Cliff Wud3a05312021-04-26 23:07:31 +08002343 {
2344 Mutex::Autolock lock(mInjectionParametersLock);
2345 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2346 mInjectionInitPending = false;
2347 status_t res = NO_ERROR;
2348 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2349 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002350 sp<BasicClient> clientSp = clientDescriptor->getValue();
2351 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2352 if(res != OK) {
2353 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2354 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002355 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002356 }
2357 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002358 if (res != OK) {
2359 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2360 }
2361 } else {
2362 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002363 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002364 res = NO_INIT;
2365 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2366 }
2367 }
2368 }
2369
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002370 return ret;
2371}
2372
Austin Borgered99f642023-06-01 16:51:35 -07002373status_t CameraService::addOfflineClient(const std::string &cameraId,
2374 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002375 if (offlineClient.get() == nullptr) {
2376 return BAD_VALUE;
2377 }
2378
2379 {
2380 // Acquire mServiceLock and prevent other clients from connecting
2381 std::unique_ptr<AutoConditionLock> lock =
2382 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2383
2384 if (lock == nullptr) {
2385 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2386 , __FUNCTION__, offlineClient->getClientPid());
2387 return TIMED_OUT;
2388 }
2389
2390 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2391 if (onlineClientDesc.get() == nullptr) {
2392 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2393 cameraId.c_str());
2394 return BAD_VALUE;
2395 }
2396
2397 // Offline clients do not evict or conflict with other online devices. Resource sharing
2398 // conflicts are handled by the camera provider which will either succeed or fail before
2399 // reaching this method.
2400 const auto& onlinePriority = onlineClientDesc->getPriority();
2401 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2402 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002403 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002404 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002405 // native clients don't have offline processing support.
2406 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002407 if (offlineClientDesc == nullptr) {
2408 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2409 return BAD_VALUE;
2410 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002411
2412 // Allow only one offline device per camera
2413 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2414 if (!incompatibleClients.empty()) {
2415 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2416 return BAD_VALUE;
2417 }
2418
Austin Borgered99f642023-06-01 16:51:35 -07002419 std::string monitorTags = isClientWatched(offlineClient.get())
2420 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002421 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002422 if (err != OK) {
2423 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2424 return err;
2425 }
2426
2427 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2428 if (evicted.size() > 0) {
2429 for (auto& i : evicted) {
2430 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002431 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002432 }
2433
2434 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2435 "properly", __FUNCTION__);
2436
2437 return BAD_VALUE;
2438 }
2439
2440 logConnectedOffline(offlineClientDesc->getKey(),
2441 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002442 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002443
2444 sp<IBinder> remoteCallback = offlineClient->getRemote();
2445 if (remoteCallback != nullptr) {
2446 remoteCallback->linkToDeath(this);
2447 }
2448 } // lock is destroyed, allow further connect calls
2449
2450 return OK;
2451}
2452
Austin Borgered99f642023-06-01 16:51:35 -07002453Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002454 int32_t torchStrength,
Rucha Katakwar38284522021-11-10 11:25:21 -08002455 const sp<IBinder>& clientBinder) {
2456 Mutex::Autolock lock(mServiceLock);
2457
2458 ATRACE_CALL();
2459 if (clientBinder == nullptr) {
2460 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2461 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2462 "Torch client binder in null.");
2463 }
2464
Rucha Katakwar38284522021-11-10 11:25:21 -08002465 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002466 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002467 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002468 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002469 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002470 }
2471
2472 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002473 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002474 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002475 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002476 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002477 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002478 }
2479
2480 StatusInternal cameraStatus = state->getStatus();
2481 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2482 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002483 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002484 (int)cameraStatus);
2485 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002486 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002487 }
2488
2489 {
2490 Mutex::Autolock al(mTorchStatusMutex);
2491 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002492 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002493 if (err != OK) {
2494 if (err == NAME_NOT_FOUND) {
2495 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002496 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002497 }
2498 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002499 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002500 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2501 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002502 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002503 }
2504
2505 if (status == TorchModeStatus::NOT_AVAILABLE) {
2506 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2507 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002508 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002509 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2510 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002511 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002512 } else {
2513 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002514 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002515 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2516 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002517 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002518 }
2519 }
2520 }
2521
2522 {
2523 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002524 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002525 }
2526 // Check if the current torch strength level is same as the new one.
2527 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002528 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002529
Austin Borgered99f642023-06-01 16:51:35 -07002530 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002531
2532 if (err != OK) {
2533 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002534 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002535 switch (err) {
2536 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002537 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2538 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002539 errorCode = ERROR_ILLEGAL_ARGUMENT;
2540 break;
2541 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002542 msg = fmt::sprintf("Camera \"%s\" is in use",
2543 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002544 errorCode = ERROR_CAMERA_IN_USE;
2545 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002546 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002547 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002548 "valid range.", torchStrength);
2549 errorCode = ERROR_ILLEGAL_ARGUMENT;
2550 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002551 default:
Austin Borgered99f642023-06-01 16:51:35 -07002552 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002553 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002554 }
Austin Borgered99f642023-06-01 16:51:35 -07002555 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2556 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002557 }
2558
2559 {
2560 // update the link to client's death
2561 // Store the last client that turns on each camera's torch mode.
2562 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002563 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002564 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002565 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002566 } else {
2567 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2568 mTorchClientMap.replaceValueAt(index, clientBinder);
2569 }
2570 clientBinder->linkToDeath(this);
2571 }
2572
2573 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002574 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002575 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002576 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002577 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002578 }
2579 return Status::ok();
2580}
2581
Austin Borgered99f642023-06-01 16:51:35 -07002582Status CameraService::setTorchMode(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002583 bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002584 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002585 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002586
2587 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002588 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002589 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002590 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2591 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002592 }
2593
Jayant Chowdhary12361932018-08-27 14:46:13 -07002594 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002595 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002596
Austin Borgered99f642023-06-01 16:51:35 -07002597 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002598 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002599 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002600 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002601 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002602 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002603 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002604 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002605 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002606 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002607 }
2608
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002609 StatusInternal cameraStatus = state->getStatus();
2610 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002611 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002612 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2613 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002614 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002615 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002616 }
2617
2618 {
2619 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002620 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002621 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002622 if (err != OK) {
2623 if (err == NAME_NOT_FOUND) {
2624 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002625 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002626 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002627 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002628 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002629 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002630 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002631 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002632 }
2633
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002634 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002635 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002636 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002637 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002638 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2639 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002640 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002641 } else {
2642 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002643 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002644 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2645 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002646 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002647 }
2648 }
2649 }
2650
Ruben Brunk99e69712015-05-26 17:25:07 -07002651 {
2652 // Update UID map - this is used in the torch status changed callbacks, so must be done
2653 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002654 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002655 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002656 }
2657
Austin Borgered99f642023-06-01 16:51:35 -07002658 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002660 if (err != OK) {
2661 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002662 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002663 switch (err) {
2664 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002665 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2666 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002667 errorCode = ERROR_ILLEGAL_ARGUMENT;
2668 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002669 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002670 msg = fmt::sprintf("Camera \"%s\" is in use",
2671 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002672 errorCode = ERROR_CAMERA_IN_USE;
2673 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002674 default:
Austin Borgered99f642023-06-01 16:51:35 -07002675 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002676 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002677 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002678 errorCode = ERROR_INVALID_OPERATION;
2679 }
Austin Borgered99f642023-06-01 16:51:35 -07002680 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2681 logServiceError(msg, errorCode);
2682 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002683 }
2684
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002685 {
2686 // update the link to client's death
2687 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002688 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002689 if (enabled) {
2690 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002691 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002692 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002693 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002694 mTorchClientMap.replaceValueAt(index, clientBinder);
2695 }
2696 clientBinder->linkToDeath(this);
2697 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002698 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002699 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002700 }
2701
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002702 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07002703 std::string torchState = enabled ? "on" : "off";
2704 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
2705 torchState.c_str(), clientPid);
2706 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002707 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002708}
2709
Austin Borgered99f642023-06-01 16:51:35 -07002710void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
2711 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
2712 mTorchUidMap[cameraId].first = uid;
2713 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002714 } else {
2715 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07002716 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002717 }
2718}
2719
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002720Status CameraService::notifySystemEvent(int32_t eventId,
2721 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002722 const int pid = CameraThreadState::getCallingPid();
2723 const int selfPid = getpid();
2724
2725 // Permission checks
2726 if (pid != selfPid) {
2727 // Ensure we're being called by system_server, or similar process with
2728 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002729 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002730 const int uid = CameraThreadState::getCallingUid();
2731 ALOGE("Permission Denial: cannot send updates to camera service about system"
2732 " events from pid=%d, uid=%d", pid, uid);
2733 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002734 "No permission to send updates to camera service about system events"
2735 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002736 }
2737 }
2738
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002739 ATRACE_CALL();
2740
Ruben Brunk36597b22015-03-20 22:15:57 -07002741 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002742 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002743 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002744 // from a system server crash
2745 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002746 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002747 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002748 break;
2749 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002750 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2751 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00002752 if (args.size() != 1) {
2753 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
2754 "USB Device Event requires 1 argument");
2755 }
2756
Valentin Iftime29e2e152021-08-13 15:17:33 +02002757 // Notify CameraProviderManager for lazy HALs
2758 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2759 std::to_string(args[0]));
2760 break;
2761 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002762 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002763 default: {
2764 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2765 eventId);
2766 break;
2767 }
2768 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002769 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002770}
2771
Emilian Peev53722fa2019-02-22 17:47:20 -08002772void CameraService::notifyMonitoredUids() {
2773 Mutex::Autolock lock(mStatusListenerLock);
2774
2775 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002776 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002777 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2778 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002779 }
2780}
2781
Austin Borgerdddb7552023-03-30 17:53:01 -07002782void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
2783 Mutex::Autolock lock(mStatusListenerLock);
2784
2785 for (const auto& it : mListenerList) {
2786 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
2787 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
2788 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
2789 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2790 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
2791 }
2792 }
2793}
2794
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002795Status CameraService::notifyDeviceStateChange(int64_t newState) {
2796 const int pid = CameraThreadState::getCallingPid();
2797 const int selfPid = getpid();
2798
2799 // Permission checks
2800 if (pid != selfPid) {
2801 // Ensure we're being called by system_server, or similar process with
2802 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002803 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002804 const int uid = CameraThreadState::getCallingUid();
2805 ALOGE("Permission Denial: cannot send updates to camera service about device"
2806 " state changes from pid=%d, uid=%d", pid, uid);
2807 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2808 "No permission to send updates to camera service about device state"
2809 " changes from pid=%d, uid=%d", pid, uid);
2810 }
2811 }
2812
2813 ATRACE_CALL();
2814
Austin Borger18b30a72022-10-27 12:20:29 -07002815 {
2816 Mutex::Autolock lock(mServiceLock);
2817 mDeviceState = newState;
2818 }
2819
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002820 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002821
2822 return Status::ok();
2823}
2824
Emilian Peev8b64f282021-03-25 16:49:57 -07002825Status CameraService::notifyDisplayConfigurationChange() {
2826 ATRACE_CALL();
2827 const int callingPid = CameraThreadState::getCallingPid();
2828 const int selfPid = getpid();
2829
2830 // Permission checks
2831 if (callingPid != selfPid) {
2832 // Ensure we're being called by system_server, or similar process with
2833 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002834 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07002835 const int uid = CameraThreadState::getCallingUid();
2836 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2837 " changes from pid=%d, uid=%d", callingPid, uid);
2838 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2839 "No permission to send updates to camera service about orientation"
2840 " changes from pid=%d, uid=%d", callingPid, uid);
2841 }
2842 }
2843
2844 Mutex::Autolock lock(mServiceLock);
2845
2846 // Don't do anything if rotate-and-crop override via cmd is active
2847 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2848
2849 const auto clients = mActiveClientManager.getAll();
2850 for (auto& current : clients) {
2851 if (current != nullptr) {
2852 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002853 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2854 basicClient->setRotateAndCropOverride(
2855 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2856 basicClient->getPackageName(),
2857 basicClient->getCameraFacing(),
2858 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002859 }
2860 }
2861 }
2862
2863 return Status::ok();
2864}
2865
2866Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002867 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2868 ATRACE_CALL();
2869 if (!concurrentCameraIds) {
2870 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2871 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2872 }
2873
2874 if (!mInitialized) {
2875 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07002876 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002877 return STATUS_ERROR(ERROR_DISCONNECTED,
2878 "Camera subsystem is not available");
2879 }
2880 // First call into the provider and get the set of concurrent camera
2881 // combinations
2882 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002883 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002884 for (auto &combination : concurrentCameraCombinations) {
2885 std::vector<std::string> validCombination;
2886 for (auto &cameraId : combination) {
2887 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07002888 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002889 if (state == nullptr) {
2890 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2891 continue;
2892 }
2893 StatusInternal status = state->getStatus();
2894 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2895 continue;
2896 }
Austin Borgered99f642023-06-01 16:51:35 -07002897 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002898 continue;
2899 }
2900 validCombination.push_back(cameraId);
2901 }
2902 if (validCombination.size() != 0) {
2903 concurrentCameraIds->push_back(std::move(validCombination));
2904 }
2905 }
2906 return Status::ok();
2907}
2908
2909Status CameraService::isConcurrentSessionConfigurationSupported(
2910 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002911 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002912 if (!isSupported) {
2913 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2914 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2915 }
2916
2917 if (!mInitialized) {
2918 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2919 return STATUS_ERROR(ERROR_DISCONNECTED,
2920 "Camera subsystem is not available");
2921 }
2922
2923 // Check for camera permissions
2924 int callingPid = CameraThreadState::getCallingPid();
2925 int callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002926 permission::PermissionChecker permissionChecker;
2927 AttributionSourceState attributionSource{};
2928 attributionSource.pid = callingPid;
2929 attributionSource.uid = callingUid;
2930 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07002931 toString16(sCameraPermission), attributionSource, String16(),
2932 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +00002933 if ((callingPid != getpid()) && !checkPermissionForCamera) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002934 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2935 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2936 "android.permission.CAMERA needed to call"
2937 "isConcurrentSessionConfigurationSupported");
2938 }
2939
2940 status_t res =
2941 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002942 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2943 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002944 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07002945 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07002946 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002947 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2948 "support %s (%d)", strerror(-res), res);
2949 }
2950 return Status::ok();
2951}
2952
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002953Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2954 /*out*/
2955 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002956 return addListenerHelper(listener, cameraStatuses);
2957}
2958
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002959binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2960 std::vector<hardware::CameraStatus>* cameraStatuses) {
2961 return addListenerHelper(listener, cameraStatuses, false, true);
2962}
2963
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002964Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2965 /*out*/
2966 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002967 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002968
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002969 ATRACE_CALL();
2970
Igor Murashkinbfc99152013-02-27 12:55:20 -08002971 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002972
Ruben Brunk3450ba72015-06-16 11:00:37 -07002973 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002974 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002975 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002976 }
2977
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002978 auto clientUid = CameraThreadState::getCallingUid();
2979 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002980 permission::PermissionChecker permissionChecker;
2981 AttributionSourceState attributionSource{};
2982 attributionSource.uid = clientUid;
2983 attributionSource.pid = clientPid;
2984 bool openCloseCallbackAllowed = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07002985 toString16(sCameraOpenCloseListenerPermission), attributionSource, String16(),
Joanne Chung02c13d02023-01-16 12:58:05 +00002986 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002987
Igor Murashkinbfc99152013-02-27 12:55:20 -08002988 Mutex::Autolock lock(mServiceLock);
2989
Ruben Brunkcc776712015-02-17 20:18:47 -08002990 {
2991 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002992 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002993 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002994 ALOGW("%s: Tried to add listener %p which was already subscribed",
2995 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002996 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002997 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002998 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002999
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003000 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003001 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3002 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003003 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003004 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003005 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003006 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003007 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3008 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3009 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003010 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003011 // The listener still needs to be added to the list of listeners, regardless of what
3012 // permissions the listener process has / whether it is a vendor listener. Since it might be
3013 // eligible to listen to other camera ids.
3014 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003015 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003016 }
3017
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003018 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003019 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003020 Mutex::Autolock lock(mCameraStatesLock);
3021 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003022 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003023 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003024 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003025 }
3026 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003027 // Remove the camera statuses that should be hidden from the client, we do
3028 // this after collecting the states in order to avoid holding
3029 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3030 // the same time.
3031 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3032 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3033 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3034 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3035 ALOGE("%s: Invalid camera id %s, skipping status update",
3036 __FUNCTION__, s.cameraId.c_str());
3037 return true;
3038 }
3039 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3040 clientUid);}), cameraStatuses->end());
3041
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003042 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003043 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003044 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003045 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003046 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003047
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003048 /*
3049 * Immediately signal current torch status to this listener only
3050 * This may be a subset of all the devices, so don't include it in the response directly
3051 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003052 {
3053 Mutex::Autolock al(mTorchStatusMutex);
3054 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003055 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003056 // The camera id is visible to the client. Fine to send torch
3057 // callback.
3058 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3059 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3060 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003061 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003062 }
3063
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003064 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003065}
Ruben Brunkcc776712015-02-17 20:18:47 -08003066
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003067Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003068 ATRACE_CALL();
3069
Igor Murashkinbfc99152013-02-27 12:55:20 -08003070 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3071
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003072 if (listener == 0) {
3073 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003074 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003075 }
3076
Igor Murashkinbfc99152013-02-27 12:55:20 -08003077 Mutex::Autolock lock(mServiceLock);
3078
Ruben Brunkcc776712015-02-17 20:18:47 -08003079 {
3080 Mutex::Autolock lock(mStatusListenerLock);
3081 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003082 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003083 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003084 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003085 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003086 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003087 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003088 }
3089 }
3090
3091 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3092 __FUNCTION__, listener.get());
3093
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003094 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003095}
3096
Austin Borgered99f642023-06-01 16:51:35 -07003097Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003098
3099 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003100 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3101
3102 if (parameters == NULL) {
3103 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003104 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003105 }
3106
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003107 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003108
3109 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003110 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003111 // Error logged by caller
3112 return ret;
3113 }
3114
3115 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003116
Austin Borgered99f642023-06-01 16:51:35 -07003117 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003118
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003119 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003120}
3121
Austin Borgered99f642023-06-01 16:51:35 -07003122Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003123 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003124 ATRACE_CALL();
3125
malikakashedb38962023-09-06 00:03:35 +00003126 const std::string cameraId = resolveCameraId(
3127 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003128
Austin Borgered99f642023-06-01 16:51:35 -07003129 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003130
3131 switch (apiVersion) {
3132 case API_VERSION_1:
3133 case API_VERSION_2:
3134 break;
3135 default:
Austin Borgered99f642023-06-01 16:51:35 -07003136 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3137 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3138 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003139 }
3140
Austin Borger18b30a72022-10-27 12:20:29 -07003141 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003142 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003143 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003144 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3145 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3146 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003147 }
3148 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3149 int deviceVersion = deviceVersionAndTransport.first;
3150 switch (deviceVersion) {
3151 case CAMERA_DEVICE_API_VERSION_1_0:
3152 case CAMERA_DEVICE_API_VERSION_3_0:
3153 case CAMERA_DEVICE_API_VERSION_3_1:
3154 if (apiVersion == API_VERSION_2) {
3155 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003156 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003157 *isSupported = false;
3158 } else { // if (apiVersion == API_VERSION_1) {
3159 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003160 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003161 *isSupported = true;
3162 }
3163 break;
3164 case CAMERA_DEVICE_API_VERSION_3_2:
3165 case CAMERA_DEVICE_API_VERSION_3_3:
3166 case CAMERA_DEVICE_API_VERSION_3_4:
3167 case CAMERA_DEVICE_API_VERSION_3_5:
3168 case CAMERA_DEVICE_API_VERSION_3_6:
3169 case CAMERA_DEVICE_API_VERSION_3_7:
3170 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003171 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003172 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003173 break;
3174 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003175 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3176 deviceVersion, cameraId.c_str());
3177 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3178 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003179 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003180 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003181 } else {
3182 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003183 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003184 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003185}
3186
Austin Borgered99f642023-06-01 16:51:35 -07003187Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003188 /*out*/ bool *isSupported) {
3189 ATRACE_CALL();
3190
malikakashedb38962023-09-06 00:03:35 +00003191 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3192 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003193
Austin Borgered99f642023-06-01 16:51:35 -07003194 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3195 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003196
3197 return Status::ok();
3198}
3199
Cliff Wud8cae102021-03-11 01:37:42 +08003200Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003201 const std::string& packageName, const std::string& internalCamId,
3202 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003203 const sp<ICameraInjectionCallback>& callback,
3204 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003205 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003206 ATRACE_CALL();
3207
Austin Borgered99f642023-06-01 16:51:35 -07003208 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003209 const int pid = CameraThreadState::getCallingPid();
3210 const int uid = CameraThreadState::getCallingUid();
3211 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3212 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3213 "Permission Denial: no permission to inject camera");
3214 }
3215
3216 ALOGV(
3217 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3218 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003219 __FUNCTION__, packageName.c_str(),
3220 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003221
Cliff Wud3a05312021-04-26 23:07:31 +08003222 {
3223 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003224 mInjectionInternalCamId = internalCamId;
3225 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003226 mInjectionStatusListener->addListener(callback);
3227 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003228 status_t res = NO_ERROR;
3229 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3230 // If the client already exists, we can directly connect to the camera device through the
3231 // client's injectCamera(), otherwise we need to wait until the client is established
3232 // (execute connectHelper()) before injecting the camera to the camera device.
3233 if (clientDescriptor != nullptr) {
3234 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003235 sp<BasicClient> clientSp = clientDescriptor->getValue();
3236 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3237 if(res != OK) {
3238 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3239 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003240 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003241 }
3242 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003243 if(res != OK) {
3244 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3245 }
3246 } else {
3247 mInjectionInitPending = true;
3248 }
3249 }
Cliff Wud8cae102021-03-11 01:37:42 +08003250
Cliff Wud3a05312021-04-26 23:07:31 +08003251 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003252}
3253
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003254Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003255 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003256 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3257 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3258 return Status::ok();
3259}
3260
Ruben Brunkcc776712015-02-17 20:18:47 -08003261void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003262 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003263 for (auto& i : mActiveClientManager.getAll()) {
3264 auto clientSp = i->getValue();
3265 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003266 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003267 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003268 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003269 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003270 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003271}
3272
Ruben Brunkcc776712015-02-17 20:18:47 -08003273bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003274 bool ret = false;
3275 {
3276 // Acquire mServiceLock and prevent other clients from connecting
3277 std::unique_ptr<AutoConditionLock> lock =
3278 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003279
Igor Murashkin634a5152013-02-20 17:15:11 -08003280
Ruben Brunkcc776712015-02-17 20:18:47 -08003281 std::vector<sp<BasicClient>> evicted;
3282 for (auto& i : mActiveClientManager.getAll()) {
3283 auto clientSp = i->getValue();
3284 if (clientSp.get() == nullptr) {
3285 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3286 mActiveClientManager.remove(i);
3287 continue;
3288 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003289 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003290 mActiveClientManager.remove(i);
3291 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003292
Ruben Brunkcc776712015-02-17 20:18:47 -08003293 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003294 clientSp->notifyError(
3295 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003296 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003297 }
3298 }
3299
Ruben Brunkcc776712015-02-17 20:18:47 -08003300 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3301 // other clients from connecting in mServiceLockWrapper if held
3302 mServiceLock.unlock();
3303
Ruben Brunk36597b22015-03-20 22:15:57 -07003304 // Do not clear caller identity, remote caller should be client proccess
3305
Ruben Brunkcc776712015-02-17 20:18:47 -08003306 for (auto& i : evicted) {
3307 if (i.get() != nullptr) {
3308 i->disconnect();
3309 ret = true;
3310 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003311 }
3312
Ruben Brunkcc776712015-02-17 20:18:47 -08003313 // Reacquire mServiceLock
3314 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003315
Ruben Brunkcc776712015-02-17 20:18:47 -08003316 } // lock is destroyed, allow further connect calls
3317
3318 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003319}
3320
Ruben Brunkcc776712015-02-17 20:18:47 -08003321std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003322 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003323 std::shared_ptr<CameraState> state;
3324 {
3325 Mutex::Autolock lock(mCameraStatesLock);
3326 auto iter = mCameraStates.find(cameraId);
3327 if (iter != mCameraStates.end()) {
3328 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003329 }
3330 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003331 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003332}
3333
Austin Borgered99f642023-06-01 16:51:35 -07003334sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003335 // Remove from active clients list
3336 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3337 if (clientDescriptorPtr == nullptr) {
3338 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003339 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003340 return sp<BasicClient>{nullptr};
3341 }
3342
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003343 sp<BasicClient> client = clientDescriptorPtr->getValue();
3344 if (client.get() != nullptr) {
3345 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3346 }
3347 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003348}
3349
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003350void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003351 // Acquire mServiceLock and prevent other clients from connecting
3352 std::unique_ptr<AutoConditionLock> lock =
3353 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3354
Ruben Brunk6267b532015-04-30 17:44:07 -07003355 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003356 for (size_t i = 0; i < newUserIds.size(); i++) {
3357 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003358 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003359 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003360 return;
3361 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003362 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003363 }
3364
Ruben Brunka8ca9152015-04-07 14:23:40 -07003365
Ruben Brunk6267b532015-04-30 17:44:07 -07003366 if (newAllowedUsers == mAllowedUsers) {
3367 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3368 return;
3369 }
3370
3371 logUserSwitch(mAllowedUsers, newAllowedUsers);
3372
3373 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003374
3375 // Current user has switched, evict all current clients.
3376 std::vector<sp<BasicClient>> evicted;
3377 for (auto& i : mActiveClientManager.getAll()) {
3378 auto clientSp = i->getValue();
3379
3380 if (clientSp.get() == nullptr) {
3381 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3382 continue;
3383 }
3384
Ruben Brunk6267b532015-04-30 17:44:07 -07003385 // Don't evict clients that are still allowed.
3386 uid_t clientUid = clientSp->getClientUid();
3387 userid_t clientUserId = multiuser_get_user_id(clientUid);
3388 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3389 continue;
3390 }
3391
Ruben Brunk36597b22015-03-20 22:15:57 -07003392 evicted.push_back(clientSp);
3393
Ruben Brunk36597b22015-03-20 22:15:57 -07003394 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003395 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003396
Ruben Brunk36597b22015-03-20 22:15:57 -07003397 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003398 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003399 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003400 " to user switch.", i->getKey().c_str(),
3401 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003402 i->getOwnerId(), i->getPriority().getScore(),
3403 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003404
3405 }
3406
3407 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3408 // blocking other clients from connecting in mServiceLockWrapper if held.
3409 mServiceLock.unlock();
3410
3411 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003412 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003413
3414 for (auto& i : evicted) {
3415 i->disconnect();
3416 }
3417
Jayant Chowdhary12361932018-08-27 14:46:13 -07003418 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003419
3420 // Reacquire mServiceLock
3421 mServiceLock.lock();
3422}
Ruben Brunkcc776712015-02-17 20:18:47 -08003423
Austin Borgered99f642023-06-01 16:51:35 -07003424void CameraService::logEvent(const std::string &event) {
3425 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003426 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003427 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003428 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003429 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003430 mEventLog.add(msg);
3431 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3432 // Error event not added to the dumpsys log before
3433 mEventLog.add(msg);
3434 sServiceErrorEventSet.insert(msg);
3435 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003436}
3437
Austin Borgered99f642023-06-01 16:51:35 -07003438void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3439 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003440 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003441 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3442 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003443}
3444
Austin Borgered99f642023-06-01 16:51:35 -07003445void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3446 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003447 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003448 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3449 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003450}
3451
Austin Borgered99f642023-06-01 16:51:35 -07003452void CameraService::logConnected(const std::string &cameraId, int clientPid,
3453 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003454 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003455 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3456 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003457}
3458
Austin Borgered99f642023-06-01 16:51:35 -07003459void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3460 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003461 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003462 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3463 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003464}
3465
Austin Borgered99f642023-06-01 16:51:35 -07003466void CameraService::logRejected(const std::string &cameraId, int clientPid,
3467 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003468 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003469 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3470 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003471}
3472
Austin Borgered99f642023-06-01 16:51:35 -07003473void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3474 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003475 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003476 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3477 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003478}
3479
Ruben Brunk6267b532015-04-30 17:44:07 -07003480void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3481 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003482 std::string newUsers = toString(newUserIds);
3483 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003484 if (oldUsers.size() == 0) {
3485 oldUsers = "<None>";
3486 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003487 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003488 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3489 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003490}
3491
Austin Borgered99f642023-06-01 16:51:35 -07003492void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003493 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003494 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003495}
3496
Austin Borgered99f642023-06-01 16:51:35 -07003497void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003498 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003499 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003500}
3501
Austin Borgered99f642023-06-01 16:51:35 -07003502void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003503 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003504 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003505}
3506
Austin Borgered99f642023-06-01 16:51:35 -07003507void CameraService::logServiceError(const std::string &msg, int errorCode) {
3508 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3509 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003510}
3511
Ruben Brunk36597b22015-03-20 22:15:57 -07003512status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3513 uint32_t flags) {
3514
Mathias Agopian65ab4712010-07-14 17:59:35 -07003515 // Permission checks
3516 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003517 case SHELL_COMMAND_TRANSACTION: {
3518 int in = data.readFileDescriptor();
3519 int out = data.readFileDescriptor();
3520 int err = data.readFileDescriptor();
3521 int argc = data.readInt32();
3522 Vector<String16> args;
3523 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3524 args.add(data.readString16());
3525 }
3526 sp<IBinder> unusedCallback;
3527 sp<IResultReceiver> resultReceiver;
3528 status_t status;
3529 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3530 return status;
3531 }
3532 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3533 return status;
3534 }
3535 status = shellCommand(in, out, err, args);
3536 if (resultReceiver != nullptr) {
3537 resultReceiver->send(status);
3538 }
3539 return NO_ERROR;
3540 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 }
3542
3543 return BnCameraService::onTransact(code, data, reply, flags);
3544}
3545
Mathias Agopian65ab4712010-07-14 17:59:35 -07003546// We share the media players for shutter and recording sound for all clients.
3547// A reference count is kept to determine when we will actually release the
3548// media players.
3549
Jaekyun Seokef498052018-03-23 13:09:44 +09003550sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3551 sp<MediaPlayer> mp = new MediaPlayer();
3552 status_t error;
3553 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003554 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003555 error = mp->prepare();
3556 }
3557 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003558 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003559 mp->disconnect();
3560 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003561 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003562 }
3563 return mp;
3564}
3565
username5755fea2018-12-27 09:48:08 +08003566void CameraService::increaseSoundRef() {
3567 Mutex::Autolock lock(mSoundLock);
3568 mSoundRef++;
3569}
3570
3571void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003572 ATRACE_CALL();
3573
username5755fea2018-12-27 09:48:08 +08003574 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3575 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3576 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3577 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3578 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3579 }
3580 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3581 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3582 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3583 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003584 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003585 }
3586 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3587 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3588 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3589 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3590 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003591 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003592}
3593
username5755fea2018-12-27 09:48:08 +08003594void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003596 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 if (--mSoundRef) return;
3598
3599 for (int i = 0; i < NUM_SOUNDS; i++) {
3600 if (mSoundPlayer[i] != 0) {
3601 mSoundPlayer[i]->disconnect();
3602 mSoundPlayer[i].clear();
3603 }
3604 }
3605}
3606
3607void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003608 ATRACE_CALL();
3609
Mathias Agopian65ab4712010-07-14 17:59:35 -07003610 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003611 if (kind < 0 || kind >= NUM_SOUNDS) {
3612 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3613 return;
3614 }
3615
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003617 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003618 sp<MediaPlayer> player = mSoundPlayer[kind];
3619 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003620 player->seekTo(0);
3621 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622 }
3623}
3624
3625// ----------------------------------------------------------------------------
3626
3627CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003628 const sp<ICameraClient>& cameraClient,
Austin Borgered99f642023-06-01 16:51:35 -07003629 const std::string& clientPackageName, bool systemNativeClient,
3630 const std::optional<std::string>& clientFeatureId,
3631 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003632 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003633 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003634 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003635 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003636 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003637 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003638 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003639 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003640 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003641 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003642{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003643 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003644 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003646 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003647
username5755fea2018-12-27 09:48:08 +08003648 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003649
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003650 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651}
3652
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653// tear down the client
3654CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003655 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003656 mDestructionStarted = true;
3657
username5755fea2018-12-27 09:48:08 +08003658 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003659 // unconditionally disconnect. function is idempotent
3660 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003661}
3662
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003663sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3664
Igor Murashkin634a5152013-02-20 17:15:11 -08003665CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003666 const sp<IBinder>& remoteCallback,
Austin Borgered99f642023-06-01 16:51:35 -07003667 const std::string& clientPackageName, bool nativeClient,
3668 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003669 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003670 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003671 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003672 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003673 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3674 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003675 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003676 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003677 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003678 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003679 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003680 mRemoteBinder(remoteCallback),
3681 mOpsActive(false),
3682 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003683{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003684 if (sCameraService == nullptr) {
3685 sCameraService = cameraService;
3686 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003687
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003688 // There are 2 scenarios in which a client won't have AppOps operations
3689 // (both scenarios : native clients)
3690 // 1) It's an system native client*, the package name will be empty
3691 // and it will return from this function in the previous if condition
3692 // (This is the same as the previously existing behavior).
3693 // 2) It is a system native client, but its package name has been
3694 // modified for debugging, however it still must not use AppOps since
3695 // the package name is not a real one.
3696 //
3697 // * system native client - native client with UID < AID_APP_START. It
3698 // doesn't exclude clients not on the system partition.
3699 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003700 mAppOpsManager = std::make_unique<AppOpsManager>();
3701 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003702
3703 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003704}
3705
3706CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003707 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003708 mDestructionStarted = true;
3709}
3710
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003711binder::Status CameraService::BasicClient::disconnect() {
3712 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003713 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003714 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003715 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003716 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003717
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003718 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07003719 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003720 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003721 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08003722
3723 sp<IBinder> remote = getRemote();
3724 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003725 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003726 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003727
3728 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003729 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003730 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07003731 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003732 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003733
Igor Murashkincba2c162013-03-20 15:56:31 -07003734 // client shouldn't be able to call into us anymore
3735 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003736
Kunal Malhotrabfc96052023-02-28 23:25:34 +00003737 const auto& mActivityManager = getActivityManager();
3738 if (mActivityManager) {
3739 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
3740 CameraThreadState::getCallingUid(),
3741 CameraThreadState::getCallingPid());
3742 }
3743
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003744 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003745}
3746
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003747status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3748 // No dumping of clients directly over Binder,
3749 // must go through CameraService::dump
3750 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003751 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003752 return OK;
3753}
3754
Austin Borgered99f642023-06-01 16:51:35 -07003755status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003756 // Can't watch tags directly, must go through CameraService::startWatchingTags
3757 return OK;
3758}
3759
3760status_t CameraService::BasicClient::stopWatchingTags(int) {
3761 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3762 return OK;
3763}
3764
3765status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3766 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3767 return OK;
3768}
3769
Austin Borgered99f642023-06-01 16:51:35 -07003770std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003771 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003772}
3773
Emilian Peev8b64f282021-03-25 16:49:57 -07003774int CameraService::BasicClient::getCameraFacing() const {
3775 return mCameraFacing;
3776}
3777
3778int CameraService::BasicClient::getCameraOrientation() const {
3779 return mOrientation;
3780}
Ruben Brunkcc776712015-02-17 20:18:47 -08003781
3782int CameraService::BasicClient::getClientPid() const {
3783 return mClientPid;
3784}
3785
Ruben Brunk6267b532015-04-30 17:44:07 -07003786uid_t CameraService::BasicClient::getClientUid() const {
3787 return mClientUid;
3788}
3789
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003790bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3791 // Defaults to API2.
3792 return level == API_2;
3793}
3794
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003795status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003796 {
3797 Mutex::Autolock l(mAudioRestrictionLock);
3798 mAudioRestriction = mode;
3799 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003800 sCameraService->updateAudioRestriction();
3801 return OK;
3802}
3803
3804int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003805 return sCameraService->updateAudioRestriction();
3806}
3807
3808int32_t CameraService::BasicClient::getAudioRestriction() const {
3809 Mutex::Autolock l(mAudioRestrictionLock);
3810 return mAudioRestriction;
3811}
3812
3813bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3814 switch (mode) {
3815 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3816 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3817 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3818 return true;
3819 default:
3820 return false;
3821 }
3822}
3823
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003824status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3825 if (mode == AppOpsManager::MODE_ERRORED) {
3826 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07003827 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003828 return PERMISSION_DENIED;
3829 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3830 // If the calling Uid is trusted (a native service), the AppOpsManager could
3831 // return MODE_IGNORED. Do not treat such case as error.
3832 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3833 mClientPackageName);
3834 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003835 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003836 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3837 // We prefer to successfully open the camera and perform camera muting
3838 // or blocking in connectHelper as handleAppOpMode can be called before the
3839 // connection has been fully established and at that time camera muting
3840 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003841 if (!isUidActive || !isCameraPrivacyEnabled) {
3842 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07003843 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003844 // Return the same error as for device policy manager rejection
3845 return -EACCES;
3846 }
3847 }
3848 return OK;
3849}
3850
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003851status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003852 ATRACE_CALL();
3853
Igor Murashkine6800ce2013-03-04 17:25:57 -08003854 {
3855 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003856 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003857 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003858 if (mAppOpsManager != nullptr) {
3859 // Notify app ops that the camera is not available
3860 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003861 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003862 toString16(mClientPackageName), mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003863
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003864 // Just check for camera acccess here on open - delay startOp until
3865 // camera frames start streaming in startCameraStreamingOps
3866 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003867 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003868 status_t res = handleAppOpMode(mode);
3869 if (res != OK) {
3870 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003871 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003872 }
3873
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003874 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003875
3876 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003877 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003878
Austin Borgerdddb7552023-03-30 17:53:01 -07003879 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08003880
Shuzhen Wang695044d2020-03-06 09:02:23 -08003881 // Notify listeners of camera open/close status
3882 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3883
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003884 return OK;
3885}
3886
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003887status_t CameraService::BasicClient::startCameraStreamingOps() {
3888 ATRACE_CALL();
3889
3890 if (!mOpsActive) {
3891 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3892 return INVALID_OPERATION;
3893 }
3894 if (mOpsStreaming) {
3895 ALOGV("%s: Streaming already active!", __FUNCTION__);
3896 return OK;
3897 }
3898
3899 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003900 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003901
3902 if (mAppOpsManager != nullptr) {
3903 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003904 toString16(mClientPackageName), /*startIfModeDefault*/ false,
3905 toString16(mClientFeatureId),
3906 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003907 status_t res = handleAppOpMode(mode);
3908 if (res != OK) {
3909 return res;
3910 }
3911 }
3912
3913 mOpsStreaming = true;
3914
3915 return OK;
3916}
3917
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003918status_t CameraService::BasicClient::noteAppOp() {
3919 ATRACE_CALL();
3920
3921 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003922 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003923
3924 // noteAppOp is only used for when camera mute is not supported, in order
3925 // to trigger the sensor privacy "Unblock" dialog
3926 if (mAppOpsManager != nullptr) {
3927 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003928 toString16(mClientPackageName), toString16(mClientFeatureId),
3929 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003930 status_t res = handleAppOpMode(mode);
3931 if (res != OK) {
3932 return res;
3933 }
3934 }
3935
3936 return OK;
3937}
3938
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003939status_t CameraService::BasicClient::finishCameraStreamingOps() {
3940 ATRACE_CALL();
3941
3942 if (!mOpsActive) {
3943 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3944 return INVALID_OPERATION;
3945 }
3946 if (!mOpsStreaming) {
3947 ALOGV("%s: Streaming not active!", __FUNCTION__);
3948 return OK;
3949 }
3950
3951 if (mAppOpsManager != nullptr) {
3952 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003953 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003954 mOpsStreaming = false;
3955 }
3956
3957 return OK;
3958}
3959
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003960status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003961 ATRACE_CALL();
3962
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003963 if (mOpsStreaming) {
3964 // Make sure we've notified everyone about camera stopping
3965 finishCameraStreamingOps();
3966 }
3967
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003968 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003969 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003970 mOpsActive = false;
3971
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003972 // This function is called when a client disconnects. This should
3973 // release the camera, but actually only if it was in a proper
3974 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003975 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003976 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003977
Ruben Brunkcc776712015-02-17 20:18:47 -08003978 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003979 sCameraService->updateStatus(StatusInternal::PRESENT,
3980 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003981 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003982 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003983 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3984 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003985 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003986 mOpsCallback.clear();
3987
Austin Borgerdddb7552023-03-30 17:53:01 -07003988 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08003989
Shuzhen Wang695044d2020-03-06 09:02:23 -08003990 // Notify listeners of camera open/close status
3991 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3992
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003993 return OK;
3994}
3995
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003996void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003997 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003998 if (mAppOpsManager == nullptr) {
3999 return;
4000 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004001 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004002 if (op != AppOpsManager::OP_CAMERA) {
4003 ALOGW("Unexpected app ops notification received: %d", op);
4004 return;
4005 }
4006
4007 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004008 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004009 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004010 ALOGV("checkOp returns: %d, %s ", res,
4011 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4012 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4013 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4014 "UNKNOWN");
4015
Shuzhen Wang64900852021-02-05 09:03:29 -08004016 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004017 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4018 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004019 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004020 } else if (res == AppOpsManager::MODE_IGNORED) {
4021 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08004022 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004023 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08004024 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
Austin Borgered99f642023-06-01 16:51:35 -07004025 mCameraIdStr.c_str(), mClientPackageName.c_str(),
Shuzhen Wang64900852021-02-05 09:03:29 -08004026 mUidIsTrusted, isUidActive);
4027 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
4028 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
4029 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004030 if (!mUidIsTrusted) {
4031 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4032 setCameraMute(true);
4033 } else if (!isUidActive
4034 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4035 block();
4036 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004037 }
Evan Severson09ab4002021-02-10 14:15:19 -08004038 } else if (res == AppOpsManager::MODE_ALLOWED) {
4039 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004040 }
4041}
4042
Svet Ganova453d0d2018-01-11 15:37:58 -08004043void CameraService::BasicClient::block() {
4044 ATRACE_CALL();
4045
4046 // Reset the client PID to allow server-initiated disconnect,
4047 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004048 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004049 CaptureResultExtras resultExtras; // a dummy result (invalid)
4050 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4051 disconnect();
4052}
4053
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054// ----------------------------------------------------------------------------
4055
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004056void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004057 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004058 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004059 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4060 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4061 api1ErrorCode = CAMERA_ERROR_DISABLED;
4062 }
4063 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004064 } else {
4065 ALOGE("mRemoteCallback is NULL!!");
4066 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004067}
4068
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004069// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004070binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004071 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004072 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004073}
4074
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004075bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4076 return level == API_1;
4077}
4078
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004079CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4080 mClient(client) {
4081}
4082
4083void CameraService::Client::OpsCallback::opChanged(int32_t op,
4084 const String16& packageName) {
4085 sp<BasicClient> client = mClient.promote();
4086 if (client != NULL) {
4087 client->opChanged(op, packageName);
4088 }
4089}
4090
Mathias Agopian65ab4712010-07-14 17:59:35 -07004091// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004092// UidPolicy
4093// ----------------------------------------------------------------------------
4094
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004095void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004096 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004097 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004098
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004099 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004100 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004101 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004102 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004103 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4104 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004105 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004106 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004107 if (res == OK) {
4108 mRegistered = true;
4109 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004110 } else {
4111 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004112 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004113}
4114
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004115void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004116 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004117 return;
4118 }
4119
4120 registerWithActivityManager();
4121}
4122
4123void CameraService::UidPolicy::registerSelf() {
4124 // Use check service to see if the activity service is available
4125 // If not available then register for notifications, instead of blocking
4126 // till the service is ready
4127 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004128 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004129 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004130 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004131 } else {
4132 registerWithActivityManager();
4133 }
4134}
4135
Svet Ganova453d0d2018-01-11 15:37:58 -08004136void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004137 Mutex::Autolock _l(mUidLock);
4138
Steven Moreland2f348142019-07-02 15:59:07 -07004139 mAm.unregisterUidObserver(this);
4140 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004141 mRegistered = false;
4142 mActiveUids.clear();
4143 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004144}
4145
4146void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4147 onUidIdle(uid, disabled);
4148}
4149
4150void CameraService::UidPolicy::onUidActive(uid_t uid) {
4151 Mutex::Autolock _l(mUidLock);
4152 mActiveUids.insert(uid);
4153}
4154
4155void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4156 bool deleted = false;
4157 {
4158 Mutex::Autolock _l(mUidLock);
4159 if (mActiveUids.erase(uid) > 0) {
4160 deleted = true;
4161 }
4162 }
4163 if (deleted) {
4164 sp<CameraService> service = mService.promote();
4165 if (service != nullptr) {
4166 service->blockClientsForUid(uid);
4167 }
4168 }
4169}
4170
Emilian Peev53722fa2019-02-22 17:47:20 -08004171void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004172 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004173 bool procStateChange = false;
4174 {
4175 Mutex::Autolock _l(mUidLock);
4176 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4177 mMonitoredUids[uid].procState != procState) {
4178 mMonitoredUids[uid].procState = procState;
4179 procStateChange = true;
4180 }
4181 }
4182
4183 if (procStateChange) {
4184 sp<CameraService> service = mService.promote();
4185 if (service != nullptr) {
4186 service->notifyMonitoredUids();
4187 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004188 }
4189}
4190
Austin Borgerdddb7552023-03-30 17:53:01 -07004191/**
4192 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4193 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4194 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4195 * monitoredUids. If it is revised above some other monitoredUid, signal
4196 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4197 * foreground apps in split screen - state changes will capture all other cases.
4198 */
4199void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4200 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004201 {
4202 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004203 auto it = mMonitoredUids.find(uid);
4204
4205 if (it != mMonitoredUids.end()) {
4206 if (it->second.hasCamera) {
4207 for (auto &monitoredUid : mMonitoredUids) {
4208 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004209 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004210 notifyUidSet.emplace(monitoredUid.first);
4211 }
4212 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004213 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004214 notifyUidSet.emplace(uid);
4215 } else {
4216 for (auto &monitoredUid : mMonitoredUids) {
4217 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004218 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004219 notifyUidSet.emplace(uid);
4220 }
4221 }
4222 }
4223 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004224 }
4225 }
4226
Austin Borgerdddb7552023-03-30 17:53:01 -07004227 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004228 sp<CameraService> service = mService.promote();
4229 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004230 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004231 }
4232 }
4233}
4234
Austin Borgerdddb7552023-03-30 17:53:01 -07004235/**
4236 * Register a uid for monitoring, and note whether it owns a camera.
4237 */
4238void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004239 Mutex::Autolock _l(mUidLock);
4240 auto it = mMonitoredUids.find(uid);
4241 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004242 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004243 } else {
Austin Borger65577682022-02-17 00:25:43 +00004244 MonitoredUid monitoredUid;
4245 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004246 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004247 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004248 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004249 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004250 if (res != OK) {
4251 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4252 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004253 }
4254
4255 if (openCamera) {
4256 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004257 }
4258}
4259
Austin Borgerdddb7552023-03-30 17:53:01 -07004260/**
4261 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4262 */
4263void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004264 Mutex::Autolock _l(mUidLock);
4265 auto it = mMonitoredUids.find(uid);
4266 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004267 it->second.refCount--;
4268 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004269 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004270 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004271 if (res != OK) {
4272 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4273 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004274 } else if (closeCamera) {
4275 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004276 }
4277 } else {
4278 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4279 }
4280}
4281
Austin Borgered99f642023-06-01 16:51:35 -07004282bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004283 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004284 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004285}
4286
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004287static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4288static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004289
Austin Borgered99f642023-06-01 16:51:35 -07004290bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004291 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004292 // If activity manager is unreachable, assume everything is active
4293 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004294 return true;
4295 }
4296 auto it = mOverrideUids.find(uid);
4297 if (it != mOverrideUids.end()) {
4298 return it->second;
4299 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004300 bool active = mActiveUids.find(uid) != mActiveUids.end();
4301 if (!active) {
4302 // We want active UIDs to always access camera with their first attempt since
4303 // there is no guarantee the app is robustly written and would retry getting
4304 // the camera on failure. The inverse case is not a problem as we would take
4305 // camera away soon once we get the callback that the uid is no longer active.
4306 ActivityManager am;
4307 // Okay to access with a lock held as UID changes are dispatched without
4308 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004309 int64_t startTimeMillis = 0;
4310 do {
4311 // TODO: Fix this b/109950150!
4312 // Okay this is a hack. There is a race between the UID turning active and
4313 // activity being resumed. The proper fix is very risky, so we temporary add
4314 // some polling which should happen pretty rarely anyway as the race is hard
4315 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004316 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004317 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004318 if (active) {
4319 break;
4320 }
4321 if (startTimeMillis <= 0) {
4322 startTimeMillis = uptimeMillis();
4323 }
4324 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004325 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004326 if (remainingTimeMillis <= 0) {
4327 break;
4328 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004329 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4330
4331 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004332 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004333 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004334 } while (true);
4335
Svet Ganov7b4ab782018-03-25 12:48:10 -07004336 if (active) {
4337 // Now that we found out the UID is actually active, cache that
4338 mActiveUids.insert(uid);
4339 }
4340 }
4341 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004342}
4343
Varun Shahb42f1eb2019-04-16 14:45:13 -07004344int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4345 Mutex::Autolock _l(mUidLock);
4346 return getProcStateLocked(uid);
4347}
4348
4349int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4350 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4351 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004352 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004353 }
4354 return procState;
4355}
4356
Austin Borgered99f642023-06-01 16:51:35 -07004357void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4358 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004359 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004360}
4361
Austin Borgered99f642023-06-01 16:51:35 -07004362void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004363 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004364}
4365
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004366void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4367 Mutex::Autolock _l(mUidLock);
4368 ALOGV("UidPolicy: ActivityManager has died");
4369 mRegistered = false;
4370 mActiveUids.clear();
4371}
4372
Austin Borgered99f642023-06-01 16:51:35 -07004373void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004374 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004375 bool wasActive = false;
4376 bool isActive = false;
4377 {
4378 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004379 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004380 mOverrideUids.erase(uid);
4381 if (insert) {
4382 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4383 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004384 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004385 }
4386 if (wasActive != isActive && !isActive) {
4387 sp<CameraService> service = mService.promote();
4388 if (service != nullptr) {
4389 service->blockClientsForUid(uid);
4390 }
4391 }
4392}
4393
4394// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004395// SensorPrivacyPolicy
4396// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004397
4398void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4399{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004400 Mutex::Autolock _l(mSensorPrivacyLock);
4401 if (mRegistered) {
4402 return;
4403 }
Evan Severson09ab4002021-02-10 14:15:19 -08004404 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004405 mSpm.addSensorPrivacyListener(this);
4406 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4407 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004408 if (res == OK) {
4409 mRegistered = true;
4410 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4411 }
4412}
4413
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004414void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4415 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004416 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004417 return;
4418 }
4419
4420 registerWithSensorPrivacyManager();
4421}
4422
4423void CameraService::SensorPrivacyPolicy::registerSelf() {
4424 // Use checkservice to see if the sensor_privacy service is available
4425 // If service is not available then register for notification
4426 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004427 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004428 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004429 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004430 } else {
4431 registerWithSensorPrivacyManager();
4432 }
4433}
4434
Michael Grooverd1d435a2018-12-18 17:39:42 -08004435void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4436 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004437 mSpm.removeSensorPrivacyListener(this);
4438 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004439 mRegistered = false;
4440 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4441}
4442
4443bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004444 if (!mRegistered) {
4445 registerWithSensorPrivacyManager();
4446 }
4447
Michael Grooverd1d435a2018-12-18 17:39:42 -08004448 Mutex::Autolock _l(mSensorPrivacyLock);
4449 return mSensorPrivacyEnabled;
4450}
4451
Evan Seversond0b69922022-01-27 10:47:34 -08004452bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004453 if (!hasCameraPrivacyFeature()) {
4454 return false;
4455 }
Evan Seversond0b69922022-01-27 10:47:34 -08004456 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004457}
4458
Evan Seversond0b69922022-01-27 10:47:34 -08004459binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4460 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004461 {
4462 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004463 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004464 }
4465 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004466 if (enabled) {
4467 sp<CameraService> service = mService.promote();
4468 if (service != nullptr) {
4469 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004470 }
4471 }
4472 return binder::Status::ok();
4473}
4474
4475void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4476 Mutex::Autolock _l(mSensorPrivacyLock);
4477 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4478 mRegistered = false;
4479}
4480
Evan Severson09ab4002021-02-10 14:15:19 -08004481bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004482 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4483 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4484 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4485 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4486 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004487}
4488
Michael Grooverd1d435a2018-12-18 17:39:42 -08004489// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004490// CameraState
4491// ----------------------------------------------------------------------------
4492
Austin Borgered99f642023-06-01 16:51:35 -07004493CameraService::CameraState::CameraState(const std::string& id, int cost,
4494 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004495 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004496 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004497 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004498
4499CameraService::CameraState::~CameraState() {}
4500
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004501CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004502 Mutex::Autolock lock(mStatusLock);
4503 return mStatus;
4504}
4505
Austin Borgered99f642023-06-01 16:51:35 -07004506std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004507 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004508 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004509 return res;
4510}
4511
Ruben Brunkcc776712015-02-17 20:18:47 -08004512CameraParameters CameraService::CameraState::getShimParams() const {
4513 return mShimParams;
4514}
4515
4516void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4517 mShimParams = params;
4518}
4519
4520int CameraService::CameraState::getCost() const {
4521 return mCost;
4522}
4523
Austin Borgered99f642023-06-01 16:51:35 -07004524std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004525 return mConflicting;
4526}
4527
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004528SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4529 return mSystemCameraKind;
4530}
4531
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004532bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4533 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4534 != mPhysicalCameras.end();
4535}
4536
Austin Borgered99f642023-06-01 16:51:35 -07004537bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004538 Mutex::Autolock lock(mStatusLock);
4539 auto result = mUnavailablePhysicalIds.insert(physicalId);
4540 return result.second;
4541}
4542
Austin Borgered99f642023-06-01 16:51:35 -07004543bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004544 Mutex::Autolock lock(mStatusLock);
4545 auto count = mUnavailablePhysicalIds.erase(physicalId);
4546 return count > 0;
4547}
4548
Austin Borgered99f642023-06-01 16:51:35 -07004549void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004550 Mutex::Autolock lock(mStatusLock);
4551 mClientPackage = clientPackage;
4552}
4553
Austin Borgered99f642023-06-01 16:51:35 -07004554std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004555 Mutex::Autolock lock(mStatusLock);
4556 return mClientPackage;
4557}
4558
Ruben Brunkcc776712015-02-17 20:18:47 -08004559// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004560// ClientEventListener
4561// ----------------------------------------------------------------------------
4562
4563void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004564 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004565 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004566 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004567 if (basicClient.get() != nullptr) {
4568 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004569 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004570 static_cast<int>(basicClient->getClientUid()));
4571 }
4572}
4573
4574void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004575 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004576 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004577 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004578 if (basicClient.get() != nullptr) {
4579 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004580 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004581 static_cast<int>(basicClient->getClientUid()));
4582 }
4583}
4584
4585
4586// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004587// CameraClientManager
4588// ----------------------------------------------------------------------------
4589
Ruben Brunk99e69712015-05-26 17:25:07 -07004590CameraService::CameraClientManager::CameraClientManager() {
4591 setListener(std::make_shared<ClientEventListener>());
4592}
4593
Ruben Brunkcc776712015-02-17 20:18:47 -08004594CameraService::CameraClientManager::~CameraClientManager() {}
4595
4596sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004597 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004598 auto descriptor = get(id);
4599 if (descriptor == nullptr) {
4600 return sp<BasicClient>{nullptr};
4601 }
4602 return descriptor->getValue();
4603}
4604
Austin Borgered99f642023-06-01 16:51:35 -07004605std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004606 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004607 std::ostringstream ret;
4608 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004609 bool hasAny = false;
4610 for (auto& i : all) {
4611 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004612 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004613 int32_t cost = i->getCost();
4614 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004615 int32_t score = i->getPriority().getScore();
4616 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004617 auto conflicting = i->getConflicting();
4618 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07004619 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004620 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004621 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004622 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07004623 uid_t clientUid = clientSp->getClientUid();
4624 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004625 }
Austin Borgered99f642023-06-01 16:51:35 -07004626 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4627 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004628
Ruben Brunk6267b532015-04-30 17:44:07 -07004629 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004630 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07004631 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004632 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07004633 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004634 }
4635
Austin Borgered99f642023-06-01 16:51:35 -07004636 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08004637 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07004638 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004639 }
Austin Borgered99f642023-06-01 16:51:35 -07004640 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08004641 }
Austin Borgered99f642023-06-01 16:51:35 -07004642 if (hasAny) ret << "\n";
4643 ret << "]\n";
4644 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004645}
4646
4647CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07004648 const std::string& key, const sp<BasicClient>& value, int32_t cost,
4649 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004650 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004651
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004652 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07004653 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004654
Austin Borgered99f642023-06-01 16:51:35 -07004655 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004656 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4657 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004658}
4659
4660CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004661 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004662 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004663 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004664 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004665 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4666 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004667}
4668
4669// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004670// InjectionStatusListener
4671// ----------------------------------------------------------------------------
4672
4673void CameraService::InjectionStatusListener::addListener(
4674 const sp<ICameraInjectionCallback>& callback) {
4675 Mutex::Autolock lock(mListenerLock);
4676 if (mCameraInjectionCallback) return;
4677 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4678 if (res == OK) {
4679 mCameraInjectionCallback = callback;
4680 }
4681}
4682
4683void CameraService::InjectionStatusListener::removeListener() {
4684 Mutex::Autolock lock(mListenerLock);
4685 if (mCameraInjectionCallback == nullptr) {
4686 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4687 return;
4688 }
4689 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4690 mCameraInjectionCallback = nullptr;
4691}
4692
4693void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07004694 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004695 if (mCameraInjectionCallback == nullptr) {
4696 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4697 return;
4698 }
Cliff Wud3a05312021-04-26 23:07:31 +08004699
4700 switch (err) {
4701 case -ENODEV:
4702 mCameraInjectionCallback->onInjectionError(
4703 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4704 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07004705 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004706 break;
4707 case -EBUSY:
4708 mCameraInjectionCallback->onInjectionError(
4709 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4710 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07004711 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004712 break;
4713 case DEAD_OBJECT:
4714 mCameraInjectionCallback->onInjectionError(
4715 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4716 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07004717 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004718 break;
4719 case INVALID_OPERATION:
4720 mCameraInjectionCallback->onInjectionError(
4721 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4722 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07004723 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004724 break;
4725 case UNKNOWN_TRANSACTION:
4726 mCameraInjectionCallback->onInjectionError(
4727 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4728 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07004729 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004730 break;
4731 default:
4732 mCameraInjectionCallback->onInjectionError(
4733 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4734 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07004735 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004736 }
Cliff Wud8cae102021-03-11 01:37:42 +08004737}
4738
4739void CameraService::InjectionStatusListener::binderDied(
4740 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004741 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4742 auto parent = mParent.promote();
4743 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004744 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4745 if (clientDescriptor != nullptr) {
4746 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4747 baseClientPtr->stopInjection();
4748 }
Cliff Wu3b268182021-07-06 15:44:43 +08004749 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004750 }
4751}
4752
4753// ----------------------------------------------------------------------------
4754// CameraInjectionSession
4755// ----------------------------------------------------------------------------
4756
4757binder::Status CameraService::CameraInjectionSession::stopInjection() {
4758 Mutex::Autolock lock(mInjectionSessionLock);
4759 auto parent = mParent.promote();
4760 if (parent == nullptr) {
4761 ALOGE("CameraInjectionSession: Parent is gone");
4762 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4763 "Camera service encountered error");
4764 }
Cliff Wud3a05312021-04-26 23:07:31 +08004765
4766 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004767 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4768 if (clientDescriptor != nullptr) {
4769 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4770 res = baseClientPtr->stopInjection();
4771 if (res != OK) {
4772 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4773 " ret != NO_ERROR: %d", res);
4774 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4775 "Camera session encountered error");
4776 }
4777 }
Cliff Wu3b268182021-07-06 15:44:43 +08004778 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004779 return binder::Status::ok();
4780}
4781
4782// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004783
4784static const int kDumpLockRetries = 50;
4785static const int kDumpLockSleep = 60000;
4786
4787static bool tryLock(Mutex& mutex)
4788{
4789 bool locked = false;
4790 for (int i = 0; i < kDumpLockRetries; ++i) {
4791 if (mutex.tryLock() == NO_ERROR) {
4792 locked = true;
4793 break;
4794 }
4795 usleep(kDumpLockSleep);
4796 }
4797 return locked;
4798}
4799
Rucha Katakwardf223072021-06-15 10:21:00 -07004800void CameraService::cacheDump() {
4801 if (mMemFd != -1) {
4802 const Vector<String16> args;
4803 ATRACE_CALL();
4804 // Acquiring service lock here will avoid the deadlock since
4805 // cacheDump will not be called during the second disconnect.
4806 Mutex::Autolock lock(mServiceLock);
4807
4808 Mutex::Autolock l(mCameraStatesLock);
4809 // Start collecting the info for open sessions and store it in temp file.
4810 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004811 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07004812 auto clientDescriptor = mActiveClientManager.get(cameraId);
4813 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004814 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004815 // Log the current open session info before device is disconnected.
4816 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4817 }
4818 }
4819 }
4820}
4821
Mathias Agopian65ab4712010-07-14 17:59:35 -07004822status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004823 ATRACE_CALL();
4824
Austin Borgered99f642023-06-01 16:51:35 -07004825 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004826 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004827 CameraThreadState::getCallingPid(),
4828 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004829 return NO_ERROR;
4830 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004831 bool locked = tryLock(mServiceLock);
4832 // failed to lock - CameraService is probably deadlocked
4833 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004834 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004835 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004836
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004837 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004838 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004839
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004840 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004841 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004842
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004843 if (locked) mServiceLock.unlock();
4844 return NO_ERROR;
4845 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004846 dprintf(fd, "\n== Service global info: ==\n\n");
4847 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004848 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004849 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4850 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004851 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4852 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4853 }
Austin Borgered99f642023-06-01 16:51:35 -07004854 std::string activeClientString = mActiveClientManager.toString();
4855 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
4856 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004857 if (mStreamUseCaseOverrides.size() > 0) {
4858 dprintf(fd, "Active stream use case overrides:");
4859 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4860 dprintf(fd, " %" PRId64, useCaseOverride);
4861 }
4862 dprintf(fd, "\n");
4863 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004864
4865 dumpEventLog(fd);
4866
4867 bool stateLocked = tryLock(mCameraStatesLock);
4868 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004869 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004870 }
4871
Emilian Peevbd8c5032018-02-14 23:05:40 +00004872 int argSize = args.size();
4873 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07004874 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00004875 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07004876 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00004877 }
4878 break;
4879 }
4880 }
4881
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004882 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004883 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004884
Austin Borgered99f642023-06-01 16:51:35 -07004885 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004886
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004887 CameraParameters p = state.second->getShimParams();
4888 if (!p.isEmpty()) {
4889 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4890 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004891 }
4892
4893 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004894 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004895 // log the current open session info
4896 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004897 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004898 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004899 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004900
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004901 }
4902
4903 if (stateLocked) mCameraStatesLock.unlock();
4904
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004905 if (locked) mServiceLock.unlock();
4906
Emilian Peevf53f66e2017-04-11 14:29:43 +01004907 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004908
4909 dprintf(fd, "\n== Vendor tags: ==\n\n");
4910
4911 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4912 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004913 sp<VendorTagDescriptorCache> cache =
4914 VendorTagDescriptorCache::getGlobalVendorTagCache();
4915 if (cache == NULL) {
4916 dprintf(fd, "No vendor tags.\n");
4917 } else {
4918 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4919 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004920 } else {
4921 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4922 }
4923
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004924 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004925 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004926 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004927
4928 // Process dump arguments, if any
4929 int n = args.size();
4930 String16 verboseOption("-v");
4931 String16 unreachableOption("--unreachable");
4932 for (int i = 0; i < n; i++) {
4933 if (args[i] == verboseOption) {
4934 // change logging level
4935 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07004936 std::string levelStr = toStdString(args[i+1]);
4937 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004938 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004939 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004940 } else if (args[i] == unreachableOption) {
4941 // Dump memory analysis
4942 // TODO - should limit be an argument parameter?
4943 UnreachableMemoryInfo info;
4944 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4945 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004946 dprintf(fd, "\n== Unable to dump unreachable memory. "
4947 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004948 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004949 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004950 std::string s = info.ToString(/*log_contents*/ true);
4951 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004952 }
4953 }
4954 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004955
4956 bool serviceLocked = tryLock(mServiceLock);
4957
4958 // Dump info from previous open sessions.
4959 // Reposition the offset to beginning of the file before reading
4960
4961 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4962 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4963 ssize_t size_read;
4964 char buf[4096];
4965 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4966 // Read data from file to a small buffer and write it to fd.
4967 write(fd, buf, size_read);
4968 if (size_read == -1) {
4969 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4970 break;
4971 }
4972 }
4973 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4974 } else {
4975 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4976 }
4977
4978 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004979 return NO_ERROR;
4980}
4981
Rucha Katakwardf223072021-06-15 10:21:00 -07004982void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07004983 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004984 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004985 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07004986 getFormattedCurrentTime().c_str(),
4987 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004988 dprintf(fd, " Client priority score: %d state: %d\n",
4989 clientDescriptor->getPriority().getScore(),
4990 clientDescriptor->getPriority().getState());
4991 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4992
4993 auto client = clientDescriptor->getValue();
4994 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07004995 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004996
4997 client->dumpClient(fd, args);
4998}
4999
Austin Borgered99f642023-06-01 16:51:35 -07005000void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005001 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005002 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005003}
5004
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005005void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005006 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005007
5008 Mutex::Autolock l(mLogLock);
5009 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005010 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005011 }
5012
5013 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005014 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005015 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005016 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005017 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005018 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005019}
5020
Austin Borgered99f642023-06-01 16:51:35 -07005021void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005022 Mutex::Autolock lock(mLogLock);
5023 if (!isClientWatchedLocked(client)) { return; }
5024
5025 std::vector<std::string> dumpVector;
5026 client->dumpWatchedEventsToVector(dumpVector);
5027
5028 if (dumpVector.empty()) { return; }
5029
Austin Borgered99f642023-06-01 16:51:35 -07005030 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005031
Austin Borgered99f642023-06-01 16:51:35 -07005032 std::string currentTime = getFormattedCurrentTime();
5033 dumpString << "Cached @ ";
5034 dumpString << currentTime;
5035 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005036
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005037 size_t i = dumpVector.size();
5038
5039 // Store the string in reverse order (latest last)
5040 while (i > 0) {
5041 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005042 dumpString << cameraId;
5043 dumpString << ":";
5044 dumpString << client->getPackageName();
5045 dumpString << " ";
5046 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005047 }
5048
Austin Borgered99f642023-06-01 16:51:35 -07005049 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005050}
5051
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005052void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005053 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005054 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5055 if (mTorchClientMap[i] == who) {
5056 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005057 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005058 status_t res = mFlashlight->setTorchMode(cameraId, false);
5059 if (res) {
5060 ALOGE("%s: torch client died but couldn't turn off torch: "
5061 "%s (%d)", __FUNCTION__, strerror(-res), res);
5062 return;
5063 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005064 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005065 break;
5066 }
5067 }
5068}
5069
Ruben Brunkcc776712015-02-17 20:18:47 -08005070/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005071
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005072 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005073 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5074 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005075 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005076 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005077 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005078
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005079 // check torch client
5080 handleTorchClientBinderDied(who);
5081
5082 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005083 if(!evictClientIdByRemote(who)) {
5084 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005085 return;
5086 }
5087
Ruben Brunkcc776712015-02-17 20:18:47 -08005088 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5089 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005090}
5091
Austin Borgered99f642023-06-01 16:51:35 -07005092void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005093 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005094}
5095
Austin Borgered99f642023-06-01 16:51:35 -07005096void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005097 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005098 // Do not lock mServiceLock here or can get into a deadlock from
5099 // connect() -> disconnect -> updateStatus
5100
5101 auto state = getCameraState(cameraId);
5102
5103 if (state == nullptr) {
5104 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005105 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005106 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005107 }
5108
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005109 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5110 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5111 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005112 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005113 return;
5114 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005115
5116 // Collect the logical cameras without holding mStatusLock in updateStatus
5117 // as that can lead to a deadlock(b/162192331).
5118 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005119 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005120 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005121 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005122 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005123 (const std::string& cameraId, StatusInternal status) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005124 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005125 // Update torch status if it has a flash unit.
5126 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005127 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005128 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5129 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005130 TorchModeStatus newTorchStatus =
5131 status == StatusInternal::PRESENT ?
5132 TorchModeStatus::AVAILABLE_OFF :
5133 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005134 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005135 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005136 }
5137 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005138 }
5139
5140 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005141 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005142 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005143
Ruben Brunkcc776712015-02-17 20:18:47 -08005144 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005145 bool isVendorListener = listener->isVendorListener();
5146 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5147 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07005148 isVendorListener) {
5149 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005150 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005151 continue;
5152 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005153 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005154 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005155 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005156 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005157 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5158 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005159 // Also trigger the callbacks for cameras that were remapped to the current
5160 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005161 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005162 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5163 for (auto& remappedCameraId : remappedCameraIds) {
5164 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005165 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005166 listener->handleBinderStatus(ret,
5167 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5168 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5169 ret.exceptionCode());
5170 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005171 }
5172 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005173}
5174
Austin Borgered99f642023-06-01 16:51:35 -07005175void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5176 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005177 auto state = getCameraState(cameraId);
5178 if (state == nullptr) {
5179 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005180 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005181 return;
5182 }
5183 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005184 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005185 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005186 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005187 }
5188
Shuzhen Wang695044d2020-03-06 09:02:23 -08005189 Mutex::Autolock lock(mStatusListenerLock);
5190
5191 for (const auto& it : mListenerList) {
5192 if (!it->isOpenCloseCallbackAllowed()) {
5193 continue;
5194 }
5195
5196 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005197 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005198 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005199 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005200 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005201 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005202
5203 it->handleBinderStatus(ret,
5204 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5205 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005206 }
5207}
5208
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005209template<class Func>
5210void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005211 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005212 std::initializer_list<StatusInternal> rejectSourceStates,
5213 Func onStatusUpdatedLocked) {
5214 Mutex::Autolock lock(mStatusLock);
5215 StatusInternal oldStatus = mStatus;
5216 mStatus = status;
5217
5218 if (oldStatus == status) {
5219 return;
5220 }
5221
5222 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005223 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005224
5225 if (oldStatus == StatusInternal::NOT_PRESENT &&
5226 (status != StatusInternal::PRESENT &&
5227 status != StatusInternal::ENUMERATING)) {
5228
5229 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5230 __FUNCTION__);
5231 mStatus = oldStatus;
5232 return;
5233 }
5234
5235 /**
5236 * Sometimes we want to conditionally do a transition.
5237 * For example if a client disconnects, we want to go to PRESENT
5238 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5239 */
5240 for (auto& rejectStatus : rejectSourceStates) {
5241 if (oldStatus == rejectStatus) {
5242 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005243 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005244 mStatus = oldStatus;
5245 return;
5246 }
5247 }
5248
5249 onStatusUpdatedLocked(cameraId, status);
5250}
5251
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005252status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005253 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005254 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005255 if (!status) {
5256 return BAD_VALUE;
5257 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005258 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5259 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005260 // invalid camera ID or the camera doesn't have a flash unit
5261 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005262 }
5263
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005264 *status = mTorchStatusMap.valueAt(index);
5265 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005266}
5267
Austin Borgered99f642023-06-01 16:51:35 -07005268status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005269 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005270 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5271 if (index == NAME_NOT_FOUND) {
5272 return BAD_VALUE;
5273 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005274 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005275
5276 return OK;
5277}
5278
Austin Borgered99f642023-06-01 16:51:35 -07005279std::list<std::string> CameraService::getLogicalCameras(
5280 const std::string& physicalCameraId) {
5281 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005282 Mutex::Autolock lock(mCameraStatesLock);
5283 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005284 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5285 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005286 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005287 }
5288 return retList;
5289}
5290
5291void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005292 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005293 SystemCameraKind deviceKind) {
5294 // mStatusListenerLock is expected to be locked
5295 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005296 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005297 // Note: we check only the deviceKind of the physical camera id
5298 // since, logical camera ids and their physical camera ids are
5299 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005300 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5301 listener->getListenerPid(), listener->getListenerUid())) {
5302 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005303 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005304 continue;
5305 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005306 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005307 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005308 listener->handleBinderStatus(ret,
5309 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5310 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5311 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005312 }
5313 }
5314}
5315
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005316
Svet Ganova453d0d2018-01-11 15:37:58 -08005317void CameraService::blockClientsForUid(uid_t uid) {
5318 const auto clients = mActiveClientManager.getAll();
5319 for (auto& current : clients) {
5320 if (current != nullptr) {
5321 const auto basicClient = current->getValue();
5322 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5323 basicClient->block();
5324 }
5325 }
5326 }
5327}
5328
Michael Grooverd1d435a2018-12-18 17:39:42 -08005329void CameraService::blockAllClients() {
5330 const auto clients = mActiveClientManager.getAll();
5331 for (auto& current : clients) {
5332 if (current != nullptr) {
5333 const auto basicClient = current->getValue();
5334 if (basicClient.get() != nullptr) {
5335 basicClient->block();
5336 }
5337 }
5338 }
5339}
5340
Svet Ganova453d0d2018-01-11 15:37:58 -08005341// NOTE: This is a remote API - make sure all args are validated
5342status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005343 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005344 return PERMISSION_DENIED;
5345 }
5346 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5347 return BAD_VALUE;
5348 }
Austin Borgered99f642023-06-01 16:51:35 -07005349 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005350 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005351 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005352 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005353 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005354 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005355 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005356 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005357 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005358 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005359 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005360 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005361 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005362 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005363 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005364 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005365 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005366 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005367 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005368 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005369 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005370 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005371 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005372 handleClearStreamUseCaseOverrides();
5373 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005374 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005375 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005376 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005377 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005378 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005379 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005380 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005381 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005382 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005383 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005384 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005385 }
5386 printHelp(err);
5387 return BAD_VALUE;
5388}
5389
malikakash82ed4352023-07-21 22:44:34 +00005390status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5391 uid_t uid = IPCThreadState::self()->getCallingUid();
5392 if (uid != AID_ROOT) {
5393 dprintf(err, "Must be adb root\n");
5394 return PERMISSION_DENIED;
5395 }
5396 if (args.size() != 4) {
5397 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5398 return BAD_VALUE;
5399 }
Austin Borgered99f642023-06-01 16:51:35 -07005400 std::string packageName = toStdString(args[1]);
5401 std::string cameraIdToReplace = toStdString(args[2]);
5402 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005403 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5404 return OK;
5405}
5406
Svet Ganova453d0d2018-01-11 15:37:58 -08005407status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005408 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005409
Svet Ganova453d0d2018-01-11 15:37:58 -08005410 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005411 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005412 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005413 } else if ((args[2] != toString16("idle"))) {
5414 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005415 return BAD_VALUE;
5416 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005417
5418 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005419 if (args.size() >= 5 && args[3] == toString16("--user")) {
5420 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005421 }
5422
5423 uid_t uid;
5424 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5425 return BAD_VALUE;
5426 }
5427
5428 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005429 return NO_ERROR;
5430}
5431
5432status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005433 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005434
5435 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005436 if (args.size() >= 4 && args[2] == toString16("--user")) {
5437 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005438 }
5439
5440 uid_t uid;
5441 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005442 return BAD_VALUE;
5443 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005444
5445 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005446 return NO_ERROR;
5447}
5448
5449status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005450 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005451
5452 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005453 if (args.size() >= 4 && args[2] == toString16("--user")) {
5454 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005455 }
5456
5457 uid_t uid;
5458 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005459 return BAD_VALUE;
5460 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005461
5462 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005463 return dprintf(out, "active\n");
5464 } else {
5465 return dprintf(out, "idle\n");
5466 }
5467}
5468
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005469status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005470 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005471 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5472 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5473 Mutex::Autolock lock(mServiceLock);
5474
5475 mOverrideRotateAndCropMode = rotateValue;
5476
5477 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5478
5479 const auto clients = mActiveClientManager.getAll();
5480 for (auto& current : clients) {
5481 if (current != nullptr) {
5482 const auto basicClient = current->getValue();
5483 if (basicClient.get() != nullptr) {
5484 basicClient->setRotateAndCropOverride(rotateValue);
5485 }
5486 }
5487 }
5488
5489 return OK;
5490}
5491
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005492status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5493 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005494 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005495 if ((*end != '\0') ||
5496 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5497 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5498 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5499 return BAD_VALUE;
5500 }
5501
5502 Mutex::Autolock lock(mServiceLock);
5503 mOverrideAutoframingMode = autoframingValue;
5504
5505 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5506
5507 const auto clients = mActiveClientManager.getAll();
5508 for (auto& current : clients) {
5509 if (current != nullptr) {
5510 const auto basicClient = current->getValue();
5511 if (basicClient.get() != nullptr) {
5512 basicClient->setAutoframingOverride(autoframingValue);
5513 }
5514 }
5515 }
5516
5517 return OK;
5518}
5519
Ravneetaeb20dc2022-03-30 05:33:03 +00005520status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005521 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005522
5523 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5524
5525 Mutex::Autolock lock(mServiceLock);
5526
5527 mCameraServiceWatchdogEnabled = enableWatchdog;
5528
5529 const auto clients = mActiveClientManager.getAll();
5530 for (auto& current : clients) {
5531 if (current != nullptr) {
5532 const auto basicClient = current->getValue();
5533 if (basicClient.get() != nullptr) {
5534 basicClient->setCameraServiceWatchdog(enableWatchdog);
5535 }
5536 }
5537 }
5538
5539 return OK;
5540}
5541
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005542status_t CameraService::handleGetRotateAndCrop(int out) {
5543 Mutex::Autolock lock(mServiceLock);
5544
5545 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5546}
5547
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005548status_t CameraService::handleGetAutoframing(int out) {
5549 Mutex::Autolock lock(mServiceLock);
5550
5551 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5552}
5553
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005554status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5555 char *endPtr;
5556 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005557 std::string maskString = toStdString(args[1]);
5558 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005559
5560 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005561 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005562 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5563
5564 Mutex::Autolock lock(mServiceLock);
5565
5566 mImageDumpMask = maskValue;
5567
5568 return OK;
5569}
5570
5571status_t CameraService::handleGetImageDumpMask(int out) {
5572 Mutex::Autolock lock(mServiceLock);
5573
5574 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5575}
5576
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005577status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005578 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005579 if (errno != 0) return BAD_VALUE;
5580
5581 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5582 Mutex::Autolock lock(mServiceLock);
5583
5584 mOverrideCameraMuteMode = (muteValue == 1);
5585
5586 const auto clients = mActiveClientManager.getAll();
5587 for (auto& current : clients) {
5588 if (current != nullptr) {
5589 const auto basicClient = current->getValue();
5590 if (basicClient.get() != nullptr) {
5591 if (basicClient->supportsCameraMute()) {
5592 basicClient->setCameraMute(mOverrideCameraMuteMode);
5593 }
5594 }
5595 }
5596 }
5597
5598 return OK;
5599}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005600
Shuzhen Wang16610a62022-12-15 22:38:07 -08005601status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5602 std::vector<int64_t> useCasesOverride;
5603 for (size_t i = 1; i < args.size(); i++) {
5604 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005605 std::string arg = toStdString(args[i]);
5606 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005607 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005608 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005609 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07005610 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005611 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07005612 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005613 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07005614 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005615 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07005616 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005617 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07005618 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005619 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5620 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005621 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005622 return BAD_VALUE;
5623 }
5624 useCasesOverride.push_back(useCase);
5625 }
5626
5627 Mutex::Autolock lock(mServiceLock);
5628 mStreamUseCaseOverrides = std::move(useCasesOverride);
5629
5630 return OK;
5631}
5632
5633void CameraService::handleClearStreamUseCaseOverrides() {
5634 Mutex::Autolock lock(mServiceLock);
5635 mStreamUseCaseOverrides.clear();
5636}
5637
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005638status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
5639 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005640 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005641 if ((*end != '\0') ||
5642 (zoomOverrideValue != -1 &&
5643 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
5644 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
5645 return BAD_VALUE;
5646 }
5647
5648 Mutex::Autolock lock(mServiceLock);
5649 mZoomOverrideValue = zoomOverrideValue;
5650
5651 const auto clients = mActiveClientManager.getAll();
5652 for (auto& current : clients) {
5653 if (current != nullptr) {
5654 const auto basicClient = current->getValue();
5655 if (basicClient.get() != nullptr) {
5656 if (basicClient->supportsZoomOverride()) {
5657 basicClient->setZoomOverride(mZoomOverrideValue);
5658 }
5659 }
5660 }
5661 }
5662
5663 return OK;
5664}
5665
Avichal Rakesh84147132021-11-11 17:47:11 -08005666status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07005667 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005668 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005669 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005670 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005671 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005672 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005673 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005674 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005675 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005676 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005677 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005678 dprintf(outFd, "Camera service watch commands:\n"
5679 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5680 " starts watching the provided tags for clients with provided package\n"
5681 " recognizes tag shorthands like '3a'\n"
5682 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005683 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005684 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005685 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005686 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005687 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005688 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005689 return BAD_VALUE;
5690}
5691
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005692status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5693 Mutex::Autolock lock(mLogLock);
5694 size_t tagsIdx; // index of '-m'
5695 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07005696 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005697 if (tagsIdx < args.size() - 1) {
5698 tags = args[tagsIdx + 1];
5699 } else {
5700 dprintf(outFd, "No tags provided.\n");
5701 return BAD_VALUE;
5702 }
5703
5704 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07005705 // watch all clients if no clients are provided
5706 String16 clients = toString16(kWatchAllClientsFlag);
5707 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005708 clientsIdx++);
5709 if (clientsIdx < args.size() - 1) {
5710 clients = args[clientsIdx + 1];
5711 }
Austin Borgered99f642023-06-01 16:51:35 -07005712 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005713
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005714 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07005715 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005716
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005717 bool serviceLock = tryLock(mServiceLock);
5718 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005719 auto cameraClients = mActiveClientManager.getAll();
5720 for (const auto &clientDescriptor: cameraClients) {
5721 if (clientDescriptor == nullptr) { continue; }
5722 sp<BasicClient> client = clientDescriptor->getValue();
5723 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005724
5725 if (isClientWatchedLocked(client.get())) {
5726 client->startWatchingTags(mMonitorTags, outFd);
5727 numWatchedClients++;
5728 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005729 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005730 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5731
5732 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005733 return OK;
5734}
5735
5736status_t CameraService::stopWatchingTags(int outFd) {
5737 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005738 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005739 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005740
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005741 mWatchedClientPackages.clear();
5742 mWatchedClientsDumpCache.clear();
5743
5744 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005745 auto cameraClients = mActiveClientManager.getAll();
5746 for (const auto &clientDescriptor : cameraClients) {
5747 if (clientDescriptor == nullptr) { continue; }
5748 sp<BasicClient> client = clientDescriptor->getValue();
5749 if (client.get() == nullptr) { continue; }
5750 client->stopWatchingTags(outFd);
5751 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005752 dprintf(outFd, "Stopped watching all clients.\n");
5753 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005754 return OK;
5755}
5756
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005757status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5758 Mutex::Autolock lock(mLogLock);
5759 size_t clearedSize = mWatchedClientsDumpCache.size();
5760 mWatchedClientsDumpCache.clear();
5761 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5762 return OK;
5763}
5764
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005765status_t CameraService::printWatchedTags(int outFd) {
5766 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005767 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005768
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005769 bool printedSomething = false; // tracks if any monitoring information was printed
5770 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005771
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005772 bool serviceLock = tryLock(mServiceLock);
5773 // get all watched clients that are currently connected
5774 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5775 if (clientDescriptor == nullptr) { continue; }
5776
5777 sp<BasicClient> client = clientDescriptor->getValue();
5778 if (client.get() == nullptr) { continue; }
5779 if (!isClientWatchedLocked(client.get())) { continue; }
5780
5781 std::vector<std::string> dumpVector;
5782 client->dumpWatchedEventsToVector(dumpVector);
5783
5784 size_t printIdx = dumpVector.size();
5785 if (printIdx == 0) {
5786 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005787 }
5788
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005789 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07005790 const std::string &cameraId = clientDescriptor->getKey();
5791 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005792 while(printIdx > 0) {
5793 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07005794 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005795 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005796 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005797 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005798 printedSomething = true;
5799
5800 connectedMonitoredClients.emplace(client->getPackageName());
5801 }
5802 if (serviceLock) { mServiceLock.unlock(); }
5803
5804 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5805 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07005806 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005807 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5808 continue;
5809 }
5810
Austin Borgered99f642023-06-01 16:51:35 -07005811 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005812 dprintf(outFd, "%s\n", kv.second.c_str());
5813 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005814 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005815
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005816 if (!printedSomething) {
5817 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005818 }
5819
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005820 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005821}
5822
Avichal Rakesh84147132021-11-11 17:47:11 -08005823// Print all events in vector `events' that came after lastPrintedEvent
5824void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005825 const std::string &cameraId,
5826 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08005827 const std::vector<std::string> &events,
5828 const std::string &lastPrintedEvent) {
5829 if (events.empty()) { return; }
5830
5831 // index of lastPrintedEvent in events.
5832 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5833 size_t lastPrintedIdx;
5834 for (lastPrintedIdx = 0;
5835 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5836 lastPrintedIdx++);
5837
5838 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5839
Avichal Rakesh84147132021-11-11 17:47:11 -08005840 // print events in chronological order (latest event last)
5841 size_t idxToPrint = lastPrintedIdx;
5842 do {
5843 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07005844 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
5845 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08005846 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08005847}
5848
5849// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5850// command should be interrupted if the user presses the return key, or if user loses any way to
5851// signal interrupt.
5852// If timeoutMs == 0, this function will always return false
5853bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5854 struct timeval startTime;
5855 int startTimeError = gettimeofday(&startTime, nullptr);
5856 if (startTimeError) {
5857 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5858 return true;
5859 }
5860
5861 const nfds_t numFds = 1;
5862 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5863
5864 struct timeval currTime;
5865 char buffer[2];
5866 while(true) {
5867 int currTimeError = gettimeofday(&currTime, nullptr);
5868 if (currTimeError) {
5869 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5870 return true;
5871 }
5872
5873 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5874 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5875 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5876
5877 if (remainingTimeMs <= 0) {
5878 // No user interrupt within timeoutMs, don't interrupt watch command
5879 return false;
5880 }
5881
5882 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5883 if (numFdsUpdated < 0) {
5884 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5885 return true;
5886 }
5887
5888 if (numFdsUpdated == 0) {
5889 // No user input within timeoutMs, don't interrupt watch command
5890 return false;
5891 }
5892
5893 if (!(pollFd.revents & POLLIN)) {
5894 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5895 return true;
5896 }
5897
5898 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5899 if (sizeRead < 0) {
5900 dprintf(outFd, "Error reading user input. Exiting.\n");
5901 return true;
5902 }
5903
5904 if (sizeRead == 0) {
5905 // Reached end of input fd (can happen if input is piped)
5906 // User has no way to signal an interrupt, so interrupt here
5907 return true;
5908 }
5909
5910 if (buffer[0] == '\n') {
5911 // User pressed return, interrupt watch command.
5912 return true;
5913 }
5914 }
5915}
5916
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005917status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5918 int inFd, int outFd) {
5919 // Figure out refresh interval, if present in args
5920 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005921 if (args.size() > 2) {
5922 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07005923 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005924 intervalIdx++);
5925
5926 size_t intervalValIdx = intervalIdx + 1;
5927 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07005928 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005929 if (errno) { return BAD_VALUE; }
5930 }
5931 }
5932
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005933 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5934 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005935
Avichal Rakesh84147132021-11-11 17:47:11 -08005936 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07005937 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005938
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005939 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005940 bool serviceLock = tryLock(mServiceLock);
5941 auto cameraClients = mActiveClientManager.getAll();
5942 if (serviceLock) { mServiceLock.unlock(); }
5943
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005944 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005945 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005946 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005947
5948 sp<BasicClient> client = clientDescriptor->getValue();
5949 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005950 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005951
Austin Borgered99f642023-06-01 16:51:35 -07005952 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08005953 // This also initializes the map entries with an empty string
5954 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5955
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005956 std::vector<std::string> latestEvents;
5957 client->dumpWatchedEventsToVector(latestEvents);
5958
5959 if (!latestEvents.empty()) {
5960 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005961 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08005962 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005963 latestEvents,
5964 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005965 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005966 }
5967 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005968 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005969 break;
5970 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005971 }
5972 return OK;
5973}
5974
Austin Borgered99f642023-06-01 16:51:35 -07005975void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005976 mWatchedClientPackages.clear();
5977
Austin Borgered99f642023-06-01 16:51:35 -07005978 std::istringstream iss(clients);
5979 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005980
Austin Borgered99f642023-06-01 16:51:35 -07005981 while (std::getline(iss, nextClient, ',')) {
5982 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005983 // Don't need to track any other package if 'all' is present
5984 mWatchedClientPackages.clear();
5985 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5986 break;
5987 }
5988
5989 // track package names
5990 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005991 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005992}
5993
Svet Ganova453d0d2018-01-11 15:37:58 -08005994status_t CameraService::printHelp(int out) {
5995 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005996 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5997 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5998 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005999 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6000 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6001 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006002 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6003 " Valid values 0=false, 1=true, 2=auto\n"
6004 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006005 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6006 " Valid values 0=OFF, 1=ON for JPEG\n"
6007 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006008 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006009 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6010 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6011 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6012 " on. In case the number of usecases is smaller than the number of streams, the\n"
6013 " last use case is assigned to all the remaining streams. In case of multiple\n"
6014 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6015 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6016 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6017 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006018 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6019 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
malikakash82ed4352023-07-21 22:44:34 +00006020 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006021 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006022 " help print this message\n");
6023}
6024
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006025bool CameraService::isClientWatched(const BasicClient *client) {
6026 Mutex::Autolock lock(mLogLock);
6027 return isClientWatchedLocked(client);
6028}
6029
6030bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6031 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6032 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6033}
6034
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006035int32_t CameraService::updateAudioRestriction() {
6036 Mutex::Autolock lock(mServiceLock);
6037 return updateAudioRestrictionLocked();
6038}
6039
6040int32_t CameraService::updateAudioRestrictionLocked() {
6041 int32_t mode = 0;
6042 // iterate through all active client
6043 for (const auto& i : mActiveClientManager.getAll()) {
6044 const auto clientSp = i->getValue();
6045 mode |= clientSp->getAudioRestriction();
6046 }
6047
6048 bool modeChanged = (mAudioRestriction != mode);
6049 mAudioRestriction = mode;
6050 if (modeChanged) {
6051 mAppOps.setCameraAudioRestriction(mode);
6052 }
6053 return mode;
6054}
6055
Austin Borgered99f642023-06-01 16:51:35 -07006056status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006057 sp<BasicClient> clientSp) {
6058 std::unique_ptr<AutoConditionLock> lock =
6059 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6060 status_t res = NO_ERROR;
6061 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006062 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006063 mInjectionStatusListener->notifyInjectionError(
6064 externalCamId, UNKNOWN_TRANSACTION);
6065 clientSp->notifyError(
6066 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6067 CaptureResultExtras());
6068
6069 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6070 // other clients from connecting in mServiceLockWrapper if held
6071 mServiceLock.unlock();
6072
6073 // Clear caller identity temporarily so client disconnect PID checks work correctly
6074 int64_t token = CameraThreadState::clearCallingIdentity();
6075 clientSp->disconnect();
6076 CameraThreadState::restoreCallingIdentity(token);
6077
6078 // Reacquire mServiceLock
6079 mServiceLock.lock();
6080 }
6081
6082 return res;
6083}
6084
Cliff Wud3a05312021-04-26 23:07:31 +08006085void CameraService::clearInjectionParameters() {
6086 {
6087 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006088 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006089 mInjectionInternalCamId = "";
6090 }
6091 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006092 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006093}
6094
Mathias Agopian65ab4712010-07-14 17:59:35 -07006095}; // namespace android