blob: da64b8d21da1bba43d3b5dfff50091e1a509ac9f [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
803 Mutex::Autolock lock(mCameraIdRemappingLock);
804 // This will disconnect all existing clients for camera Ids that are being
805 // remapped in cameraIdRemapping, but only if they were being used by an
806 // affected packageName.
807 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -0700808 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +0000809 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
810 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700811 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +0000812 id0.c_str(), id1.c_str());
813 auto clientDescriptor = mActiveClientManager.get(id0);
814 if (clientDescriptor != nullptr) {
815 sp<BasicClient> clientSp = clientDescriptor->getValue();
816 if (clientSp->getPackageName() == packageName) {
817 // This camera ID is being used by the affected packageName.
818 clientsToDisconnect.push_back(clientSp);
819 cameraIdsToUpdate.push_back(id0);
820 }
821 }
822 }
823 }
824
825 // Update mCameraIdRemapping.
826 mCameraIdRemapping.clear();
827 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
828
829 // Do not hold mServiceLock while disconnecting clients, but retain the condition
830 // blocking other clients from connecting in mServiceLockWrapper if held.
831 mServiceLock.unlock();
832
833 // Disconnect clients.
834 for (auto& clientSp : clientsToDisconnect) {
835 // We send up ERROR_CAMERA_DEVICE so that the app attempts to reconnect
836 // automatically.
837 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
838 CaptureResultExtras{});
839 // This also triggers the status updates
840 clientSp->disconnect();
841 }
842
843 mServiceLock.lock();
844}
845
Austin Borgered99f642023-06-01 16:51:35 -0700846std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
847 const std::string& inputCameraId, int clientUid) {
848 std::string packageName = getPackageNameFromUid(clientUid);
849 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +0000850 Mutex::Autolock lock(mCameraIdRemappingLock);
851 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
852 packageMapIter != mCameraIdRemapping.end()) {
853 for (auto& [id0, id1]: packageMapIter->second) {
854 if (id1 == inputCameraId) {
855 cameraIds.push_back(id0);
856 }
857 }
858 }
859 return cameraIds;
860}
861
Austin Borgered99f642023-06-01 16:51:35 -0700862std::string CameraService::resolveCameraId(const std::string& inputCameraId) {
863 return resolveCameraId(inputCameraId, std::string(""));
malikakash82ed4352023-07-21 22:44:34 +0000864}
865
Austin Borgered99f642023-06-01 16:51:35 -0700866std::string CameraService::resolveCameraId(
867 const std::string& inputCameraId,
868 const std::string& packageName) {
869 std::string packageNameVal = packageName;
870 if (packageName == "") {
malikakash82ed4352023-07-21 22:44:34 +0000871 int clientUid = CameraThreadState::getCallingUid();
872 packageNameVal = getPackageNameFromUid(clientUid);
873 }
874 Mutex::Autolock lock(mCameraIdRemappingLock);
875 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
876 packageMapIter != mCameraIdRemapping.end()) {
877 ALOGI("%s: resolveCameraId: packageName found %s",
Austin Borgered99f642023-06-01 16:51:35 -0700878 __FUNCTION__, packageNameVal.c_str());
malikakash82ed4352023-07-21 22:44:34 +0000879 auto packageMap = packageMapIter->second;
880 if (auto replacementIdIter = packageMap.find(inputCameraId);
881 replacementIdIter != packageMap.end()) {
882 ALOGI("%s: resolveCameraId: inputId found %s, replacing with %s",
883 __FUNCTION__, inputCameraId.c_str(),
884 replacementIdIter->second.c_str());
885 return replacementIdIter->second;
886 }
887 }
888 return inputCameraId;
889}
890
Austin Borger18b30a72022-10-27 12:20:29 -0700891Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800892 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700893 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100894 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700895 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId);
Austin Borgered99f642023-06-01 16:51:35 -0700896 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700897 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
898 "characteristics for system only device %s: ", cameraIdStr.c_str());
899 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100900
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800901 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -0700902 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800903 return STATUS_ERROR(ERROR_DISCONNECTED,
904 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700905 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700906 bool hasSystemCameraPermissions =
907 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
908 CameraThreadState::getCallingUid());
909 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
910 if (hasSystemCameraPermissions) {
911 cameraIdBound = mNumberOfCameras;
912 }
913 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800914 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
915 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916 }
917
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800918 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700919 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800920 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -0700921 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100922 if (err != OK) {
923 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
924 "Error retrieving camera info from device %d: %s (%d)", cameraId,
925 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -0700926 logServiceError(std::string("Error retrieving camera info from device ")
927 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800928 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100929
Ruben Brunkcc776712015-02-17 20:18:47 -0800930 return ret;
931}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700932
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800933std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700934 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
935 auto callingPid = CameraThreadState::getCallingPid();
936 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +0000937 permission::PermissionChecker permissionChecker;
938 AttributionSourceState attributionSource{};
939 attributionSource.pid = callingPid;
940 attributionSource.uid = callingUid;
941 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700942 toString16(sSystemCameraPermission), attributionSource, String16(),
943 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000944 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700945 deviceIds = &mNormalDeviceIds;
946 }
947 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800948 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700949 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800950 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800951 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800952
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700953 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800954}
955
Austin Borgered99f642023-06-01 16:51:35 -0700956std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800957 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -0700958 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800959}
960
Austin Borgered99f642023-06-01 16:51:35 -0700961Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700962 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700963 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -0700964
965 const std::string cameraId = resolveCameraId(unresolvedCameraId);
966
Zhijun He2b59be82013-09-25 10:14:30 -0700967 if (!cameraInfo) {
968 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800969 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700970 }
971
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800972 if (!mInitialized) {
973 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -0700974 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800975 return STATUS_ERROR(ERROR_DISCONNECTED,
976 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700977 }
978
Austin Borgered99f642023-06-01 16:51:35 -0700979 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700980 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -0700981 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700982 }
983
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800984 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800985
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700986 bool overrideForPerfClass =
987 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -0700988 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100989 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -0700990 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100991 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700992 if (res == NAME_NOT_FOUND) {
993 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -0700994 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700995 strerror(-res), res);
996 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700997 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
998 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -0700999 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001000 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001001 strerror(-res), res);
1002 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001003 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001004 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001005 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1006 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001007 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001008 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001009 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001010 int callingPid = CameraThreadState::getCallingPid();
1011 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001012 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001013 // If it's not calling from cameraserver, check the permission only if
1014 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1015 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +00001016 permission::PermissionChecker permissionChecker;
1017 AttributionSourceState attributionSource{};
1018 attributionSource.pid = callingPid;
1019 attributionSource.uid = callingUid;
1020 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001021 toString16(sCameraPermission), attributionSource, String16(),
1022 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Emilian Peeve20c6372018-08-14 18:45:53 +01001023 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001024 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001025 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001026 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001027 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001028 &tagsRemoved);
1029 if (res != OK) {
1030 cameraInfo->clear();
1031 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1032 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001033 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001034 }
1035 }
1036
1037 if (!tagsRemoved.empty()) {
1038 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1039 tagsRemoved.data(), tagsRemoved.size());
1040 if (res != OK) {
1041 cameraInfo->clear();
1042 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001043 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001044 strerror(-res), res);
1045 }
1046 }
1047
Zhijun He2b59be82013-09-25 10:14:30 -07001048 return ret;
1049}
1050
Austin Borgered99f642023-06-01 16:51:35 -07001051Status CameraService::getTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001052 int32_t* torchStrength) {
1053 ATRACE_CALL();
1054 Mutex::Autolock l(mServiceLock);
1055 if (!mInitialized) {
1056 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1057 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1058 }
1059
1060 if(torchStrength == NULL) {
1061 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1062 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1063 }
1064
Austin Borgered99f642023-06-01 16:51:35 -07001065 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001066 if (res != OK) {
1067 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001068 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001069 strerror(-res), res);
1070 }
1071 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1072 return Status::ok();
1073}
1074
Austin Borgered99f642023-06-01 16:51:35 -07001075std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001076 time_t now = time(nullptr);
1077 char formattedTime[64];
1078 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001079 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001080}
1081
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001082Status CameraService::getCameraVendorTagDescriptor(
1083 /*out*/
1084 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001085 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001086 if (!mInitialized) {
1087 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001088 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001089 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001090 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1091 if (globalDescriptor != nullptr) {
1092 *desc = *(globalDescriptor.get());
1093 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001094 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001095}
1096
Emilian Peev71c73a22017-03-21 16:35:51 +00001097Status CameraService::getCameraVendorTagCache(
1098 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1099 ATRACE_CALL();
1100 if (!mInitialized) {
1101 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1102 return STATUS_ERROR(ERROR_DISCONNECTED,
1103 "Camera subsystem not available");
1104 }
1105 sp<VendorTagDescriptorCache> globalCache =
1106 VendorTagDescriptorCache::getGlobalVendorTagCache();
1107 if (globalCache != nullptr) {
1108 *cache = *(globalCache.get());
1109 }
1110 return Status::ok();
1111}
1112
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001113void CameraService::clearCachedVariables() {
1114 BasicClient::BasicClient::sCameraService = nullptr;
1115}
1116
Austin Borgered99f642023-06-01 16:51:35 -07001117std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001118 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001119 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001120
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001121 int deviceVersion = 0;
1122
Emilian Peevf53f66e2017-04-11 14:29:43 +01001123 status_t res;
1124 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001125 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001126 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001127 if (res != OK || transport == IPCTransport::INVALID) {
1128 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001129 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001130 return std::make_pair(-1, IPCTransport::INVALID) ;
1131 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001132 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001133
Emilian Peevf53f66e2017-04-11 14:29:43 +01001134 hardware::CameraInfo info;
1135 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001136 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001137 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001138 if (res != OK) {
1139 return std::make_pair(-1, IPCTransport::INVALID);
1140 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001141 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001142 if (orientation) {
1143 *orientation = info.orientation;
1144 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001145 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001146
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001147 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001148}
1149
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001150Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001151 switch(err) {
1152 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001153 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001154 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001155 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1156 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001157 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001158 return STATUS_ERROR(ERROR_DISCONNECTED,
1159 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001160 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001161 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1162 "Camera HAL encountered error %d: %s",
1163 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001164 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001165}
1166
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001167Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001168 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1169 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001170 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001171 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001172 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
Austin Borgered99f642023-06-01 16:51:35 -07001173 bool forceSlowJpegMode, const std::string& originalCameraId, /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001174 // For HIDL devices
1175 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1176 // Create CameraClient based on device version reported by the HAL.
1177 int deviceVersion = deviceVersionAndTransport.first;
1178 switch(deviceVersion) {
1179 case CAMERA_DEVICE_API_VERSION_1_0:
1180 ALOGE("Camera using old HAL version: %d", deviceVersion);
1181 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1182 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001183 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001184 break;
1185 case CAMERA_DEVICE_API_VERSION_3_0:
1186 case CAMERA_DEVICE_API_VERSION_3_1:
1187 case CAMERA_DEVICE_API_VERSION_3_2:
1188 case CAMERA_DEVICE_API_VERSION_3_3:
1189 case CAMERA_DEVICE_API_VERSION_3_4:
1190 case CAMERA_DEVICE_API_VERSION_3_5:
1191 case CAMERA_DEVICE_API_VERSION_3_6:
1192 case CAMERA_DEVICE_API_VERSION_3_7:
1193 break;
1194 default:
1195 // Should not be reachable
1196 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1197 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1198 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001199 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001200 }
1201 }
1202 if (effectiveApiLevel == API_1) { // Camera1 API route
1203 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001204 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borgered99f642023-06-01 16:51:35 -07001205 packageName, featureId, cameraId,
1206 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001207 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1208 forceSlowJpegMode);
1209 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1210 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001211 } else { // Camera2 API route
1212 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1213 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001214 *client = new CameraDeviceClient(cameraService, tmp,
1215 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1216 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001217 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001218 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001219 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001220 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001221}
1222
Austin Borgered99f642023-06-01 16:51:35 -07001223std::string CameraService::toString(std::set<userid_t> intSet) {
1224 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001225 bool first = true;
1226 for (userid_t i : intSet) {
1227 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001228 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001229 first = false;
1230 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001231 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001232 }
1233 }
Austin Borgered99f642023-06-01 16:51:35 -07001234 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001235}
1236
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001237int32_t CameraService::mapToInterface(TorchModeStatus status) {
1238 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1239 switch (status) {
1240 case TorchModeStatus::NOT_AVAILABLE:
1241 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1242 break;
1243 case TorchModeStatus::AVAILABLE_OFF:
1244 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1245 break;
1246 case TorchModeStatus::AVAILABLE_ON:
1247 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1248 break;
1249 default:
1250 ALOGW("Unknown new flash status: %d", status);
1251 }
1252 return serviceStatus;
1253}
1254
1255CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1256 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1257 switch (status) {
1258 case CameraDeviceStatus::NOT_PRESENT:
1259 serviceStatus = StatusInternal::NOT_PRESENT;
1260 break;
1261 case CameraDeviceStatus::PRESENT:
1262 serviceStatus = StatusInternal::PRESENT;
1263 break;
1264 case CameraDeviceStatus::ENUMERATING:
1265 serviceStatus = StatusInternal::ENUMERATING;
1266 break;
1267 default:
1268 ALOGW("Unknown new HAL device status: %d", status);
1269 }
1270 return serviceStatus;
1271}
1272
1273int32_t CameraService::mapToInterface(StatusInternal status) {
1274 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1275 switch (status) {
1276 case StatusInternal::NOT_PRESENT:
1277 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1278 break;
1279 case StatusInternal::PRESENT:
1280 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1281 break;
1282 case StatusInternal::ENUMERATING:
1283 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1284 break;
1285 case StatusInternal::NOT_AVAILABLE:
1286 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1287 break;
1288 case StatusInternal::UNKNOWN:
1289 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1290 break;
1291 default:
1292 ALOGW("Unknown new internal device status: %d", status);
1293 }
1294 return serviceStatus;
1295}
1296
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001297Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001298 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001299
Austin Borgered99f642023-06-01 16:51:35 -07001300 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001301 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001302 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001303 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001304 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1305 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001306 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001307 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001308 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001309 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001310 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001311 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001312 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001313}
1314
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001315Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001316 /*out*/
1317 CameraParameters* parameters) {
1318
1319 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1320
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001321 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001322
1323 if (parameters == NULL) {
1324 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001325 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001326 }
1327
Austin Borgered99f642023-06-01 16:51:35 -07001328 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001329
1330 // Check if we already have parameters
1331 {
1332 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001333 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001334 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001335 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001336 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001337 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001338 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001339 }
1340 CameraParameters p = cameraState->getShimParams();
1341 if (!p.isEmpty()) {
1342 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001343 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001344 }
1345 }
1346
Jayant Chowdhary12361932018-08-27 14:46:13 -07001347 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001348 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001349 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001350 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001351 // Error already logged by callee
1352 return ret;
1353 }
1354
1355 // Check for parameters again
1356 {
1357 // Scope for service lock
1358 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001359 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001360 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001361 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001362 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001363 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001364 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001365 CameraParameters p = cameraState->getShimParams();
1366 if (!p.isEmpty()) {
1367 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001368 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001369 }
1370 }
1371
Ruben Brunkcc776712015-02-17 20:18:47 -08001372 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1373 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001374 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001375}
1376
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001377// Can camera service trust the caller based on the calling UID?
1378static bool isTrustedCallingUid(uid_t uid) {
1379 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001380 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001381 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001382 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001383 return true;
1384 default:
1385 return false;
1386 }
1387}
1388
Austin Borgered99f642023-06-01 16:51:35 -07001389static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
1390 int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07001391 PermissionController pc;
Austin Borgered99f642023-06-01 16:51:35 -07001392 uid = pc.getPackageUid(toString16(packageName), 0);
Nicholas Sauera3620332019-04-03 14:05:17 -07001393 if (uid <= 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001394 ALOGE("Unknown package: '%s'", packageName.c_str());
1395 dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07001396 return BAD_VALUE;
1397 }
1398
1399 if (userId < 0) {
1400 ALOGE("Invalid user: %d", userId);
1401 dprintf(err, "Invalid user: %d\n", userId);
1402 return BAD_VALUE;
1403 }
1404
1405 uid = multiuser_get_uid(userId, uid);
1406 return NO_ERROR;
1407}
1408
Austin Borgered99f642023-06-01 16:51:35 -07001409Status CameraService::validateConnectLocked(const std::string& cameraId,
1410 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001411 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001412
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001413#ifdef __BRILLO__
1414 UNUSED(clientName8);
1415 UNUSED(clientUid);
1416 UNUSED(clientPid);
1417 UNUSED(originalClientPid);
1418#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001419 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1420 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001421 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001422 return allowed;
1423 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001424#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001425
Jayant Chowdhary12361932018-08-27 14:46:13 -07001426 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001427
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001428 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001429 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1430 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001431 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001432 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001433 }
1434
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 if (getCameraState(cameraId) == nullptr) {
1436 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001437 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001438 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001439 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001440 }
1441
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001442 status_t err = checkIfDeviceIsUsable(cameraId);
1443 if (err != NO_ERROR) {
1444 switch(err) {
1445 case -ENODEV:
1446 case -EBUSY:
1447 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001448 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001449 default:
1450 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001451 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001452 }
1453 }
1454 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001455}
1456
Austin Borgered99f642023-06-01 16:51:35 -07001457Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1458 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001459 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001460 permission::PermissionChecker permissionChecker;
1461 AttributionSourceState attributionSource{};
1462
Jayant Chowdhary12361932018-08-27 14:46:13 -07001463 int callingPid = CameraThreadState::getCallingPid();
1464 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001465
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001466 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001467 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001468 clientUid = callingUid;
1469 } else if (!isTrustedCallingUid(callingUid)) {
1470 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1471 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001472 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1473 "Untrusted caller (calling PID %d, UID %d) trying to "
1474 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001475 callingPid, callingUid, cameraId.c_str(),
1476 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001477 }
1478
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001479 // Check if we can trust clientPid
1480 if (clientPid == USE_CALLING_PID) {
1481 clientPid = callingPid;
1482 } else if (!isTrustedCallingUid(callingUid)) {
1483 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1484 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001485 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1486 "Untrusted caller (calling PID %d, UID %d) trying to "
1487 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001488 callingPid, callingUid, cameraId.c_str(),
1489 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001490 }
1491
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001492 if (shouldRejectSystemCameraConnection(cameraId)) {
1493 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1494 cameraId.c_str());
1495 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001496 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001497 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001498 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1499 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001500 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001501 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001502 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001503
1504 }
1505
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001506 // If it's not calling from cameraserver, check the permission if the
1507 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1508 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001509 attributionSource.pid = clientPid;
1510 attributionSource.uid = clientUid;
Austin Borgered99f642023-06-01 16:51:35 -07001511 attributionSource.packageName = clientName;
Joanne Chung02c13d02023-01-16 12:58:05 +00001512 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001513 toString16(sCameraPermission), attributionSource, String16(), AppOpsManager::OP_NONE)
Joanne Chung02c13d02023-01-16 12:58:05 +00001514 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001515 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001516 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001517 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001518 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1519 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001520 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001521 }
1522
Svet Ganova453d0d2018-01-11 15:37:58 -08001523 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001524 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001525 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001526 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1527 clientPid, clientUid);
1528 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001529 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1530 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001531 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001532 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001533 }
1534
Michael Grooverd1d435a2018-12-18 17:39:42 -08001535 // If sensor privacy is enabled then prevent access to the camera
1536 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1537 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1538 return STATUS_ERROR_FMT(ERROR_DISABLED,
1539 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001540 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001541 }
1542
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001543 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1544 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001545 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001546 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001547
Ruben Brunk6267b532015-04-30 17:44:07 -07001548 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001549
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001550 // For non-system clients : Only allow clients who are being used by the current foreground
1551 // device user, unless calling from our own process.
1552 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001553 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001554 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1555 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001556 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1558 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001559 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001560 }
1561
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001562 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001563}
1564
Austin Borgered99f642023-06-01 16:51:35 -07001565status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001566 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001567 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001568 if (cameraState == nullptr) {
1569 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001570 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001571 return -ENODEV;
1572 }
1573
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001574 StatusInternal currentStatus = cameraState->getStatus();
1575 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001576 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001577 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001578 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001579 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001580 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001581 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001582 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001583 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001584
Ruben Brunkcc776712015-02-17 20:18:47 -08001585 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001586}
1587
Ruben Brunkcc776712015-02-17 20:18:47 -08001588void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001589 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001590
Ruben Brunkcc776712015-02-17 20:18:47 -08001591 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001592 auto clientDescriptor =
1593 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001594 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001595 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1596
1597 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001598 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001599
1600 if (evicted.size() > 0) {
1601 // This should never happen - clients should already have been removed in disconnect
1602 for (auto& i : evicted) {
1603 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001604 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001605 }
1606
1607 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1608 __FUNCTION__);
1609 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001610
1611 // And register a death notification for the client callback. Do
1612 // this last to avoid Binder policy where a nested Binder
1613 // transaction might be pre-empted to service the client death
1614 // notification if the client process dies before linkToDeath is
1615 // invoked.
1616 sp<IBinder> remoteCallback = client->getRemote();
1617 if (remoteCallback != nullptr) {
1618 remoteCallback->linkToDeath(this);
1619 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001620}
1621
Austin Borgered99f642023-06-01 16:51:35 -07001622status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1623 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1624 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001625 /*out*/
1626 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001627 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001628 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001629 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001630 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001631 DescriptorPtr clientDescriptor;
1632 {
1633 if (effectiveApiLevel == API_1) {
1634 // If we are using API1, any existing client for this camera ID with the same remote
1635 // should be returned rather than evicted to allow MediaRecorder to work properly.
1636
1637 auto current = mActiveClientManager.get(cameraId);
1638 if (current != nullptr) {
1639 auto clientSp = current->getValue();
1640 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001641 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001642 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001643 " API level, evicting prior client...");
1644 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001645 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001646 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001647 *client = clientSp;
1648 return NO_ERROR;
1649 }
1650 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001651 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001652 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001653
Ruben Brunkcc776712015-02-17 20:18:47 -08001654 // Get current active client PIDs
1655 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1656 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001657
Emilian Peev8131a262017-02-01 12:33:43 +00001658 std::vector<int> priorityScores(ownerPids.size());
1659 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001660
Emilian Peev8131a262017-02-01 12:33:43 +00001661 // Get priority scores of all active PIDs
1662 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1663 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1664 /*out*/&priorityScores[0]);
1665 if (err != OK) {
1666 ALOGE("%s: Priority score query failed: %d",
1667 __FUNCTION__, err);
1668 return err;
1669 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001670
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001672 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001673 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001674 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001675 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001676 /* isVendorClient won't get copied over*/ false,
1677 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 }
1679 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001680
Ruben Brunkcc776712015-02-17 20:18:47 -08001681 // Get state for the given cameraId
1682 auto state = getCameraState(cameraId);
1683 if (state == nullptr) {
1684 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001685 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001686 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001687 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001688 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001689
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001690 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1691 int32_t actualState = states[states.size() - 1];
1692
1693 // Make descriptor for incoming client. We store the oomScoreOffset
1694 // since we might need it later on new handleEvictionsLocked and
1695 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001696 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001697 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001698 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001699 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001700
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001701 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1702
Ruben Brunkcc776712015-02-17 20:18:47 -08001703 // Find clients that would be evicted
1704 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1705
1706 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1707 // background, so we cannot do evictions
1708 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1709 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1710 " priority).", clientPid);
1711
1712 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001713 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001714 auto incompatibleClients =
1715 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1716
Austin Borgered99f642023-06-01 16:51:35 -07001717 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1718 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1719 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001720 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001721
1722 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001723 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001724 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001725 i->getKey().c_str(),
1726 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001727 i->getOwnerId(), i->getPriority().getScore(),
1728 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001729 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07001730 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
1731 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001732 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001733 }
1734
1735 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001736 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001737 mEventLog.add(msg);
1738
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001739 auto current = mActiveClientManager.get(cameraId);
1740 if (current != nullptr) {
1741 return -EBUSY; // CAMERA_IN_USE
1742 } else {
1743 return -EUSERS; // MAX_CAMERAS_IN_USE
1744 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001745 }
1746
1747 for (auto& i : evicted) {
1748 sp<BasicClient> clientSp = i->getValue();
1749 if (clientSp.get() == nullptr) {
1750 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1751
1752 // TODO: Remove this
1753 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1754 __FUNCTION__);
1755 mActiveClientManager.remove(i);
1756 continue;
1757 }
1758
1759 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07001760 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001761 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001762
Ruben Brunkcc776712015-02-17 20:18:47 -08001763 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07001764 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001765 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1766 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001767 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001768 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07001769 i->getPriority().getState(), cameraId.c_str(),
1770 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001771 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001772
1773 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001774 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001775 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001776 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001777 }
1778
Ruben Brunkcc776712015-02-17 20:18:47 -08001779 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1780 // other clients from connecting in mServiceLockWrapper if held
1781 mServiceLock.unlock();
1782
1783 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001784 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001785
1786 // Destroy evicted clients
1787 for (auto& i : evictedClients) {
1788 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001789 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001790 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001791
Jayant Chowdhary12361932018-08-27 14:46:13 -07001792 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001793
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001794 for (const auto& i : evictedClients) {
1795 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001796 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001797 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1798 if (ret == TIMED_OUT) {
1799 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07001800 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
1801 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001802 return -EBUSY;
1803 }
1804 if (ret != NO_ERROR) {
1805 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07001806 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
1807 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001808 return ret;
1809 }
1810 }
1811
1812 evictedClients.clear();
1813
Ruben Brunkcc776712015-02-17 20:18:47 -08001814 // Once clients have been disconnected, relock
1815 mServiceLock.lock();
1816
1817 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1818 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1819 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001820 }
1821
Ruben Brunkcc776712015-02-17 20:18:47 -08001822 *partial = clientDescriptor;
1823 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001824}
1825
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001826Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001827 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001828 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001829 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001830 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001831 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001832 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001833 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00001834 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001835 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001836 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001837
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001838 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001839 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001840
Austin Borgered99f642023-06-01 16:51:35 -07001841 std::string cameraIdStr = cameraIdIntToStr(api1CameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001842 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001843 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
1844 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001845 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07001846 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001847
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001848 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07001849 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
1850 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001851 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001852 }
1853
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001854 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00001855
1856 const sp<IServiceManager> sm(defaultServiceManager());
1857 const auto& mActivityManager = getActivityManager();
1858 if (mActivityManager) {
1859 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
1860 CameraThreadState::getCallingUid(),
1861 CameraThreadState::getCallingPid());
1862 }
1863
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001864 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001865}
1866
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001867bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1868 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001869 // If the client is not a vendor client, don't add listener if
1870 // a) the camera is a publicly hidden secure camera OR
1871 // b) the camera is a system only camera and the client doesn't
1872 // have android.permission.SYSTEM_CAMERA permissions.
1873 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1874 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1875 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001876 return true;
1877 }
1878 return false;
1879}
1880
Austin Borgered99f642023-06-01 16:51:35 -07001881bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001882 // Rules for rejection:
1883 // 1) If cameraserver tries to access this camera device, accept the
1884 // connection.
1885 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001886 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001887 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1888 // and the serving thread is a non hwbinder thread, the client must have
1889 // android.permission.SYSTEM_CAMERA permissions to connect.
1890
1891 int cPid = CameraThreadState::getCallingPid();
1892 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001893 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001894 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1895 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001896 // This isn't a known camera ID, so it's not a system camera
1897 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1898 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001899 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001900
1901 // (1) Cameraserver trying to connect, accept.
1902 if (CameraThreadState::getCallingPid() == getpid()) {
1903 return false;
1904 }
1905 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001906 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001907 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1908 return true;
1909 }
1910 // (3) Here we only check for permissions if it is a system only camera device. This is since
1911 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1912 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1913 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001914 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001915 !hasPermissionsForSystemCamera(cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001916 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1917 cameraId.c_str());
1918 return true;
1919 }
1920
1921 return false;
1922}
1923
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001924Status CameraService::connectDevice(
1925 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07001926 const std::string& unresolvedCameraId,
1927 const std::string& clientPackageName,
1928 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001929 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001930 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001931 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001932 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001933
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001934 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001935 Status ret = Status::ok();
Austin Borgered99f642023-06-01 16:51:35 -07001936 const std::string cameraId = resolveCameraId(unresolvedCameraId, clientPackageName);
Ruben Brunkcc776712015-02-17 20:18:47 -08001937 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001938 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001939 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001940 bool systemNativeClient = false;
1941 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1942 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07001943 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
1944 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001945 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001946 }
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001947
1948 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001949 std::string msg =
1950 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
1951 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
1952 cameraId.c_str());
1953 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1954 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001955 }
1956
Austin Borger9bfa0a72022-08-03 17:50:40 -07001957 userid_t clientUserId = multiuser_get_user_id(clientUid);
1958 int callingUid = CameraThreadState::getCallingUid();
1959 if (clientUid == USE_CALLING_UID) {
1960 clientUserId = multiuser_get_user_id(callingUid);
1961 }
1962
1963 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07001964 std::string msg = "Camera disabled by device policy";
1965 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1966 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07001967 }
1968
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001969 // enforce system camera permissions
1970 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001971 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
1972 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07001973 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001974 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07001975 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
1976 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1977 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001978 }
1979
Austin Borgered99f642023-06-01 16:51:35 -07001980 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
1981 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001982 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Chengfei Taobe683db2023-01-31 18:52:49 +00001983 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false,
Austin Borgered99f642023-06-01 16:51:35 -07001984 unresolvedCameraId, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08001985
Austin Borgered99f642023-06-01 16:51:35 -07001986 if (!ret.isOk()) {
1987 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001988 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08001989 }
1990
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001991 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07001992 Mutex::Autolock lock(mServiceLock);
1993
1994 // Clear the previous cached logs and reposition the
1995 // file offset to beginning of the file to log new data.
1996 // If either truncate or lseek fails, close the previous file and create a new one.
1997 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
1998 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
1999 // Close the previous memfd.
2000 close(mMemFd);
2001 // If failure to wipe the data, then create a new file and
2002 // assign the new value to mMemFd.
2003 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2004 if (mMemFd == -1) {
2005 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2006 }
2007 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002008 const sp<IServiceManager> sm(defaultServiceManager());
2009 const auto& mActivityManager = getActivityManager();
2010 if (mActivityManager) {
2011 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2012 CameraThreadState::getCallingUid(),
2013 CameraThreadState::getCallingPid());
2014 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002015 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002016}
2017
Austin Borgered99f642023-06-01 16:51:35 -07002018std::string CameraService::getPackageNameFromUid(int clientUid) {
2019 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002020
2021 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002022 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002023 if (binder == 0) {
2024 ALOGE("Cannot get permission service");
2025 // Return empty package name and the further interaction
2026 // with camera will likely fail
2027 return packageName;
2028 }
2029
2030 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2031 Vector<String16> packages;
2032
2033 permCtrl->getPackagesForUid(clientUid, packages);
2034
2035 if (packages.isEmpty()) {
2036 ALOGE("No packages for calling UID %d", clientUid);
2037 // Return empty package name and the further interaction
2038 // with camera will likely fail
2039 return packageName;
2040 }
2041
2042 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002043 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002044
2045 return packageName;
2046}
2047
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002048template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002049Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2050 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2051 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002052 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002053 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002054 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002055 binder::Status ret = binder::Status::ok();
2056
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002057 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002058 std::string clientPackageName;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002059 if (clientPackageNameMaybe.size() <= 0) {
2060 // NDK calls don't come with package names, but we need one for various cases.
2061 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2062 // do exist. For all authentication cases, all packages under the same UID get the
2063 // same permissions, so picking any associated package name is sufficient. For some
2064 // other cases, this may give inaccurate names for clients in logs.
2065 isNonSystemNdk = true;
2066 int packageUid = (clientUid == USE_CALLING_UID) ?
2067 CameraThreadState::getCallingUid() : clientUid;
2068 clientPackageName = getPackageNameFromUid(packageUid);
2069 } else {
2070 clientPackageName = clientPackageNameMaybe;
2071 }
2072
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002073 int originalClientPid = 0;
2074
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002075 int packagePid = (clientPid == USE_CALLING_PID) ?
2076 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002077 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002078 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002079 static_cast<int>(effectiveApiLevel));
2080
Shuzhen Wang316781a2020-08-18 18:11:01 -07002081 nsecs_t openTimeNs = systemTime();
2082
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002083 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002084 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002085 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002086
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002087 {
2088 // Acquire mServiceLock and prevent other clients from connecting
2089 std::unique_ptr<AutoConditionLock> lock =
2090 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2091
2092 if (lock == nullptr) {
2093 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2094 , clientPid);
2095 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2096 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002097 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002098 }
2099
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002100 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002101 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002102 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2103 return ret;
2104 }
2105
2106 // Check the shim parameters after acquiring lock, if they have already been updated and
2107 // we were doing a shim update, return immediately
2108 if (shimUpdateOnly) {
2109 auto cameraState = getCameraState(cameraId);
2110 if (cameraState != nullptr) {
2111 if (!cameraState->getShimParams().isEmpty()) return ret;
2112 }
2113 }
2114
2115 status_t err;
2116
2117 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002118 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002119 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002120 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2121 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002122 switch (err) {
2123 case -ENODEV:
2124 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2125 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002126 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002127 case -EBUSY:
2128 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2129 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002130 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002131 case -EUSERS:
2132 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2133 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002134 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002135 default:
2136 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2137 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002138 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002139 }
2140 }
2141
2142 if (clientTmp.get() != nullptr) {
2143 // Handle special case for API1 MediaRecorder where the existing client is returned
2144 device = static_cast<CLIENT*>(clientTmp.get());
2145 return ret;
2146 }
2147
2148 // give flashlight a chance to close devices if necessary.
2149 mFlashlight->prepareDeviceOpen(cameraId);
2150
Austin Borger18b30a72022-10-27 12:20:29 -07002151 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002152 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002153 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2154 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002155 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002156 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002157 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002158 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002159 }
2160
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002161 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002162 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002163 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002164 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002165 clientFeatureId, cameraId, api1CameraId, facing,
2166 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002167 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002168 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002169 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002170 return ret;
2171 }
2172 client = static_cast<CLIENT*>(tmp.get());
2173
2174 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2175 __FUNCTION__);
2176
Austin Borgered99f642023-06-01 16:51:35 -07002177 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002178 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002179 if (err != OK) {
2180 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002181 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002182 mServiceLock.unlock();
2183 client->disconnect();
2184 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002185 switch(err) {
2186 case BAD_VALUE:
2187 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002188 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002189 case -EBUSY:
2190 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002191 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002192 case -EUSERS:
2193 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2194 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002195 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002196 case PERMISSION_DENIED:
2197 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002198 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002199 case -EACCES:
2200 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002201 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002202 case -ENODEV:
2203 default:
2204 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002205 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002206 strerror(-err), err);
2207 }
2208 }
2209
2210 // Update shim paremeters for legacy clients
2211 if (effectiveApiLevel == API_1) {
2212 // Assume we have always received a Client subclass for API1
2213 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2214 String8 rawParams = shimClient->getParameters();
2215 CameraParameters params(rawParams);
2216
2217 auto cameraState = getCameraState(cameraId);
2218 if (cameraState != nullptr) {
2219 cameraState->setShimParams(params);
2220 } else {
2221 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002222 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002223 }
2224 }
2225
Ravneetaeb20dc2022-03-30 05:33:03 +00002226 // Enable/disable camera service watchdog
2227 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2228
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002229 // Set rotate-and-crop override behavior
2230 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2231 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002232 } else if (overrideToPortrait && portraitRotation != 0) {
2233 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2234 switch (portraitRotation) {
2235 case 90:
2236 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2237 break;
2238 case 180:
2239 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2240 break;
2241 case 270:
2242 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2243 break;
2244 default:
2245 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2246 break;
2247 }
2248 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002249 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002250 client->setRotateAndCropOverride(
2251 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2252 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2253 }
2254
2255 // Set autoframing override behaviour
2256 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2257 client->setAutoframingOverride(mOverrideAutoframingMode);
2258 } else {
2259 client->setAutoframingOverride(
2260 mCameraServiceProxyWrapper->getAutoframingOverride(
2261 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002262 }
2263
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002264 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002265 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002266 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002267 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002268 client->setCameraMute(
2269 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2270 } else if (isCameraPrivacyEnabled) {
2271 // no camera mute supported, but privacy is on! => disconnect
2272 ALOGI("Camera mute not supported for package: %s, camera id: %s",
Austin Borgered99f642023-06-01 16:51:35 -07002273 client->getPackageName().c_str(), cameraId.c_str());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002274 // Do not hold mServiceLock while disconnecting clients, but
2275 // retain the condition blocking other clients from connecting
2276 // in mServiceLockWrapper if held.
2277 mServiceLock.unlock();
2278 // Clear caller identity temporarily so client disconnect PID
2279 // checks work correctly
2280 int64_t token = CameraThreadState::clearCallingIdentity();
2281 // Note AppOp to trigger the "Unblock" dialog
2282 client->noteAppOp();
2283 client->disconnect();
2284 CameraThreadState::restoreCallingIdentity(token);
2285 // Reacquire mServiceLock
2286 mServiceLock.lock();
2287
2288 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002289 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002290 }
2291
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002292 if (shimUpdateOnly) {
2293 // If only updating legacy shim parameters, immediately disconnect client
2294 mServiceLock.unlock();
2295 client->disconnect();
2296 mServiceLock.lock();
2297 } else {
2298 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002299 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002300 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002301
2302 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002303 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002304 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002305 } // lock is destroyed, allow further connect calls
2306
2307 // Important: release the mutex here so the client can call back into the service from its
2308 // destructor (can be at the end of the call)
2309 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002310
2311 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002312 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002313 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002314
Cliff Wud3a05312021-04-26 23:07:31 +08002315 {
2316 Mutex::Autolock lock(mInjectionParametersLock);
2317 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2318 mInjectionInitPending = false;
2319 status_t res = NO_ERROR;
2320 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2321 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002322 sp<BasicClient> clientSp = clientDescriptor->getValue();
2323 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2324 if(res != OK) {
2325 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2326 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002327 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002328 }
2329 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002330 if (res != OK) {
2331 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2332 }
2333 } else {
2334 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002335 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002336 res = NO_INIT;
2337 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2338 }
2339 }
2340 }
2341
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002342 return ret;
2343}
2344
Austin Borgered99f642023-06-01 16:51:35 -07002345status_t CameraService::addOfflineClient(const std::string &cameraId,
2346 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002347 if (offlineClient.get() == nullptr) {
2348 return BAD_VALUE;
2349 }
2350
2351 {
2352 // Acquire mServiceLock and prevent other clients from connecting
2353 std::unique_ptr<AutoConditionLock> lock =
2354 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2355
2356 if (lock == nullptr) {
2357 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2358 , __FUNCTION__, offlineClient->getClientPid());
2359 return TIMED_OUT;
2360 }
2361
2362 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2363 if (onlineClientDesc.get() == nullptr) {
2364 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2365 cameraId.c_str());
2366 return BAD_VALUE;
2367 }
2368
2369 // Offline clients do not evict or conflict with other online devices. Resource sharing
2370 // conflicts are handled by the camera provider which will either succeed or fail before
2371 // reaching this method.
2372 const auto& onlinePriority = onlineClientDesc->getPriority();
2373 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2374 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002375 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002376 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002377 // native clients don't have offline processing support.
2378 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002379 if (offlineClientDesc == nullptr) {
2380 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2381 return BAD_VALUE;
2382 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002383
2384 // Allow only one offline device per camera
2385 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2386 if (!incompatibleClients.empty()) {
2387 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2388 return BAD_VALUE;
2389 }
2390
Austin Borgered99f642023-06-01 16:51:35 -07002391 std::string monitorTags = isClientWatched(offlineClient.get())
2392 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002393 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002394 if (err != OK) {
2395 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2396 return err;
2397 }
2398
2399 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2400 if (evicted.size() > 0) {
2401 for (auto& i : evicted) {
2402 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002403 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002404 }
2405
2406 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2407 "properly", __FUNCTION__);
2408
2409 return BAD_VALUE;
2410 }
2411
2412 logConnectedOffline(offlineClientDesc->getKey(),
2413 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002414 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002415
2416 sp<IBinder> remoteCallback = offlineClient->getRemote();
2417 if (remoteCallback != nullptr) {
2418 remoteCallback->linkToDeath(this);
2419 }
2420 } // lock is destroyed, allow further connect calls
2421
2422 return OK;
2423}
2424
Austin Borgered99f642023-06-01 16:51:35 -07002425Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002426 int32_t torchStrength,
Rucha Katakwar38284522021-11-10 11:25:21 -08002427 const sp<IBinder>& clientBinder) {
2428 Mutex::Autolock lock(mServiceLock);
2429
2430 ATRACE_CALL();
2431 if (clientBinder == nullptr) {
2432 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2433 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2434 "Torch client binder in null.");
2435 }
2436
Austin Borgered99f642023-06-01 16:51:35 -07002437 const std::string cameraId = resolveCameraId(unresolvedCameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002438 int uid = CameraThreadState::getCallingUid();
2439
Austin Borgered99f642023-06-01 16:51:35 -07002440 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002441 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002442 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002443 }
2444
2445 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002446 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002447 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002448 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002449 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002450 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002451 }
2452
2453 StatusInternal cameraStatus = state->getStatus();
2454 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2455 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002456 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002457 (int)cameraStatus);
2458 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002459 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002460 }
2461
2462 {
2463 Mutex::Autolock al(mTorchStatusMutex);
2464 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002465 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002466 if (err != OK) {
2467 if (err == NAME_NOT_FOUND) {
2468 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002469 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002470 }
2471 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002472 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002473 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2474 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002475 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002476 }
2477
2478 if (status == TorchModeStatus::NOT_AVAILABLE) {
2479 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2480 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002481 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002482 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2483 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002484 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002485 } else {
2486 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002487 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002488 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2489 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002490 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002491 }
2492 }
2493 }
2494
2495 {
2496 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002497 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002498 }
2499 // Check if the current torch strength level is same as the new one.
2500 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002501 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002502
Austin Borgered99f642023-06-01 16:51:35 -07002503 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002504
2505 if (err != OK) {
2506 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002507 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002508 switch (err) {
2509 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002510 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2511 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002512 errorCode = ERROR_ILLEGAL_ARGUMENT;
2513 break;
2514 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002515 msg = fmt::sprintf("Camera \"%s\" is in use",
2516 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002517 errorCode = ERROR_CAMERA_IN_USE;
2518 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002519 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002520 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002521 "valid range.", torchStrength);
2522 errorCode = ERROR_ILLEGAL_ARGUMENT;
2523 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002524 default:
Austin Borgered99f642023-06-01 16:51:35 -07002525 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002526 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002527 }
Austin Borgered99f642023-06-01 16:51:35 -07002528 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2529 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002530 }
2531
2532 {
2533 // update the link to client's death
2534 // Store the last client that turns on each camera's torch mode.
2535 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002536 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002537 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002538 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002539 } else {
2540 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2541 mTorchClientMap.replaceValueAt(index, clientBinder);
2542 }
2543 clientBinder->linkToDeath(this);
2544 }
2545
2546 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002547 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002548 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002549 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002550 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002551 }
2552 return Status::ok();
2553}
2554
Austin Borgered99f642023-06-01 16:51:35 -07002555Status CameraService::setTorchMode(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002556 bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002557 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002558 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002559
2560 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002561 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002562 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002563 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2564 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002565 }
2566
Austin Borgered99f642023-06-01 16:51:35 -07002567 const std::string cameraId = resolveCameraId(unresolvedCameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07002568 int uid = CameraThreadState::getCallingUid();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002569
Austin Borgered99f642023-06-01 16:51:35 -07002570 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002571 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002572 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002573 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002574 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002575 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002576 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002577 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002578 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002579 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002580 }
2581
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002582 StatusInternal cameraStatus = state->getStatus();
2583 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002584 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002585 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2586 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002587 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002588 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002589 }
2590
2591 {
2592 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002593 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002594 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002595 if (err != OK) {
2596 if (err == NAME_NOT_FOUND) {
2597 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002598 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002599 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002600 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002601 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002602 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002603 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002604 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002605 }
2606
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002607 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002608 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002609 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002610 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002611 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2612 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002613 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002614 } else {
2615 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002616 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002617 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2618 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002619 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002620 }
2621 }
2622 }
2623
Ruben Brunk99e69712015-05-26 17:25:07 -07002624 {
2625 // Update UID map - this is used in the torch status changed callbacks, so must be done
2626 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002627 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002628 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002629 }
2630
Austin Borgered99f642023-06-01 16:51:35 -07002631 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002632
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002633 if (err != OK) {
2634 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002635 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002636 switch (err) {
2637 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002638 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2639 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002640 errorCode = ERROR_ILLEGAL_ARGUMENT;
2641 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002642 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002643 msg = fmt::sprintf("Camera \"%s\" is in use",
2644 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002645 errorCode = ERROR_CAMERA_IN_USE;
2646 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002647 default:
Austin Borgered99f642023-06-01 16:51:35 -07002648 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002649 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002650 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002651 errorCode = ERROR_INVALID_OPERATION;
2652 }
Austin Borgered99f642023-06-01 16:51:35 -07002653 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2654 logServiceError(msg, errorCode);
2655 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002656 }
2657
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002658 {
2659 // update the link to client's death
2660 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002661 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002662 if (enabled) {
2663 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002664 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002665 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002666 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002667 mTorchClientMap.replaceValueAt(index, clientBinder);
2668 }
2669 clientBinder->linkToDeath(this);
2670 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002671 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002672 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002673 }
2674
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002675 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07002676 std::string torchState = enabled ? "on" : "off";
2677 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
2678 torchState.c_str(), clientPid);
2679 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002680 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002681}
2682
Austin Borgered99f642023-06-01 16:51:35 -07002683void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
2684 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
2685 mTorchUidMap[cameraId].first = uid;
2686 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002687 } else {
2688 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07002689 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002690 }
2691}
2692
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002693Status CameraService::notifySystemEvent(int32_t eventId,
2694 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002695 const int pid = CameraThreadState::getCallingPid();
2696 const int selfPid = getpid();
2697
2698 // Permission checks
2699 if (pid != selfPid) {
2700 // Ensure we're being called by system_server, or similar process with
2701 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002702 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002703 const int uid = CameraThreadState::getCallingUid();
2704 ALOGE("Permission Denial: cannot send updates to camera service about system"
2705 " events from pid=%d, uid=%d", pid, uid);
2706 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002707 "No permission to send updates to camera service about system events"
2708 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002709 }
2710 }
2711
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002712 ATRACE_CALL();
2713
Ruben Brunk36597b22015-03-20 22:15:57 -07002714 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002715 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002716 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002717 // from a system server crash
2718 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002719 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002720 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002721 break;
2722 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002723 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2724 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00002725 if (args.size() != 1) {
2726 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
2727 "USB Device Event requires 1 argument");
2728 }
2729
Valentin Iftime29e2e152021-08-13 15:17:33 +02002730 // Notify CameraProviderManager for lazy HALs
2731 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2732 std::to_string(args[0]));
2733 break;
2734 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002735 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002736 default: {
2737 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2738 eventId);
2739 break;
2740 }
2741 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002742 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002743}
2744
Emilian Peev53722fa2019-02-22 17:47:20 -08002745void CameraService::notifyMonitoredUids() {
2746 Mutex::Autolock lock(mStatusListenerLock);
2747
2748 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002749 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002750 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2751 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002752 }
2753}
2754
Austin Borgerdddb7552023-03-30 17:53:01 -07002755void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
2756 Mutex::Autolock lock(mStatusListenerLock);
2757
2758 for (const auto& it : mListenerList) {
2759 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
2760 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
2761 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
2762 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2763 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
2764 }
2765 }
2766}
2767
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002768Status CameraService::notifyDeviceStateChange(int64_t newState) {
2769 const int pid = CameraThreadState::getCallingPid();
2770 const int selfPid = getpid();
2771
2772 // Permission checks
2773 if (pid != selfPid) {
2774 // Ensure we're being called by system_server, or similar process with
2775 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002776 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002777 const int uid = CameraThreadState::getCallingUid();
2778 ALOGE("Permission Denial: cannot send updates to camera service about device"
2779 " state changes from pid=%d, uid=%d", pid, uid);
2780 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2781 "No permission to send updates to camera service about device state"
2782 " changes from pid=%d, uid=%d", pid, uid);
2783 }
2784 }
2785
2786 ATRACE_CALL();
2787
Austin Borger18b30a72022-10-27 12:20:29 -07002788 {
2789 Mutex::Autolock lock(mServiceLock);
2790 mDeviceState = newState;
2791 }
2792
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002793 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002794
2795 return Status::ok();
2796}
2797
Emilian Peev8b64f282021-03-25 16:49:57 -07002798Status CameraService::notifyDisplayConfigurationChange() {
2799 ATRACE_CALL();
2800 const int callingPid = CameraThreadState::getCallingPid();
2801 const int selfPid = getpid();
2802
2803 // Permission checks
2804 if (callingPid != selfPid) {
2805 // Ensure we're being called by system_server, or similar process with
2806 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002807 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07002808 const int uid = CameraThreadState::getCallingUid();
2809 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2810 " changes from pid=%d, uid=%d", callingPid, uid);
2811 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2812 "No permission to send updates to camera service about orientation"
2813 " changes from pid=%d, uid=%d", callingPid, uid);
2814 }
2815 }
2816
2817 Mutex::Autolock lock(mServiceLock);
2818
2819 // Don't do anything if rotate-and-crop override via cmd is active
2820 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2821
2822 const auto clients = mActiveClientManager.getAll();
2823 for (auto& current : clients) {
2824 if (current != nullptr) {
2825 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002826 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2827 basicClient->setRotateAndCropOverride(
2828 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2829 basicClient->getPackageName(),
2830 basicClient->getCameraFacing(),
2831 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002832 }
2833 }
2834 }
2835
2836 return Status::ok();
2837}
2838
2839Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002840 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2841 ATRACE_CALL();
2842 if (!concurrentCameraIds) {
2843 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2844 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2845 }
2846
2847 if (!mInitialized) {
2848 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07002849 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002850 return STATUS_ERROR(ERROR_DISCONNECTED,
2851 "Camera subsystem is not available");
2852 }
2853 // First call into the provider and get the set of concurrent camera
2854 // combinations
2855 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002856 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002857 for (auto &combination : concurrentCameraCombinations) {
2858 std::vector<std::string> validCombination;
2859 for (auto &cameraId : combination) {
2860 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07002861 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002862 if (state == nullptr) {
2863 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2864 continue;
2865 }
2866 StatusInternal status = state->getStatus();
2867 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2868 continue;
2869 }
Austin Borgered99f642023-06-01 16:51:35 -07002870 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002871 continue;
2872 }
2873 validCombination.push_back(cameraId);
2874 }
2875 if (validCombination.size() != 0) {
2876 concurrentCameraIds->push_back(std::move(validCombination));
2877 }
2878 }
2879 return Status::ok();
2880}
2881
2882Status CameraService::isConcurrentSessionConfigurationSupported(
2883 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002884 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002885 if (!isSupported) {
2886 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2887 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2888 }
2889
2890 if (!mInitialized) {
2891 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2892 return STATUS_ERROR(ERROR_DISCONNECTED,
2893 "Camera subsystem is not available");
2894 }
2895
2896 // Check for camera permissions
2897 int callingPid = CameraThreadState::getCallingPid();
2898 int callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002899 permission::PermissionChecker permissionChecker;
2900 AttributionSourceState attributionSource{};
2901 attributionSource.pid = callingPid;
2902 attributionSource.uid = callingUid;
2903 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07002904 toString16(sCameraPermission), attributionSource, String16(),
2905 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +00002906 if ((callingPid != getpid()) && !checkPermissionForCamera) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002907 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2908 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2909 "android.permission.CAMERA needed to call"
2910 "isConcurrentSessionConfigurationSupported");
2911 }
2912
2913 status_t res =
2914 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002915 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2916 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002917 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07002918 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07002919 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002920 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2921 "support %s (%d)", strerror(-res), res);
2922 }
2923 return Status::ok();
2924}
2925
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002926Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2927 /*out*/
2928 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002929 return addListenerHelper(listener, cameraStatuses);
2930}
2931
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002932binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2933 std::vector<hardware::CameraStatus>* cameraStatuses) {
2934 return addListenerHelper(listener, cameraStatuses, false, true);
2935}
2936
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002937Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2938 /*out*/
2939 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002940 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002941
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002942 ATRACE_CALL();
2943
Igor Murashkinbfc99152013-02-27 12:55:20 -08002944 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002945
Ruben Brunk3450ba72015-06-16 11:00:37 -07002946 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002947 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002948 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002949 }
2950
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002951 auto clientUid = CameraThreadState::getCallingUid();
2952 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002953 permission::PermissionChecker permissionChecker;
2954 AttributionSourceState attributionSource{};
2955 attributionSource.uid = clientUid;
2956 attributionSource.pid = clientPid;
2957 bool openCloseCallbackAllowed = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07002958 toString16(sCameraOpenCloseListenerPermission), attributionSource, String16(),
Joanne Chung02c13d02023-01-16 12:58:05 +00002959 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002960
Igor Murashkinbfc99152013-02-27 12:55:20 -08002961 Mutex::Autolock lock(mServiceLock);
2962
Ruben Brunkcc776712015-02-17 20:18:47 -08002963 {
2964 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002965 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002966 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002967 ALOGW("%s: Tried to add listener %p which was already subscribed",
2968 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002969 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002970 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002971 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002972
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002973 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002974 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
2975 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002976 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08002977 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07002978 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08002979 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07002980 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
2981 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2982 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08002983 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002984 // The listener still needs to be added to the list of listeners, regardless of what
2985 // permissions the listener process has / whether it is a vendor listener. Since it might be
2986 // eligible to listen to other camera ids.
2987 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07002988 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08002989 }
2990
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002991 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07002992 {
Ruben Brunkcc776712015-02-17 20:18:47 -08002993 Mutex::Autolock lock(mCameraStatesLock);
2994 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08002995 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07002996 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07002997 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07002998 }
2999 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003000 // Remove the camera statuses that should be hidden from the client, we do
3001 // this after collecting the states in order to avoid holding
3002 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3003 // the same time.
3004 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3005 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3006 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3007 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3008 ALOGE("%s: Invalid camera id %s, skipping status update",
3009 __FUNCTION__, s.cameraId.c_str());
3010 return true;
3011 }
3012 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3013 clientUid);}), cameraStatuses->end());
3014
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003015 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003016 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003017 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003018 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003019 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003020
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003021 /*
3022 * Immediately signal current torch status to this listener only
3023 * This may be a subset of all the devices, so don't include it in the response directly
3024 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003025 {
3026 Mutex::Autolock al(mTorchStatusMutex);
3027 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003028 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003029 // The camera id is visible to the client. Fine to send torch
3030 // callback.
3031 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3032 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3033 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003034 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003035 }
3036
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003037 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003038}
Ruben Brunkcc776712015-02-17 20:18:47 -08003039
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003040Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003041 ATRACE_CALL();
3042
Igor Murashkinbfc99152013-02-27 12:55:20 -08003043 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3044
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003045 if (listener == 0) {
3046 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003047 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003048 }
3049
Igor Murashkinbfc99152013-02-27 12:55:20 -08003050 Mutex::Autolock lock(mServiceLock);
3051
Ruben Brunkcc776712015-02-17 20:18:47 -08003052 {
3053 Mutex::Autolock lock(mStatusListenerLock);
3054 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003055 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003056 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003057 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003058 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003059 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003060 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003061 }
3062 }
3063
3064 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3065 __FUNCTION__, listener.get());
3066
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003067 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003068}
3069
Austin Borgered99f642023-06-01 16:51:35 -07003070Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003071
3072 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003073 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3074
3075 if (parameters == NULL) {
3076 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003077 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003078 }
3079
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003081
3082 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003083 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003084 // Error logged by caller
3085 return ret;
3086 }
3087
3088 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003089
Austin Borgered99f642023-06-01 16:51:35 -07003090 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003091
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003092 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003093}
3094
Austin Borgered99f642023-06-01 16:51:35 -07003095Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003096 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003097 ATRACE_CALL();
3098
Austin Borgered99f642023-06-01 16:51:35 -07003099 std::string resolvedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00003100 if (apiVersion == API_VERSION_2) {
Austin Borgered99f642023-06-01 16:51:35 -07003101 resolvedCameraId = resolveCameraId(unresolvedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00003102 } else { // if (apiVersion == API_VERSION_1)
3103 // We don't support remapping for API 1.
3104 // TODO(b/286287541): Also support remapping for API 1.
Austin Borgered99f642023-06-01 16:51:35 -07003105 resolvedCameraId = unresolvedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00003106 }
Austin Borgered99f642023-06-01 16:51:35 -07003107 const std::string cameraId = resolvedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00003108
Austin Borgered99f642023-06-01 16:51:35 -07003109 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003110
3111 switch (apiVersion) {
3112 case API_VERSION_1:
3113 case API_VERSION_2:
3114 break;
3115 default:
Austin Borgered99f642023-06-01 16:51:35 -07003116 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3117 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3118 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003119 }
3120
Austin Borger18b30a72022-10-27 12:20:29 -07003121 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003122 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003123 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003124 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3125 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3126 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003127 }
3128 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3129 int deviceVersion = deviceVersionAndTransport.first;
3130 switch (deviceVersion) {
3131 case CAMERA_DEVICE_API_VERSION_1_0:
3132 case CAMERA_DEVICE_API_VERSION_3_0:
3133 case CAMERA_DEVICE_API_VERSION_3_1:
3134 if (apiVersion == API_VERSION_2) {
3135 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003136 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003137 *isSupported = false;
3138 } else { // if (apiVersion == API_VERSION_1) {
3139 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003140 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003141 *isSupported = true;
3142 }
3143 break;
3144 case CAMERA_DEVICE_API_VERSION_3_2:
3145 case CAMERA_DEVICE_API_VERSION_3_3:
3146 case CAMERA_DEVICE_API_VERSION_3_4:
3147 case CAMERA_DEVICE_API_VERSION_3_5:
3148 case CAMERA_DEVICE_API_VERSION_3_6:
3149 case CAMERA_DEVICE_API_VERSION_3_7:
3150 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003151 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003152 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003153 break;
3154 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003155 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3156 deviceVersion, cameraId.c_str());
3157 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3158 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003159 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003160 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003161 } else {
3162 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003163 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003164 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003165}
3166
Austin Borgered99f642023-06-01 16:51:35 -07003167Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003168 /*out*/ bool *isSupported) {
3169 ATRACE_CALL();
3170
Austin Borgered99f642023-06-01 16:51:35 -07003171 const std::string cameraId = resolveCameraId(unresolvedCameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003172
Austin Borgered99f642023-06-01 16:51:35 -07003173 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3174 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003175
3176 return Status::ok();
3177}
3178
Cliff Wud8cae102021-03-11 01:37:42 +08003179Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003180 const std::string& packageName, const std::string& internalCamId,
3181 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003182 const sp<ICameraInjectionCallback>& callback,
3183 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003184 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003185 ATRACE_CALL();
3186
Austin Borgered99f642023-06-01 16:51:35 -07003187 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003188 const int pid = CameraThreadState::getCallingPid();
3189 const int uid = CameraThreadState::getCallingUid();
3190 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3191 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3192 "Permission Denial: no permission to inject camera");
3193 }
3194
3195 ALOGV(
3196 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3197 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003198 __FUNCTION__, packageName.c_str(),
3199 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003200
Cliff Wud3a05312021-04-26 23:07:31 +08003201 {
3202 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003203 mInjectionInternalCamId = internalCamId;
3204 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003205 mInjectionStatusListener->addListener(callback);
3206 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003207 status_t res = NO_ERROR;
3208 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3209 // If the client already exists, we can directly connect to the camera device through the
3210 // client's injectCamera(), otherwise we need to wait until the client is established
3211 // (execute connectHelper()) before injecting the camera to the camera device.
3212 if (clientDescriptor != nullptr) {
3213 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003214 sp<BasicClient> clientSp = clientDescriptor->getValue();
3215 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3216 if(res != OK) {
3217 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3218 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003219 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003220 }
3221 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003222 if(res != OK) {
3223 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3224 }
3225 } else {
3226 mInjectionInitPending = true;
3227 }
3228 }
Cliff Wud8cae102021-03-11 01:37:42 +08003229
Cliff Wud3a05312021-04-26 23:07:31 +08003230 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003231}
3232
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003233Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003234 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003235 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3236 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3237 return Status::ok();
3238}
3239
Ruben Brunkcc776712015-02-17 20:18:47 -08003240void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003241 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003242 for (auto& i : mActiveClientManager.getAll()) {
3243 auto clientSp = i->getValue();
3244 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003245 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003246 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003247 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003248 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003249 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003250}
3251
Ruben Brunkcc776712015-02-17 20:18:47 -08003252bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003253 bool ret = false;
3254 {
3255 // Acquire mServiceLock and prevent other clients from connecting
3256 std::unique_ptr<AutoConditionLock> lock =
3257 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003258
Igor Murashkin634a5152013-02-20 17:15:11 -08003259
Ruben Brunkcc776712015-02-17 20:18:47 -08003260 std::vector<sp<BasicClient>> evicted;
3261 for (auto& i : mActiveClientManager.getAll()) {
3262 auto clientSp = i->getValue();
3263 if (clientSp.get() == nullptr) {
3264 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3265 mActiveClientManager.remove(i);
3266 continue;
3267 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003268 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003269 mActiveClientManager.remove(i);
3270 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003271
Ruben Brunkcc776712015-02-17 20:18:47 -08003272 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003273 clientSp->notifyError(
3274 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003275 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003276 }
3277 }
3278
Ruben Brunkcc776712015-02-17 20:18:47 -08003279 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3280 // other clients from connecting in mServiceLockWrapper if held
3281 mServiceLock.unlock();
3282
Ruben Brunk36597b22015-03-20 22:15:57 -07003283 // Do not clear caller identity, remote caller should be client proccess
3284
Ruben Brunkcc776712015-02-17 20:18:47 -08003285 for (auto& i : evicted) {
3286 if (i.get() != nullptr) {
3287 i->disconnect();
3288 ret = true;
3289 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003290 }
3291
Ruben Brunkcc776712015-02-17 20:18:47 -08003292 // Reacquire mServiceLock
3293 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003294
Ruben Brunkcc776712015-02-17 20:18:47 -08003295 } // lock is destroyed, allow further connect calls
3296
3297 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003298}
3299
Ruben Brunkcc776712015-02-17 20:18:47 -08003300std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003301 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003302 std::shared_ptr<CameraState> state;
3303 {
3304 Mutex::Autolock lock(mCameraStatesLock);
3305 auto iter = mCameraStates.find(cameraId);
3306 if (iter != mCameraStates.end()) {
3307 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003308 }
3309 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003310 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003311}
3312
Austin Borgered99f642023-06-01 16:51:35 -07003313sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003314 // Remove from active clients list
3315 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3316 if (clientDescriptorPtr == nullptr) {
3317 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003318 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003319 return sp<BasicClient>{nullptr};
3320 }
3321
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003322 sp<BasicClient> client = clientDescriptorPtr->getValue();
3323 if (client.get() != nullptr) {
3324 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3325 }
3326 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003327}
3328
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003329void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003330 // Acquire mServiceLock and prevent other clients from connecting
3331 std::unique_ptr<AutoConditionLock> lock =
3332 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3333
Ruben Brunk6267b532015-04-30 17:44:07 -07003334 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003335 for (size_t i = 0; i < newUserIds.size(); i++) {
3336 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003337 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003338 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003339 return;
3340 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003341 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003342 }
3343
Ruben Brunka8ca9152015-04-07 14:23:40 -07003344
Ruben Brunk6267b532015-04-30 17:44:07 -07003345 if (newAllowedUsers == mAllowedUsers) {
3346 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3347 return;
3348 }
3349
3350 logUserSwitch(mAllowedUsers, newAllowedUsers);
3351
3352 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003353
3354 // Current user has switched, evict all current clients.
3355 std::vector<sp<BasicClient>> evicted;
3356 for (auto& i : mActiveClientManager.getAll()) {
3357 auto clientSp = i->getValue();
3358
3359 if (clientSp.get() == nullptr) {
3360 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3361 continue;
3362 }
3363
Ruben Brunk6267b532015-04-30 17:44:07 -07003364 // Don't evict clients that are still allowed.
3365 uid_t clientUid = clientSp->getClientUid();
3366 userid_t clientUserId = multiuser_get_user_id(clientUid);
3367 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3368 continue;
3369 }
3370
Ruben Brunk36597b22015-03-20 22:15:57 -07003371 evicted.push_back(clientSp);
3372
Ruben Brunk36597b22015-03-20 22:15:57 -07003373 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003374 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003375
Ruben Brunk36597b22015-03-20 22:15:57 -07003376 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003377 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003378 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003379 " to user switch.", i->getKey().c_str(),
3380 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003381 i->getOwnerId(), i->getPriority().getScore(),
3382 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003383
3384 }
3385
3386 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3387 // blocking other clients from connecting in mServiceLockWrapper if held.
3388 mServiceLock.unlock();
3389
3390 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003391 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003392
3393 for (auto& i : evicted) {
3394 i->disconnect();
3395 }
3396
Jayant Chowdhary12361932018-08-27 14:46:13 -07003397 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003398
3399 // Reacquire mServiceLock
3400 mServiceLock.lock();
3401}
Ruben Brunkcc776712015-02-17 20:18:47 -08003402
Austin Borgered99f642023-06-01 16:51:35 -07003403void CameraService::logEvent(const std::string &event) {
3404 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003405 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003406 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003407 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003408 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003409 mEventLog.add(msg);
3410 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3411 // Error event not added to the dumpsys log before
3412 mEventLog.add(msg);
3413 sServiceErrorEventSet.insert(msg);
3414 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003415}
3416
Austin Borgered99f642023-06-01 16:51:35 -07003417void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3418 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003419 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003420 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3421 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003422}
3423
Austin Borgered99f642023-06-01 16:51:35 -07003424void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3425 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003426 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003427 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3428 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003429}
3430
Austin Borgered99f642023-06-01 16:51:35 -07003431void CameraService::logConnected(const std::string &cameraId, int clientPid,
3432 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003433 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003434 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3435 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003436}
3437
Austin Borgered99f642023-06-01 16:51:35 -07003438void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3439 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003440 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003441 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3442 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003443}
3444
Austin Borgered99f642023-06-01 16:51:35 -07003445void CameraService::logRejected(const std::string &cameraId, int clientPid,
3446 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003447 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003448 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3449 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003450}
3451
Austin Borgered99f642023-06-01 16:51:35 -07003452void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3453 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003454 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003455 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3456 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003457}
3458
Ruben Brunk6267b532015-04-30 17:44:07 -07003459void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3460 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003461 std::string newUsers = toString(newUserIds);
3462 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003463 if (oldUsers.size() == 0) {
3464 oldUsers = "<None>";
3465 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003466 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003467 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3468 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003469}
3470
Austin Borgered99f642023-06-01 16:51:35 -07003471void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003472 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003473 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003474}
3475
Austin Borgered99f642023-06-01 16:51:35 -07003476void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003477 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003478 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003479}
3480
Austin Borgered99f642023-06-01 16:51:35 -07003481void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003482 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003483 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003484}
3485
Austin Borgered99f642023-06-01 16:51:35 -07003486void CameraService::logServiceError(const std::string &msg, int errorCode) {
3487 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3488 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003489}
3490
Ruben Brunk36597b22015-03-20 22:15:57 -07003491status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3492 uint32_t flags) {
3493
Mathias Agopian65ab4712010-07-14 17:59:35 -07003494 // Permission checks
3495 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003496 case SHELL_COMMAND_TRANSACTION: {
3497 int in = data.readFileDescriptor();
3498 int out = data.readFileDescriptor();
3499 int err = data.readFileDescriptor();
3500 int argc = data.readInt32();
3501 Vector<String16> args;
3502 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3503 args.add(data.readString16());
3504 }
3505 sp<IBinder> unusedCallback;
3506 sp<IResultReceiver> resultReceiver;
3507 status_t status;
3508 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3509 return status;
3510 }
3511 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3512 return status;
3513 }
3514 status = shellCommand(in, out, err, args);
3515 if (resultReceiver != nullptr) {
3516 resultReceiver->send(status);
3517 }
3518 return NO_ERROR;
3519 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003520 }
3521
3522 return BnCameraService::onTransact(code, data, reply, flags);
3523}
3524
Mathias Agopian65ab4712010-07-14 17:59:35 -07003525// We share the media players for shutter and recording sound for all clients.
3526// A reference count is kept to determine when we will actually release the
3527// media players.
3528
Jaekyun Seokef498052018-03-23 13:09:44 +09003529sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3530 sp<MediaPlayer> mp = new MediaPlayer();
3531 status_t error;
3532 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003533 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003534 error = mp->prepare();
3535 }
3536 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003537 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003538 mp->disconnect();
3539 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003540 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003541 }
3542 return mp;
3543}
3544
username5755fea2018-12-27 09:48:08 +08003545void CameraService::increaseSoundRef() {
3546 Mutex::Autolock lock(mSoundLock);
3547 mSoundRef++;
3548}
3549
3550void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003551 ATRACE_CALL();
3552
username5755fea2018-12-27 09:48:08 +08003553 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3554 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3555 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3556 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3557 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3558 }
3559 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3560 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3561 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3562 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003563 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003564 }
3565 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3566 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3567 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3568 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3569 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003570 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003571}
3572
username5755fea2018-12-27 09:48:08 +08003573void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003574 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003575 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003576 if (--mSoundRef) return;
3577
3578 for (int i = 0; i < NUM_SOUNDS; i++) {
3579 if (mSoundPlayer[i] != 0) {
3580 mSoundPlayer[i]->disconnect();
3581 mSoundPlayer[i].clear();
3582 }
3583 }
3584}
3585
3586void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003587 ATRACE_CALL();
3588
Mathias Agopian65ab4712010-07-14 17:59:35 -07003589 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003590 if (kind < 0 || kind >= NUM_SOUNDS) {
3591 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3592 return;
3593 }
3594
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003596 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003597 sp<MediaPlayer> player = mSoundPlayer[kind];
3598 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003599 player->seekTo(0);
3600 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003601 }
3602}
3603
3604// ----------------------------------------------------------------------------
3605
3606CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003607 const sp<ICameraClient>& cameraClient,
Austin Borgered99f642023-06-01 16:51:35 -07003608 const std::string& clientPackageName, bool systemNativeClient,
3609 const std::optional<std::string>& clientFeatureId,
3610 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003611 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003612 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003613 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003614 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003615 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003616 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003617 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003618 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003619 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003620 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003621{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003622 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003623 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003624
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003625 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626
username5755fea2018-12-27 09:48:08 +08003627 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003628
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003629 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003630}
3631
Mathias Agopian65ab4712010-07-14 17:59:35 -07003632// tear down the client
3633CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003634 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003635 mDestructionStarted = true;
3636
username5755fea2018-12-27 09:48:08 +08003637 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003638 // unconditionally disconnect. function is idempotent
3639 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003640}
3641
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003642sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3643
Igor Murashkin634a5152013-02-20 17:15:11 -08003644CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003645 const sp<IBinder>& remoteCallback,
Austin Borgered99f642023-06-01 16:51:35 -07003646 const std::string& clientPackageName, bool nativeClient,
3647 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003648 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003649 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003650 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003651 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003652 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3653 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003654 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003655 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003656 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003657 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003658 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003659 mRemoteBinder(remoteCallback),
3660 mOpsActive(false),
3661 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003662{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003663 if (sCameraService == nullptr) {
3664 sCameraService = cameraService;
3665 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003666
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003667 // There are 2 scenarios in which a client won't have AppOps operations
3668 // (both scenarios : native clients)
3669 // 1) It's an system native client*, the package name will be empty
3670 // and it will return from this function in the previous if condition
3671 // (This is the same as the previously existing behavior).
3672 // 2) It is a system native client, but its package name has been
3673 // modified for debugging, however it still must not use AppOps since
3674 // the package name is not a real one.
3675 //
3676 // * system native client - native client with UID < AID_APP_START. It
3677 // doesn't exclude clients not on the system partition.
3678 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003679 mAppOpsManager = std::make_unique<AppOpsManager>();
3680 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003681
3682 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003683}
3684
3685CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003686 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003687 mDestructionStarted = true;
3688}
3689
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003690binder::Status CameraService::BasicClient::disconnect() {
3691 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003692 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003693 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003694 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003695 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003696
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003697 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07003698 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003699 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003700 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08003701
3702 sp<IBinder> remote = getRemote();
3703 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003704 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003705 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003706
3707 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003708 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003709 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07003710 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003711 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003712
Igor Murashkincba2c162013-03-20 15:56:31 -07003713 // client shouldn't be able to call into us anymore
3714 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003715
Kunal Malhotrabfc96052023-02-28 23:25:34 +00003716 const auto& mActivityManager = getActivityManager();
3717 if (mActivityManager) {
3718 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
3719 CameraThreadState::getCallingUid(),
3720 CameraThreadState::getCallingPid());
3721 }
3722
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003723 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003724}
3725
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003726status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3727 // No dumping of clients directly over Binder,
3728 // must go through CameraService::dump
3729 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003730 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003731 return OK;
3732}
3733
Austin Borgered99f642023-06-01 16:51:35 -07003734status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003735 // Can't watch tags directly, must go through CameraService::startWatchingTags
3736 return OK;
3737}
3738
3739status_t CameraService::BasicClient::stopWatchingTags(int) {
3740 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3741 return OK;
3742}
3743
3744status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3745 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3746 return OK;
3747}
3748
Austin Borgered99f642023-06-01 16:51:35 -07003749std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003750 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003751}
3752
Emilian Peev8b64f282021-03-25 16:49:57 -07003753int CameraService::BasicClient::getCameraFacing() const {
3754 return mCameraFacing;
3755}
3756
3757int CameraService::BasicClient::getCameraOrientation() const {
3758 return mOrientation;
3759}
Ruben Brunkcc776712015-02-17 20:18:47 -08003760
3761int CameraService::BasicClient::getClientPid() const {
3762 return mClientPid;
3763}
3764
Ruben Brunk6267b532015-04-30 17:44:07 -07003765uid_t CameraService::BasicClient::getClientUid() const {
3766 return mClientUid;
3767}
3768
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003769bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3770 // Defaults to API2.
3771 return level == API_2;
3772}
3773
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003774status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003775 {
3776 Mutex::Autolock l(mAudioRestrictionLock);
3777 mAudioRestriction = mode;
3778 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003779 sCameraService->updateAudioRestriction();
3780 return OK;
3781}
3782
3783int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003784 return sCameraService->updateAudioRestriction();
3785}
3786
3787int32_t CameraService::BasicClient::getAudioRestriction() const {
3788 Mutex::Autolock l(mAudioRestrictionLock);
3789 return mAudioRestriction;
3790}
3791
3792bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3793 switch (mode) {
3794 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3795 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3796 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3797 return true;
3798 default:
3799 return false;
3800 }
3801}
3802
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003803status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3804 if (mode == AppOpsManager::MODE_ERRORED) {
3805 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07003806 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003807 return PERMISSION_DENIED;
3808 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3809 // If the calling Uid is trusted (a native service), the AppOpsManager could
3810 // return MODE_IGNORED. Do not treat such case as error.
3811 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3812 mClientPackageName);
3813 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003814 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003815 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3816 // We prefer to successfully open the camera and perform camera muting
3817 // or blocking in connectHelper as handleAppOpMode can be called before the
3818 // connection has been fully established and at that time camera muting
3819 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003820 if (!isUidActive || !isCameraPrivacyEnabled) {
3821 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07003822 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003823 // Return the same error as for device policy manager rejection
3824 return -EACCES;
3825 }
3826 }
3827 return OK;
3828}
3829
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003830status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003831 ATRACE_CALL();
3832
Igor Murashkine6800ce2013-03-04 17:25:57 -08003833 {
3834 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003835 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003836 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003837 if (mAppOpsManager != nullptr) {
3838 // Notify app ops that the camera is not available
3839 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003840 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003841 toString16(mClientPackageName), mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003842
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003843 // Just check for camera acccess here on open - delay startOp until
3844 // camera frames start streaming in startCameraStreamingOps
3845 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003846 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003847 status_t res = handleAppOpMode(mode);
3848 if (res != OK) {
3849 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003850 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003851 }
3852
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003853 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003854
3855 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003856 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003857
Austin Borgerdddb7552023-03-30 17:53:01 -07003858 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08003859
Shuzhen Wang695044d2020-03-06 09:02:23 -08003860 // Notify listeners of camera open/close status
3861 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3862
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003863 return OK;
3864}
3865
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003866status_t CameraService::BasicClient::startCameraStreamingOps() {
3867 ATRACE_CALL();
3868
3869 if (!mOpsActive) {
3870 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3871 return INVALID_OPERATION;
3872 }
3873 if (mOpsStreaming) {
3874 ALOGV("%s: Streaming already active!", __FUNCTION__);
3875 return OK;
3876 }
3877
3878 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003879 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003880
3881 if (mAppOpsManager != nullptr) {
3882 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003883 toString16(mClientPackageName), /*startIfModeDefault*/ false,
3884 toString16(mClientFeatureId),
3885 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003886 status_t res = handleAppOpMode(mode);
3887 if (res != OK) {
3888 return res;
3889 }
3890 }
3891
3892 mOpsStreaming = true;
3893
3894 return OK;
3895}
3896
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003897status_t CameraService::BasicClient::noteAppOp() {
3898 ATRACE_CALL();
3899
3900 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003901 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003902
3903 // noteAppOp is only used for when camera mute is not supported, in order
3904 // to trigger the sensor privacy "Unblock" dialog
3905 if (mAppOpsManager != nullptr) {
3906 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003907 toString16(mClientPackageName), toString16(mClientFeatureId),
3908 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003909 status_t res = handleAppOpMode(mode);
3910 if (res != OK) {
3911 return res;
3912 }
3913 }
3914
3915 return OK;
3916}
3917
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003918status_t CameraService::BasicClient::finishCameraStreamingOps() {
3919 ATRACE_CALL();
3920
3921 if (!mOpsActive) {
3922 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3923 return INVALID_OPERATION;
3924 }
3925 if (!mOpsStreaming) {
3926 ALOGV("%s: Streaming not active!", __FUNCTION__);
3927 return OK;
3928 }
3929
3930 if (mAppOpsManager != nullptr) {
3931 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003932 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003933 mOpsStreaming = false;
3934 }
3935
3936 return OK;
3937}
3938
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003939status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003940 ATRACE_CALL();
3941
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003942 if (mOpsStreaming) {
3943 // Make sure we've notified everyone about camera stopping
3944 finishCameraStreamingOps();
3945 }
3946
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003947 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003948 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003949 mOpsActive = false;
3950
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003951 // This function is called when a client disconnects. This should
3952 // release the camera, but actually only if it was in a proper
3953 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003954 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003955 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003956
Ruben Brunkcc776712015-02-17 20:18:47 -08003957 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003958 sCameraService->updateStatus(StatusInternal::PRESENT,
3959 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003960 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003961 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003962 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3963 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003964 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003965 mOpsCallback.clear();
3966
Austin Borgerdddb7552023-03-30 17:53:01 -07003967 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08003968
Shuzhen Wang695044d2020-03-06 09:02:23 -08003969 // Notify listeners of camera open/close status
3970 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3971
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003972 return OK;
3973}
3974
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003975void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003976 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003977 if (mAppOpsManager == nullptr) {
3978 return;
3979 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003980 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003981 if (op != AppOpsManager::OP_CAMERA) {
3982 ALOGW("Unexpected app ops notification received: %d", op);
3983 return;
3984 }
3985
3986 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003987 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003988 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003989 ALOGV("checkOp returns: %d, %s ", res,
3990 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
3991 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
3992 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
3993 "UNKNOWN");
3994
Shuzhen Wang64900852021-02-05 09:03:29 -08003995 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07003996 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
3997 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08003998 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08003999 } else if (res == AppOpsManager::MODE_IGNORED) {
4000 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08004001 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004002 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08004003 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
Austin Borgered99f642023-06-01 16:51:35 -07004004 mCameraIdStr.c_str(), mClientPackageName.c_str(),
Shuzhen Wang64900852021-02-05 09:03:29 -08004005 mUidIsTrusted, isUidActive);
4006 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
4007 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
4008 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004009 if (!mUidIsTrusted) {
4010 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4011 setCameraMute(true);
4012 } else if (!isUidActive
4013 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4014 block();
4015 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004016 }
Evan Severson09ab4002021-02-10 14:15:19 -08004017 } else if (res == AppOpsManager::MODE_ALLOWED) {
4018 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004019 }
4020}
4021
Svet Ganova453d0d2018-01-11 15:37:58 -08004022void CameraService::BasicClient::block() {
4023 ATRACE_CALL();
4024
4025 // Reset the client PID to allow server-initiated disconnect,
4026 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004027 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004028 CaptureResultExtras resultExtras; // a dummy result (invalid)
4029 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4030 disconnect();
4031}
4032
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033// ----------------------------------------------------------------------------
4034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004035void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004036 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004037 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004038 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4039 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4040 api1ErrorCode = CAMERA_ERROR_DISABLED;
4041 }
4042 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004043 } else {
4044 ALOGE("mRemoteCallback is NULL!!");
4045 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004046}
4047
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004048// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004049binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004050 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004051 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004052}
4053
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004054bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4055 return level == API_1;
4056}
4057
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004058CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4059 mClient(client) {
4060}
4061
4062void CameraService::Client::OpsCallback::opChanged(int32_t op,
4063 const String16& packageName) {
4064 sp<BasicClient> client = mClient.promote();
4065 if (client != NULL) {
4066 client->opChanged(op, packageName);
4067 }
4068}
4069
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004071// UidPolicy
4072// ----------------------------------------------------------------------------
4073
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004074void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004075 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004076 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004077
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004078 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004079 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004080 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004081 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004082 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4083 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004084 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004085 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004086 if (res == OK) {
4087 mRegistered = true;
4088 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004089 } else {
4090 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004091 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004092}
4093
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004094void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004095 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004096 return;
4097 }
4098
4099 registerWithActivityManager();
4100}
4101
4102void CameraService::UidPolicy::registerSelf() {
4103 // Use check service to see if the activity service is available
4104 // If not available then register for notifications, instead of blocking
4105 // till the service is ready
4106 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004107 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004108 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004109 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004110 } else {
4111 registerWithActivityManager();
4112 }
4113}
4114
Svet Ganova453d0d2018-01-11 15:37:58 -08004115void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004116 Mutex::Autolock _l(mUidLock);
4117
Steven Moreland2f348142019-07-02 15:59:07 -07004118 mAm.unregisterUidObserver(this);
4119 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004120 mRegistered = false;
4121 mActiveUids.clear();
4122 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004123}
4124
4125void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4126 onUidIdle(uid, disabled);
4127}
4128
4129void CameraService::UidPolicy::onUidActive(uid_t uid) {
4130 Mutex::Autolock _l(mUidLock);
4131 mActiveUids.insert(uid);
4132}
4133
4134void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4135 bool deleted = false;
4136 {
4137 Mutex::Autolock _l(mUidLock);
4138 if (mActiveUids.erase(uid) > 0) {
4139 deleted = true;
4140 }
4141 }
4142 if (deleted) {
4143 sp<CameraService> service = mService.promote();
4144 if (service != nullptr) {
4145 service->blockClientsForUid(uid);
4146 }
4147 }
4148}
4149
Emilian Peev53722fa2019-02-22 17:47:20 -08004150void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004151 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004152 bool procStateChange = false;
4153 {
4154 Mutex::Autolock _l(mUidLock);
4155 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4156 mMonitoredUids[uid].procState != procState) {
4157 mMonitoredUids[uid].procState = procState;
4158 procStateChange = true;
4159 }
4160 }
4161
4162 if (procStateChange) {
4163 sp<CameraService> service = mService.promote();
4164 if (service != nullptr) {
4165 service->notifyMonitoredUids();
4166 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004167 }
4168}
4169
Austin Borgerdddb7552023-03-30 17:53:01 -07004170/**
4171 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4172 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4173 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4174 * monitoredUids. If it is revised above some other monitoredUid, signal
4175 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4176 * foreground apps in split screen - state changes will capture all other cases.
4177 */
4178void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4179 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004180 {
4181 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004182 auto it = mMonitoredUids.find(uid);
4183
4184 if (it != mMonitoredUids.end()) {
4185 if (it->second.hasCamera) {
4186 for (auto &monitoredUid : mMonitoredUids) {
4187 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004188 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004189 notifyUidSet.emplace(monitoredUid.first);
4190 }
4191 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004192 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004193 notifyUidSet.emplace(uid);
4194 } else {
4195 for (auto &monitoredUid : mMonitoredUids) {
4196 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004197 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004198 notifyUidSet.emplace(uid);
4199 }
4200 }
4201 }
4202 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004203 }
4204 }
4205
Austin Borgerdddb7552023-03-30 17:53:01 -07004206 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004207 sp<CameraService> service = mService.promote();
4208 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004209 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004210 }
4211 }
4212}
4213
Austin Borgerdddb7552023-03-30 17:53:01 -07004214/**
4215 * Register a uid for monitoring, and note whether it owns a camera.
4216 */
4217void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004218 Mutex::Autolock _l(mUidLock);
4219 auto it = mMonitoredUids.find(uid);
4220 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004221 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004222 } else {
Austin Borger65577682022-02-17 00:25:43 +00004223 MonitoredUid monitoredUid;
4224 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004225 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004226 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004227 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004228 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004229 if (res != OK) {
4230 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4231 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004232 }
4233
4234 if (openCamera) {
4235 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004236 }
4237}
4238
Austin Borgerdddb7552023-03-30 17:53:01 -07004239/**
4240 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4241 */
4242void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004243 Mutex::Autolock _l(mUidLock);
4244 auto it = mMonitoredUids.find(uid);
4245 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004246 it->second.refCount--;
4247 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004248 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004249 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004250 if (res != OK) {
4251 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4252 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004253 } else if (closeCamera) {
4254 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004255 }
4256 } else {
4257 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4258 }
4259}
4260
Austin Borgered99f642023-06-01 16:51:35 -07004261bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004262 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004263 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004264}
4265
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004266static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4267static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004268
Austin Borgered99f642023-06-01 16:51:35 -07004269bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004270 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004271 // If activity manager is unreachable, assume everything is active
4272 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004273 return true;
4274 }
4275 auto it = mOverrideUids.find(uid);
4276 if (it != mOverrideUids.end()) {
4277 return it->second;
4278 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004279 bool active = mActiveUids.find(uid) != mActiveUids.end();
4280 if (!active) {
4281 // We want active UIDs to always access camera with their first attempt since
4282 // there is no guarantee the app is robustly written and would retry getting
4283 // the camera on failure. The inverse case is not a problem as we would take
4284 // camera away soon once we get the callback that the uid is no longer active.
4285 ActivityManager am;
4286 // Okay to access with a lock held as UID changes are dispatched without
4287 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004288 int64_t startTimeMillis = 0;
4289 do {
4290 // TODO: Fix this b/109950150!
4291 // Okay this is a hack. There is a race between the UID turning active and
4292 // activity being resumed. The proper fix is very risky, so we temporary add
4293 // some polling which should happen pretty rarely anyway as the race is hard
4294 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004295 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004296 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004297 if (active) {
4298 break;
4299 }
4300 if (startTimeMillis <= 0) {
4301 startTimeMillis = uptimeMillis();
4302 }
4303 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004304 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004305 if (remainingTimeMillis <= 0) {
4306 break;
4307 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004308 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4309
4310 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004311 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004312 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004313 } while (true);
4314
Svet Ganov7b4ab782018-03-25 12:48:10 -07004315 if (active) {
4316 // Now that we found out the UID is actually active, cache that
4317 mActiveUids.insert(uid);
4318 }
4319 }
4320 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004321}
4322
Varun Shahb42f1eb2019-04-16 14:45:13 -07004323int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4324 Mutex::Autolock _l(mUidLock);
4325 return getProcStateLocked(uid);
4326}
4327
4328int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4329 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4330 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004331 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004332 }
4333 return procState;
4334}
4335
Austin Borgered99f642023-06-01 16:51:35 -07004336void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4337 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004338 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004339}
4340
Austin Borgered99f642023-06-01 16:51:35 -07004341void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004342 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004343}
4344
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004345void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4346 Mutex::Autolock _l(mUidLock);
4347 ALOGV("UidPolicy: ActivityManager has died");
4348 mRegistered = false;
4349 mActiveUids.clear();
4350}
4351
Austin Borgered99f642023-06-01 16:51:35 -07004352void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004353 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004354 bool wasActive = false;
4355 bool isActive = false;
4356 {
4357 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004358 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004359 mOverrideUids.erase(uid);
4360 if (insert) {
4361 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4362 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004363 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004364 }
4365 if (wasActive != isActive && !isActive) {
4366 sp<CameraService> service = mService.promote();
4367 if (service != nullptr) {
4368 service->blockClientsForUid(uid);
4369 }
4370 }
4371}
4372
4373// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004374// SensorPrivacyPolicy
4375// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004376
4377void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4378{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004379 Mutex::Autolock _l(mSensorPrivacyLock);
4380 if (mRegistered) {
4381 return;
4382 }
Evan Severson09ab4002021-02-10 14:15:19 -08004383 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004384 mSpm.addSensorPrivacyListener(this);
4385 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4386 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004387 if (res == OK) {
4388 mRegistered = true;
4389 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4390 }
4391}
4392
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004393void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4394 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004395 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004396 return;
4397 }
4398
4399 registerWithSensorPrivacyManager();
4400}
4401
4402void CameraService::SensorPrivacyPolicy::registerSelf() {
4403 // Use checkservice to see if the sensor_privacy service is available
4404 // If service is not available then register for notification
4405 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004406 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004407 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004408 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004409 } else {
4410 registerWithSensorPrivacyManager();
4411 }
4412}
4413
Michael Grooverd1d435a2018-12-18 17:39:42 -08004414void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4415 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004416 mSpm.removeSensorPrivacyListener(this);
4417 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004418 mRegistered = false;
4419 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4420}
4421
4422bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004423 if (!mRegistered) {
4424 registerWithSensorPrivacyManager();
4425 }
4426
Michael Grooverd1d435a2018-12-18 17:39:42 -08004427 Mutex::Autolock _l(mSensorPrivacyLock);
4428 return mSensorPrivacyEnabled;
4429}
4430
Evan Seversond0b69922022-01-27 10:47:34 -08004431bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004432 if (!hasCameraPrivacyFeature()) {
4433 return false;
4434 }
Evan Seversond0b69922022-01-27 10:47:34 -08004435 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004436}
4437
Evan Seversond0b69922022-01-27 10:47:34 -08004438binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4439 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004440 {
4441 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004442 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004443 }
4444 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004445 if (enabled) {
4446 sp<CameraService> service = mService.promote();
4447 if (service != nullptr) {
4448 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004449 }
4450 }
4451 return binder::Status::ok();
4452}
4453
4454void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4455 Mutex::Autolock _l(mSensorPrivacyLock);
4456 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4457 mRegistered = false;
4458}
4459
Evan Severson09ab4002021-02-10 14:15:19 -08004460bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004461 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4462 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4463 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4464 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4465 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004466}
4467
Michael Grooverd1d435a2018-12-18 17:39:42 -08004468// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004469// CameraState
4470// ----------------------------------------------------------------------------
4471
Austin Borgered99f642023-06-01 16:51:35 -07004472CameraService::CameraState::CameraState(const std::string& id, int cost,
4473 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004474 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004475 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004476 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004477
4478CameraService::CameraState::~CameraState() {}
4479
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004480CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004481 Mutex::Autolock lock(mStatusLock);
4482 return mStatus;
4483}
4484
Austin Borgered99f642023-06-01 16:51:35 -07004485std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004486 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004487 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004488 return res;
4489}
4490
Ruben Brunkcc776712015-02-17 20:18:47 -08004491CameraParameters CameraService::CameraState::getShimParams() const {
4492 return mShimParams;
4493}
4494
4495void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4496 mShimParams = params;
4497}
4498
4499int CameraService::CameraState::getCost() const {
4500 return mCost;
4501}
4502
Austin Borgered99f642023-06-01 16:51:35 -07004503std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004504 return mConflicting;
4505}
4506
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004507SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4508 return mSystemCameraKind;
4509}
4510
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004511bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4512 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4513 != mPhysicalCameras.end();
4514}
4515
Austin Borgered99f642023-06-01 16:51:35 -07004516bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004517 Mutex::Autolock lock(mStatusLock);
4518 auto result = mUnavailablePhysicalIds.insert(physicalId);
4519 return result.second;
4520}
4521
Austin Borgered99f642023-06-01 16:51:35 -07004522bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004523 Mutex::Autolock lock(mStatusLock);
4524 auto count = mUnavailablePhysicalIds.erase(physicalId);
4525 return count > 0;
4526}
4527
Austin Borgered99f642023-06-01 16:51:35 -07004528void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004529 Mutex::Autolock lock(mStatusLock);
4530 mClientPackage = clientPackage;
4531}
4532
Austin Borgered99f642023-06-01 16:51:35 -07004533std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004534 Mutex::Autolock lock(mStatusLock);
4535 return mClientPackage;
4536}
4537
Ruben Brunkcc776712015-02-17 20:18:47 -08004538// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004539// ClientEventListener
4540// ----------------------------------------------------------------------------
4541
4542void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004543 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004544 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004545 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004546 if (basicClient.get() != nullptr) {
4547 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004548 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004549 static_cast<int>(basicClient->getClientUid()));
4550 }
4551}
4552
4553void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004554 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004555 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004556 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004557 if (basicClient.get() != nullptr) {
4558 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004559 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004560 static_cast<int>(basicClient->getClientUid()));
4561 }
4562}
4563
4564
4565// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004566// CameraClientManager
4567// ----------------------------------------------------------------------------
4568
Ruben Brunk99e69712015-05-26 17:25:07 -07004569CameraService::CameraClientManager::CameraClientManager() {
4570 setListener(std::make_shared<ClientEventListener>());
4571}
4572
Ruben Brunkcc776712015-02-17 20:18:47 -08004573CameraService::CameraClientManager::~CameraClientManager() {}
4574
4575sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004576 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004577 auto descriptor = get(id);
4578 if (descriptor == nullptr) {
4579 return sp<BasicClient>{nullptr};
4580 }
4581 return descriptor->getValue();
4582}
4583
Austin Borgered99f642023-06-01 16:51:35 -07004584std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004585 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004586 std::ostringstream ret;
4587 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004588 bool hasAny = false;
4589 for (auto& i : all) {
4590 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004591 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004592 int32_t cost = i->getCost();
4593 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004594 int32_t score = i->getPriority().getScore();
4595 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004596 auto conflicting = i->getConflicting();
4597 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07004598 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004599 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004600 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004601 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07004602 uid_t clientUid = clientSp->getClientUid();
4603 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004604 }
Austin Borgered99f642023-06-01 16:51:35 -07004605 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4606 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004607
Ruben Brunk6267b532015-04-30 17:44:07 -07004608 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004609 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07004610 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004611 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07004612 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004613 }
4614
Austin Borgered99f642023-06-01 16:51:35 -07004615 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08004616 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07004617 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004618 }
Austin Borgered99f642023-06-01 16:51:35 -07004619 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08004620 }
Austin Borgered99f642023-06-01 16:51:35 -07004621 if (hasAny) ret << "\n";
4622 ret << "]\n";
4623 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004624}
4625
4626CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07004627 const std::string& key, const sp<BasicClient>& value, int32_t cost,
4628 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004629 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004630
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004631 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07004632 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004633
Austin Borgered99f642023-06-01 16:51:35 -07004634 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004635 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4636 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004637}
4638
4639CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004640 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004641 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004642 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004643 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004644 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4645 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004646}
4647
4648// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004649// InjectionStatusListener
4650// ----------------------------------------------------------------------------
4651
4652void CameraService::InjectionStatusListener::addListener(
4653 const sp<ICameraInjectionCallback>& callback) {
4654 Mutex::Autolock lock(mListenerLock);
4655 if (mCameraInjectionCallback) return;
4656 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4657 if (res == OK) {
4658 mCameraInjectionCallback = callback;
4659 }
4660}
4661
4662void CameraService::InjectionStatusListener::removeListener() {
4663 Mutex::Autolock lock(mListenerLock);
4664 if (mCameraInjectionCallback == nullptr) {
4665 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4666 return;
4667 }
4668 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4669 mCameraInjectionCallback = nullptr;
4670}
4671
4672void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07004673 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004674 if (mCameraInjectionCallback == nullptr) {
4675 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4676 return;
4677 }
Cliff Wud3a05312021-04-26 23:07:31 +08004678
4679 switch (err) {
4680 case -ENODEV:
4681 mCameraInjectionCallback->onInjectionError(
4682 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4683 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07004684 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004685 break;
4686 case -EBUSY:
4687 mCameraInjectionCallback->onInjectionError(
4688 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4689 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07004690 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004691 break;
4692 case DEAD_OBJECT:
4693 mCameraInjectionCallback->onInjectionError(
4694 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4695 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07004696 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004697 break;
4698 case INVALID_OPERATION:
4699 mCameraInjectionCallback->onInjectionError(
4700 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4701 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07004702 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004703 break;
4704 case UNKNOWN_TRANSACTION:
4705 mCameraInjectionCallback->onInjectionError(
4706 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4707 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07004708 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004709 break;
4710 default:
4711 mCameraInjectionCallback->onInjectionError(
4712 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4713 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07004714 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004715 }
Cliff Wud8cae102021-03-11 01:37:42 +08004716}
4717
4718void CameraService::InjectionStatusListener::binderDied(
4719 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004720 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4721 auto parent = mParent.promote();
4722 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004723 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4724 if (clientDescriptor != nullptr) {
4725 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4726 baseClientPtr->stopInjection();
4727 }
Cliff Wu3b268182021-07-06 15:44:43 +08004728 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004729 }
4730}
4731
4732// ----------------------------------------------------------------------------
4733// CameraInjectionSession
4734// ----------------------------------------------------------------------------
4735
4736binder::Status CameraService::CameraInjectionSession::stopInjection() {
4737 Mutex::Autolock lock(mInjectionSessionLock);
4738 auto parent = mParent.promote();
4739 if (parent == nullptr) {
4740 ALOGE("CameraInjectionSession: Parent is gone");
4741 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4742 "Camera service encountered error");
4743 }
Cliff Wud3a05312021-04-26 23:07:31 +08004744
4745 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004746 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4747 if (clientDescriptor != nullptr) {
4748 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4749 res = baseClientPtr->stopInjection();
4750 if (res != OK) {
4751 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4752 " ret != NO_ERROR: %d", res);
4753 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4754 "Camera session encountered error");
4755 }
4756 }
Cliff Wu3b268182021-07-06 15:44:43 +08004757 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004758 return binder::Status::ok();
4759}
4760
4761// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004762
4763static const int kDumpLockRetries = 50;
4764static const int kDumpLockSleep = 60000;
4765
4766static bool tryLock(Mutex& mutex)
4767{
4768 bool locked = false;
4769 for (int i = 0; i < kDumpLockRetries; ++i) {
4770 if (mutex.tryLock() == NO_ERROR) {
4771 locked = true;
4772 break;
4773 }
4774 usleep(kDumpLockSleep);
4775 }
4776 return locked;
4777}
4778
Rucha Katakwardf223072021-06-15 10:21:00 -07004779void CameraService::cacheDump() {
4780 if (mMemFd != -1) {
4781 const Vector<String16> args;
4782 ATRACE_CALL();
4783 // Acquiring service lock here will avoid the deadlock since
4784 // cacheDump will not be called during the second disconnect.
4785 Mutex::Autolock lock(mServiceLock);
4786
4787 Mutex::Autolock l(mCameraStatesLock);
4788 // Start collecting the info for open sessions and store it in temp file.
4789 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004790 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07004791 auto clientDescriptor = mActiveClientManager.get(cameraId);
4792 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004793 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004794 // Log the current open session info before device is disconnected.
4795 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4796 }
4797 }
4798 }
4799}
4800
Mathias Agopian65ab4712010-07-14 17:59:35 -07004801status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004802 ATRACE_CALL();
4803
Austin Borgered99f642023-06-01 16:51:35 -07004804 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004805 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004806 CameraThreadState::getCallingPid(),
4807 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004808 return NO_ERROR;
4809 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004810 bool locked = tryLock(mServiceLock);
4811 // failed to lock - CameraService is probably deadlocked
4812 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004813 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004814 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004815
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004816 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004817 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004818
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004819 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004820 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004821
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004822 if (locked) mServiceLock.unlock();
4823 return NO_ERROR;
4824 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004825 dprintf(fd, "\n== Service global info: ==\n\n");
4826 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004827 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004828 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4829 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004830 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4831 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4832 }
Austin Borgered99f642023-06-01 16:51:35 -07004833 std::string activeClientString = mActiveClientManager.toString();
4834 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
4835 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004836 if (mStreamUseCaseOverrides.size() > 0) {
4837 dprintf(fd, "Active stream use case overrides:");
4838 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4839 dprintf(fd, " %" PRId64, useCaseOverride);
4840 }
4841 dprintf(fd, "\n");
4842 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004843
4844 dumpEventLog(fd);
4845
4846 bool stateLocked = tryLock(mCameraStatesLock);
4847 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004848 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004849 }
4850
Emilian Peevbd8c5032018-02-14 23:05:40 +00004851 int argSize = args.size();
4852 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07004853 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00004854 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07004855 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00004856 }
4857 break;
4858 }
4859 }
4860
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004861 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004862 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004863
Austin Borgered99f642023-06-01 16:51:35 -07004864 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004865
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004866 CameraParameters p = state.second->getShimParams();
4867 if (!p.isEmpty()) {
4868 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4869 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004870 }
4871
4872 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004873 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004874 // log the current open session info
4875 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004876 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004877 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004878 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004879
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004880 }
4881
4882 if (stateLocked) mCameraStatesLock.unlock();
4883
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004884 if (locked) mServiceLock.unlock();
4885
Emilian Peevf53f66e2017-04-11 14:29:43 +01004886 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004887
4888 dprintf(fd, "\n== Vendor tags: ==\n\n");
4889
4890 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4891 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004892 sp<VendorTagDescriptorCache> cache =
4893 VendorTagDescriptorCache::getGlobalVendorTagCache();
4894 if (cache == NULL) {
4895 dprintf(fd, "No vendor tags.\n");
4896 } else {
4897 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4898 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004899 } else {
4900 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4901 }
4902
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004903 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004904 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004905 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004906
4907 // Process dump arguments, if any
4908 int n = args.size();
4909 String16 verboseOption("-v");
4910 String16 unreachableOption("--unreachable");
4911 for (int i = 0; i < n; i++) {
4912 if (args[i] == verboseOption) {
4913 // change logging level
4914 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07004915 std::string levelStr = toStdString(args[i+1]);
4916 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004917 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004918 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004919 } else if (args[i] == unreachableOption) {
4920 // Dump memory analysis
4921 // TODO - should limit be an argument parameter?
4922 UnreachableMemoryInfo info;
4923 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4924 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004925 dprintf(fd, "\n== Unable to dump unreachable memory. "
4926 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004927 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004928 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004929 std::string s = info.ToString(/*log_contents*/ true);
4930 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004931 }
4932 }
4933 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004934
4935 bool serviceLocked = tryLock(mServiceLock);
4936
4937 // Dump info from previous open sessions.
4938 // Reposition the offset to beginning of the file before reading
4939
4940 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4941 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4942 ssize_t size_read;
4943 char buf[4096];
4944 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4945 // Read data from file to a small buffer and write it to fd.
4946 write(fd, buf, size_read);
4947 if (size_read == -1) {
4948 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4949 break;
4950 }
4951 }
4952 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4953 } else {
4954 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4955 }
4956
4957 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004958 return NO_ERROR;
4959}
4960
Rucha Katakwardf223072021-06-15 10:21:00 -07004961void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07004962 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004963 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004964 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07004965 getFormattedCurrentTime().c_str(),
4966 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004967 dprintf(fd, " Client priority score: %d state: %d\n",
4968 clientDescriptor->getPriority().getScore(),
4969 clientDescriptor->getPriority().getState());
4970 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4971
4972 auto client = clientDescriptor->getValue();
4973 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07004974 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004975
4976 client->dumpClient(fd, args);
4977}
4978
Austin Borgered99f642023-06-01 16:51:35 -07004979void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004980 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07004981 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004982}
4983
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004984void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004985 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004986
4987 Mutex::Autolock l(mLogLock);
4988 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07004989 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004990 }
4991
4992 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004993 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004994 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004995 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004996 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004997 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004998}
4999
Austin Borgered99f642023-06-01 16:51:35 -07005000void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005001 Mutex::Autolock lock(mLogLock);
5002 if (!isClientWatchedLocked(client)) { return; }
5003
5004 std::vector<std::string> dumpVector;
5005 client->dumpWatchedEventsToVector(dumpVector);
5006
5007 if (dumpVector.empty()) { return; }
5008
Austin Borgered99f642023-06-01 16:51:35 -07005009 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005010
Austin Borgered99f642023-06-01 16:51:35 -07005011 std::string currentTime = getFormattedCurrentTime();
5012 dumpString << "Cached @ ";
5013 dumpString << currentTime;
5014 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005015
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005016 size_t i = dumpVector.size();
5017
5018 // Store the string in reverse order (latest last)
5019 while (i > 0) {
5020 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005021 dumpString << cameraId;
5022 dumpString << ":";
5023 dumpString << client->getPackageName();
5024 dumpString << " ";
5025 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005026 }
5027
Austin Borgered99f642023-06-01 16:51:35 -07005028 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005029}
5030
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005031void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005032 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005033 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5034 if (mTorchClientMap[i] == who) {
5035 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005036 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005037 status_t res = mFlashlight->setTorchMode(cameraId, false);
5038 if (res) {
5039 ALOGE("%s: torch client died but couldn't turn off torch: "
5040 "%s (%d)", __FUNCTION__, strerror(-res), res);
5041 return;
5042 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005043 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005044 break;
5045 }
5046 }
5047}
5048
Ruben Brunkcc776712015-02-17 20:18:47 -08005049/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005050
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005051 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005052 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5053 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005054 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005055 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005056 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005057
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005058 // check torch client
5059 handleTorchClientBinderDied(who);
5060
5061 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005062 if(!evictClientIdByRemote(who)) {
5063 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005064 return;
5065 }
5066
Ruben Brunkcc776712015-02-17 20:18:47 -08005067 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5068 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005069}
5070
Austin Borgered99f642023-06-01 16:51:35 -07005071void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005072 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005073}
5074
Austin Borgered99f642023-06-01 16:51:35 -07005075void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005076 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005077 // Do not lock mServiceLock here or can get into a deadlock from
5078 // connect() -> disconnect -> updateStatus
5079
5080 auto state = getCameraState(cameraId);
5081
5082 if (state == nullptr) {
5083 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005084 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005085 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005086 }
5087
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005088 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5089 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5090 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005091 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005092 return;
5093 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005094
5095 // Collect the logical cameras without holding mStatusLock in updateStatus
5096 // as that can lead to a deadlock(b/162192331).
5097 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005098 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005099 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005100 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005101 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005102 (const std::string& cameraId, StatusInternal status) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005103 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005104 // Update torch status if it has a flash unit.
5105 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005106 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005107 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5108 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005109 TorchModeStatus newTorchStatus =
5110 status == StatusInternal::PRESENT ?
5111 TorchModeStatus::AVAILABLE_OFF :
5112 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005113 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005114 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005115 }
5116 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005117 }
5118
5119 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005120 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005121 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005122
Ruben Brunkcc776712015-02-17 20:18:47 -08005123 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005124 bool isVendorListener = listener->isVendorListener();
5125 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5126 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07005127 isVendorListener) {
5128 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005129 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005130 continue;
5131 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005132 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005133 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005134 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005135 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005136 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5137 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005138 // Also trigger the callbacks for cameras that were remapped to the current
5139 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005140 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005141 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5142 for (auto& remappedCameraId : remappedCameraIds) {
5143 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005144 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005145 listener->handleBinderStatus(ret,
5146 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5147 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5148 ret.exceptionCode());
5149 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005150 }
5151 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005152}
5153
Austin Borgered99f642023-06-01 16:51:35 -07005154void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5155 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005156 auto state = getCameraState(cameraId);
5157 if (state == nullptr) {
5158 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005159 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005160 return;
5161 }
5162 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005163 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005164 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005165 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005166 }
5167
Shuzhen Wang695044d2020-03-06 09:02:23 -08005168 Mutex::Autolock lock(mStatusListenerLock);
5169
5170 for (const auto& it : mListenerList) {
5171 if (!it->isOpenCloseCallbackAllowed()) {
5172 continue;
5173 }
5174
5175 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005176 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005177 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005178 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005179 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005180 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005181
5182 it->handleBinderStatus(ret,
5183 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5184 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005185 }
5186}
5187
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005188template<class Func>
5189void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005190 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005191 std::initializer_list<StatusInternal> rejectSourceStates,
5192 Func onStatusUpdatedLocked) {
5193 Mutex::Autolock lock(mStatusLock);
5194 StatusInternal oldStatus = mStatus;
5195 mStatus = status;
5196
5197 if (oldStatus == status) {
5198 return;
5199 }
5200
5201 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005202 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005203
5204 if (oldStatus == StatusInternal::NOT_PRESENT &&
5205 (status != StatusInternal::PRESENT &&
5206 status != StatusInternal::ENUMERATING)) {
5207
5208 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5209 __FUNCTION__);
5210 mStatus = oldStatus;
5211 return;
5212 }
5213
5214 /**
5215 * Sometimes we want to conditionally do a transition.
5216 * For example if a client disconnects, we want to go to PRESENT
5217 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5218 */
5219 for (auto& rejectStatus : rejectSourceStates) {
5220 if (oldStatus == rejectStatus) {
5221 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005222 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005223 mStatus = oldStatus;
5224 return;
5225 }
5226 }
5227
5228 onStatusUpdatedLocked(cameraId, status);
5229}
5230
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005231status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005232 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005233 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005234 if (!status) {
5235 return BAD_VALUE;
5236 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005237 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5238 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005239 // invalid camera ID or the camera doesn't have a flash unit
5240 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005241 }
5242
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005243 *status = mTorchStatusMap.valueAt(index);
5244 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005245}
5246
Austin Borgered99f642023-06-01 16:51:35 -07005247status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005248 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005249 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5250 if (index == NAME_NOT_FOUND) {
5251 return BAD_VALUE;
5252 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005253 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005254
5255 return OK;
5256}
5257
Austin Borgered99f642023-06-01 16:51:35 -07005258std::list<std::string> CameraService::getLogicalCameras(
5259 const std::string& physicalCameraId) {
5260 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005261 Mutex::Autolock lock(mCameraStatesLock);
5262 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005263 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5264 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005265 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005266 }
5267 return retList;
5268}
5269
5270void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005271 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005272 SystemCameraKind deviceKind) {
5273 // mStatusListenerLock is expected to be locked
5274 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005275 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005276 // Note: we check only the deviceKind of the physical camera id
5277 // since, logical camera ids and their physical camera ids are
5278 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005279 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5280 listener->getListenerPid(), listener->getListenerUid())) {
5281 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005282 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005283 continue;
5284 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005285 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005286 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005287 listener->handleBinderStatus(ret,
5288 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5289 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5290 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005291 }
5292 }
5293}
5294
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005295
Svet Ganova453d0d2018-01-11 15:37:58 -08005296void CameraService::blockClientsForUid(uid_t uid) {
5297 const auto clients = mActiveClientManager.getAll();
5298 for (auto& current : clients) {
5299 if (current != nullptr) {
5300 const auto basicClient = current->getValue();
5301 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5302 basicClient->block();
5303 }
5304 }
5305 }
5306}
5307
Michael Grooverd1d435a2018-12-18 17:39:42 -08005308void CameraService::blockAllClients() {
5309 const auto clients = mActiveClientManager.getAll();
5310 for (auto& current : clients) {
5311 if (current != nullptr) {
5312 const auto basicClient = current->getValue();
5313 if (basicClient.get() != nullptr) {
5314 basicClient->block();
5315 }
5316 }
5317 }
5318}
5319
Svet Ganova453d0d2018-01-11 15:37:58 -08005320// NOTE: This is a remote API - make sure all args are validated
5321status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005322 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005323 return PERMISSION_DENIED;
5324 }
5325 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5326 return BAD_VALUE;
5327 }
Austin Borgered99f642023-06-01 16:51:35 -07005328 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005329 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005330 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005331 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005332 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005333 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005334 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005335 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005336 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005337 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005338 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005339 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005340 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005341 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005342 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005343 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005344 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005345 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005346 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005347 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005348 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005349 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005350 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005351 handleClearStreamUseCaseOverrides();
5352 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005353 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005354 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005355 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005356 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005357 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005358 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005359 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005360 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005361 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005362 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005363 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005364 }
5365 printHelp(err);
5366 return BAD_VALUE;
5367}
5368
malikakash82ed4352023-07-21 22:44:34 +00005369status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5370 uid_t uid = IPCThreadState::self()->getCallingUid();
5371 if (uid != AID_ROOT) {
5372 dprintf(err, "Must be adb root\n");
5373 return PERMISSION_DENIED;
5374 }
5375 if (args.size() != 4) {
5376 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5377 return BAD_VALUE;
5378 }
Austin Borgered99f642023-06-01 16:51:35 -07005379 std::string packageName = toStdString(args[1]);
5380 std::string cameraIdToReplace = toStdString(args[2]);
5381 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005382 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5383 return OK;
5384}
5385
Svet Ganova453d0d2018-01-11 15:37:58 -08005386status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005387 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005388
Svet Ganova453d0d2018-01-11 15:37:58 -08005389 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005390 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005391 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005392 } else if ((args[2] != toString16("idle"))) {
5393 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005394 return BAD_VALUE;
5395 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005396
5397 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005398 if (args.size() >= 5 && args[3] == toString16("--user")) {
5399 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005400 }
5401
5402 uid_t uid;
5403 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5404 return BAD_VALUE;
5405 }
5406
5407 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005408 return NO_ERROR;
5409}
5410
5411status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005412 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005413
5414 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005415 if (args.size() >= 4 && args[2] == toString16("--user")) {
5416 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005417 }
5418
5419 uid_t uid;
5420 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005421 return BAD_VALUE;
5422 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005423
5424 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005425 return NO_ERROR;
5426}
5427
5428status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005429 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005430
5431 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005432 if (args.size() >= 4 && args[2] == toString16("--user")) {
5433 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005434 }
5435
5436 uid_t uid;
5437 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005438 return BAD_VALUE;
5439 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005440
5441 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005442 return dprintf(out, "active\n");
5443 } else {
5444 return dprintf(out, "idle\n");
5445 }
5446}
5447
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005448status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005449 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005450 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5451 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5452 Mutex::Autolock lock(mServiceLock);
5453
5454 mOverrideRotateAndCropMode = rotateValue;
5455
5456 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5457
5458 const auto clients = mActiveClientManager.getAll();
5459 for (auto& current : clients) {
5460 if (current != nullptr) {
5461 const auto basicClient = current->getValue();
5462 if (basicClient.get() != nullptr) {
5463 basicClient->setRotateAndCropOverride(rotateValue);
5464 }
5465 }
5466 }
5467
5468 return OK;
5469}
5470
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005471status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5472 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005473 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005474 if ((*end != '\0') ||
5475 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5476 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5477 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5478 return BAD_VALUE;
5479 }
5480
5481 Mutex::Autolock lock(mServiceLock);
5482 mOverrideAutoframingMode = autoframingValue;
5483
5484 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5485
5486 const auto clients = mActiveClientManager.getAll();
5487 for (auto& current : clients) {
5488 if (current != nullptr) {
5489 const auto basicClient = current->getValue();
5490 if (basicClient.get() != nullptr) {
5491 basicClient->setAutoframingOverride(autoframingValue);
5492 }
5493 }
5494 }
5495
5496 return OK;
5497}
5498
Ravneetaeb20dc2022-03-30 05:33:03 +00005499status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005500 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005501
5502 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5503
5504 Mutex::Autolock lock(mServiceLock);
5505
5506 mCameraServiceWatchdogEnabled = enableWatchdog;
5507
5508 const auto clients = mActiveClientManager.getAll();
5509 for (auto& current : clients) {
5510 if (current != nullptr) {
5511 const auto basicClient = current->getValue();
5512 if (basicClient.get() != nullptr) {
5513 basicClient->setCameraServiceWatchdog(enableWatchdog);
5514 }
5515 }
5516 }
5517
5518 return OK;
5519}
5520
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005521status_t CameraService::handleGetRotateAndCrop(int out) {
5522 Mutex::Autolock lock(mServiceLock);
5523
5524 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5525}
5526
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005527status_t CameraService::handleGetAutoframing(int out) {
5528 Mutex::Autolock lock(mServiceLock);
5529
5530 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5531}
5532
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005533status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5534 char *endPtr;
5535 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005536 std::string maskString = toStdString(args[1]);
5537 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005538
5539 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005540 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005541 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5542
5543 Mutex::Autolock lock(mServiceLock);
5544
5545 mImageDumpMask = maskValue;
5546
5547 return OK;
5548}
5549
5550status_t CameraService::handleGetImageDumpMask(int out) {
5551 Mutex::Autolock lock(mServiceLock);
5552
5553 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5554}
5555
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005556status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005557 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005558 if (errno != 0) return BAD_VALUE;
5559
5560 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5561 Mutex::Autolock lock(mServiceLock);
5562
5563 mOverrideCameraMuteMode = (muteValue == 1);
5564
5565 const auto clients = mActiveClientManager.getAll();
5566 for (auto& current : clients) {
5567 if (current != nullptr) {
5568 const auto basicClient = current->getValue();
5569 if (basicClient.get() != nullptr) {
5570 if (basicClient->supportsCameraMute()) {
5571 basicClient->setCameraMute(mOverrideCameraMuteMode);
5572 }
5573 }
5574 }
5575 }
5576
5577 return OK;
5578}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005579
Shuzhen Wang16610a62022-12-15 22:38:07 -08005580status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5581 std::vector<int64_t> useCasesOverride;
5582 for (size_t i = 1; i < args.size(); i++) {
5583 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005584 std::string arg = toStdString(args[i]);
5585 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005586 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005587 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005588 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07005589 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005590 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07005591 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005592 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07005593 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005594 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07005595 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005596 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07005597 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005598 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5599 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005600 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005601 return BAD_VALUE;
5602 }
5603 useCasesOverride.push_back(useCase);
5604 }
5605
5606 Mutex::Autolock lock(mServiceLock);
5607 mStreamUseCaseOverrides = std::move(useCasesOverride);
5608
5609 return OK;
5610}
5611
5612void CameraService::handleClearStreamUseCaseOverrides() {
5613 Mutex::Autolock lock(mServiceLock);
5614 mStreamUseCaseOverrides.clear();
5615}
5616
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005617status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
5618 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005619 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005620 if ((*end != '\0') ||
5621 (zoomOverrideValue != -1 &&
5622 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
5623 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
5624 return BAD_VALUE;
5625 }
5626
5627 Mutex::Autolock lock(mServiceLock);
5628 mZoomOverrideValue = zoomOverrideValue;
5629
5630 const auto clients = mActiveClientManager.getAll();
5631 for (auto& current : clients) {
5632 if (current != nullptr) {
5633 const auto basicClient = current->getValue();
5634 if (basicClient.get() != nullptr) {
5635 if (basicClient->supportsZoomOverride()) {
5636 basicClient->setZoomOverride(mZoomOverrideValue);
5637 }
5638 }
5639 }
5640 }
5641
5642 return OK;
5643}
5644
Avichal Rakesh84147132021-11-11 17:47:11 -08005645status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07005646 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005647 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005648 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005649 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005650 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005651 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005652 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005653 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005654 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005655 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005656 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005657 dprintf(outFd, "Camera service watch commands:\n"
5658 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5659 " starts watching the provided tags for clients with provided package\n"
5660 " recognizes tag shorthands like '3a'\n"
5661 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005662 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005663 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005664 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005665 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005666 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005667 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005668 return BAD_VALUE;
5669}
5670
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005671status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5672 Mutex::Autolock lock(mLogLock);
5673 size_t tagsIdx; // index of '-m'
5674 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07005675 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005676 if (tagsIdx < args.size() - 1) {
5677 tags = args[tagsIdx + 1];
5678 } else {
5679 dprintf(outFd, "No tags provided.\n");
5680 return BAD_VALUE;
5681 }
5682
5683 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07005684 // watch all clients if no clients are provided
5685 String16 clients = toString16(kWatchAllClientsFlag);
5686 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005687 clientsIdx++);
5688 if (clientsIdx < args.size() - 1) {
5689 clients = args[clientsIdx + 1];
5690 }
Austin Borgered99f642023-06-01 16:51:35 -07005691 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005692
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005693 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07005694 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005695
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005696 bool serviceLock = tryLock(mServiceLock);
5697 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005698 auto cameraClients = mActiveClientManager.getAll();
5699 for (const auto &clientDescriptor: cameraClients) {
5700 if (clientDescriptor == nullptr) { continue; }
5701 sp<BasicClient> client = clientDescriptor->getValue();
5702 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005703
5704 if (isClientWatchedLocked(client.get())) {
5705 client->startWatchingTags(mMonitorTags, outFd);
5706 numWatchedClients++;
5707 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005708 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005709 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5710
5711 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005712 return OK;
5713}
5714
5715status_t CameraService::stopWatchingTags(int outFd) {
5716 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005717 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005718 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005719
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005720 mWatchedClientPackages.clear();
5721 mWatchedClientsDumpCache.clear();
5722
5723 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005724 auto cameraClients = mActiveClientManager.getAll();
5725 for (const auto &clientDescriptor : cameraClients) {
5726 if (clientDescriptor == nullptr) { continue; }
5727 sp<BasicClient> client = clientDescriptor->getValue();
5728 if (client.get() == nullptr) { continue; }
5729 client->stopWatchingTags(outFd);
5730 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005731 dprintf(outFd, "Stopped watching all clients.\n");
5732 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005733 return OK;
5734}
5735
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005736status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5737 Mutex::Autolock lock(mLogLock);
5738 size_t clearedSize = mWatchedClientsDumpCache.size();
5739 mWatchedClientsDumpCache.clear();
5740 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5741 return OK;
5742}
5743
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005744status_t CameraService::printWatchedTags(int outFd) {
5745 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005746 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005747
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005748 bool printedSomething = false; // tracks if any monitoring information was printed
5749 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005750
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005751 bool serviceLock = tryLock(mServiceLock);
5752 // get all watched clients that are currently connected
5753 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5754 if (clientDescriptor == nullptr) { continue; }
5755
5756 sp<BasicClient> client = clientDescriptor->getValue();
5757 if (client.get() == nullptr) { continue; }
5758 if (!isClientWatchedLocked(client.get())) { continue; }
5759
5760 std::vector<std::string> dumpVector;
5761 client->dumpWatchedEventsToVector(dumpVector);
5762
5763 size_t printIdx = dumpVector.size();
5764 if (printIdx == 0) {
5765 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005766 }
5767
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005768 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07005769 const std::string &cameraId = clientDescriptor->getKey();
5770 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005771 while(printIdx > 0) {
5772 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07005773 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005774 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005775 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005776 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005777 printedSomething = true;
5778
5779 connectedMonitoredClients.emplace(client->getPackageName());
5780 }
5781 if (serviceLock) { mServiceLock.unlock(); }
5782
5783 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5784 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07005785 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005786 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5787 continue;
5788 }
5789
Austin Borgered99f642023-06-01 16:51:35 -07005790 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005791 dprintf(outFd, "%s\n", kv.second.c_str());
5792 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005793 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005794
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005795 if (!printedSomething) {
5796 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005797 }
5798
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005799 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005800}
5801
Avichal Rakesh84147132021-11-11 17:47:11 -08005802// Print all events in vector `events' that came after lastPrintedEvent
5803void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005804 const std::string &cameraId,
5805 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08005806 const std::vector<std::string> &events,
5807 const std::string &lastPrintedEvent) {
5808 if (events.empty()) { return; }
5809
5810 // index of lastPrintedEvent in events.
5811 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5812 size_t lastPrintedIdx;
5813 for (lastPrintedIdx = 0;
5814 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5815 lastPrintedIdx++);
5816
5817 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5818
Avichal Rakesh84147132021-11-11 17:47:11 -08005819 // print events in chronological order (latest event last)
5820 size_t idxToPrint = lastPrintedIdx;
5821 do {
5822 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07005823 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
5824 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08005825 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08005826}
5827
5828// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5829// command should be interrupted if the user presses the return key, or if user loses any way to
5830// signal interrupt.
5831// If timeoutMs == 0, this function will always return false
5832bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5833 struct timeval startTime;
5834 int startTimeError = gettimeofday(&startTime, nullptr);
5835 if (startTimeError) {
5836 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5837 return true;
5838 }
5839
5840 const nfds_t numFds = 1;
5841 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5842
5843 struct timeval currTime;
5844 char buffer[2];
5845 while(true) {
5846 int currTimeError = gettimeofday(&currTime, nullptr);
5847 if (currTimeError) {
5848 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5849 return true;
5850 }
5851
5852 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5853 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5854 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5855
5856 if (remainingTimeMs <= 0) {
5857 // No user interrupt within timeoutMs, don't interrupt watch command
5858 return false;
5859 }
5860
5861 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5862 if (numFdsUpdated < 0) {
5863 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5864 return true;
5865 }
5866
5867 if (numFdsUpdated == 0) {
5868 // No user input within timeoutMs, don't interrupt watch command
5869 return false;
5870 }
5871
5872 if (!(pollFd.revents & POLLIN)) {
5873 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5874 return true;
5875 }
5876
5877 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5878 if (sizeRead < 0) {
5879 dprintf(outFd, "Error reading user input. Exiting.\n");
5880 return true;
5881 }
5882
5883 if (sizeRead == 0) {
5884 // Reached end of input fd (can happen if input is piped)
5885 // User has no way to signal an interrupt, so interrupt here
5886 return true;
5887 }
5888
5889 if (buffer[0] == '\n') {
5890 // User pressed return, interrupt watch command.
5891 return true;
5892 }
5893 }
5894}
5895
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005896status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5897 int inFd, int outFd) {
5898 // Figure out refresh interval, if present in args
5899 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005900 if (args.size() > 2) {
5901 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07005902 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005903 intervalIdx++);
5904
5905 size_t intervalValIdx = intervalIdx + 1;
5906 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07005907 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005908 if (errno) { return BAD_VALUE; }
5909 }
5910 }
5911
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005912 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5913 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005914
Avichal Rakesh84147132021-11-11 17:47:11 -08005915 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07005916 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005917
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005918 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005919 bool serviceLock = tryLock(mServiceLock);
5920 auto cameraClients = mActiveClientManager.getAll();
5921 if (serviceLock) { mServiceLock.unlock(); }
5922
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005923 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005924 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005925 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005926
5927 sp<BasicClient> client = clientDescriptor->getValue();
5928 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005929 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005930
Austin Borgered99f642023-06-01 16:51:35 -07005931 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08005932 // This also initializes the map entries with an empty string
5933 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5934
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005935 std::vector<std::string> latestEvents;
5936 client->dumpWatchedEventsToVector(latestEvents);
5937
5938 if (!latestEvents.empty()) {
5939 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005940 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08005941 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005942 latestEvents,
5943 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005944 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005945 }
5946 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005947 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005948 break;
5949 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005950 }
5951 return OK;
5952}
5953
Austin Borgered99f642023-06-01 16:51:35 -07005954void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005955 mWatchedClientPackages.clear();
5956
Austin Borgered99f642023-06-01 16:51:35 -07005957 std::istringstream iss(clients);
5958 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005959
Austin Borgered99f642023-06-01 16:51:35 -07005960 while (std::getline(iss, nextClient, ',')) {
5961 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005962 // Don't need to track any other package if 'all' is present
5963 mWatchedClientPackages.clear();
5964 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5965 break;
5966 }
5967
5968 // track package names
5969 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005970 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005971}
5972
Svet Ganova453d0d2018-01-11 15:37:58 -08005973status_t CameraService::printHelp(int out) {
5974 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005975 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5976 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5977 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005978 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5979 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5980 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005981 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
5982 " Valid values 0=false, 1=true, 2=auto\n"
5983 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005984 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
5985 " Valid values 0=OFF, 1=ON for JPEG\n"
5986 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005987 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08005988 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
5989 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
5990 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
5991 " on. In case the number of usecases is smaller than the number of streams, the\n"
5992 " last use case is assigned to all the remaining streams. In case of multiple\n"
5993 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
5994 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
5995 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
5996 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005997 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
5998 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
malikakash82ed4352023-07-21 22:44:34 +00005999 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006000 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006001 " help print this message\n");
6002}
6003
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006004bool CameraService::isClientWatched(const BasicClient *client) {
6005 Mutex::Autolock lock(mLogLock);
6006 return isClientWatchedLocked(client);
6007}
6008
6009bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6010 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6011 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6012}
6013
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006014int32_t CameraService::updateAudioRestriction() {
6015 Mutex::Autolock lock(mServiceLock);
6016 return updateAudioRestrictionLocked();
6017}
6018
6019int32_t CameraService::updateAudioRestrictionLocked() {
6020 int32_t mode = 0;
6021 // iterate through all active client
6022 for (const auto& i : mActiveClientManager.getAll()) {
6023 const auto clientSp = i->getValue();
6024 mode |= clientSp->getAudioRestriction();
6025 }
6026
6027 bool modeChanged = (mAudioRestriction != mode);
6028 mAudioRestriction = mode;
6029 if (modeChanged) {
6030 mAppOps.setCameraAudioRestriction(mode);
6031 }
6032 return mode;
6033}
6034
Austin Borgered99f642023-06-01 16:51:35 -07006035status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006036 sp<BasicClient> clientSp) {
6037 std::unique_ptr<AutoConditionLock> lock =
6038 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6039 status_t res = NO_ERROR;
6040 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006041 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006042 mInjectionStatusListener->notifyInjectionError(
6043 externalCamId, UNKNOWN_TRANSACTION);
6044 clientSp->notifyError(
6045 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6046 CaptureResultExtras());
6047
6048 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6049 // other clients from connecting in mServiceLockWrapper if held
6050 mServiceLock.unlock();
6051
6052 // Clear caller identity temporarily so client disconnect PID checks work correctly
6053 int64_t token = CameraThreadState::clearCallingIdentity();
6054 clientSp->disconnect();
6055 CameraThreadState::restoreCallingIdentity(token);
6056
6057 // Reacquire mServiceLock
6058 mServiceLock.lock();
6059 }
6060
6061 return res;
6062}
6063
Cliff Wud3a05312021-04-26 23:07:31 +08006064void CameraService::clearInjectionParameters() {
6065 {
6066 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006067 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006068 mInjectionInternalCamId = "";
6069 }
6070 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006071 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006072}
6073
Mathias Agopian65ab4712010-07-14 17:59:35 -07006074}; // namespace android