blob: 31ac39274d0c1c9a87ca478acfa4d1ad93aabb04 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Joanne Chung02c13d02023-01-16 12:58:05 +000041#include <android/permission/PermissionChecker.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080042#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080043#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/MemoryBase.h>
46#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080049#include <binderthreadstate/CallerUtils.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070051#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080052#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080053#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070055#include "hidl/HidlCameraService.h"
56#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080057#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070058#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080060#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070062#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000063#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070064#include <utils/Errors.h>
65#include <utils/Log.h>
66#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070067#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080069#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080070#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080071#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070072#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000073#include <binder/IServiceManager.h>
74#include <binder/IActivityManager.h>
Austin Borgered99f642023-06-01 16:51:35 -070075#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080076
Ruben Brunkb2119af2014-05-09 19:57:56 -070077#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
79#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070080#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070081#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070082#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000083#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070084#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080087namespace {
88 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080089 const char* kActivityServiceName = "activity";
90 const char* kSensorPrivacyServiceName = "sensor_privacy";
91 const char* kAppopsServiceName = "appops";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080092}; // namespace anonymous
93
Mathias Agopian65ab4712010-07-14 17:59:35 -070094namespace android {
95
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080096using binder::Status;
Austin Borgerea931242021-12-13 23:10:41 +000097using namespace camera3;
Jayant Chowdharybe543d42018-08-15 13:16:14 -070098using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070099using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800100using hardware::ICamera;
101using hardware::ICameraClient;
102using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800103using hardware::camera2::ICameraInjectionCallback;
104using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800105using hardware::camera2::utils::CameraIdAndSessionConfiguration;
106using hardware::camera2::utils::ConcurrentCameraIdCombination;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800107
Mathias Agopian65ab4712010-07-14 17:59:35 -0700108// ----------------------------------------------------------------------------
109// Logging support -- this is for debugging only
110// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700111volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112
Steve Blockb8a80522011-12-20 16:23:08 +0000113#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
114#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700115
116static void setLogLevel(int level) {
117 android_atomic_write(level, &gLogLevel);
118}
119
120// ----------------------------------------------------------------------------
121
Austin Borgered99f642023-06-01 16:51:35 -0700122static const std::string sDumpPermission("android.permission.DUMP");
123static const std::string sManageCameraPermission("android.permission.MANAGE_CAMERA");
124static const std::string sCameraPermission("android.permission.CAMERA");
125static const std::string sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
126static const std::string
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700127 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Austin Borgered99f642023-06-01 16:51:35 -0700128static const std::string sCameraOpenCloseListenerPermission(
Shuzhen Wang695044d2020-03-06 09:02:23 -0800129 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Austin Borgered99f642023-06-01 16:51:35 -0700130static const std::string
Cliff Wud8cae102021-03-11 01:37:42 +0800131 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000132// Constant integer for FGS Logging, used to denote the API type for logger
133static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700134const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800135static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
136static constexpr int32_t kSystemNativeClientState =
137 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700138static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700139
Austin Borgered99f642023-06-01 16:51:35 -0700140const std::string CameraService::kOfflineDevice("offline-");
141const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700142
Rucha Katakward9ea6452021-05-06 11:57:16 -0700143// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700144static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700145
Austin Borger74fca042022-05-23 12:41:21 -0700146CameraService::CameraService(
147 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
148 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
149 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800150 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800151 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700152 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700153 mSoundRef(0), mInitialized(false),
154 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000155 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800156 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700157 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
158 if (mMemFd == -1) {
159 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
160 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700161}
162
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800163// The word 'System' here does not refer to clients only on the system
164// partition. They just need to have a android system uid.
165static bool doesClientHaveSystemUid() {
166 return (CameraThreadState::getCallingUid() < AID_APP_START);
167}
168
Charles Chena7b613c2023-01-24 21:57:33 +0000169// Enable processes with isolated AID to request the binder
170void CameraService::instantiate() {
171 CameraService::publish(true);
172}
173
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800174void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700175 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800176 return;
177 }
178
179 ALOGV("appops service registered. setting camera audio restriction");
180 mAppOps.setCameraAudioRestriction(mAudioRestriction);
181}
182
Iliyan Malchev8951a972011-04-14 16:55:59 -0700183void CameraService::onFirstRef()
184{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700185
Ruben Brunkcc776712015-02-17 20:18:47 -0800186 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800187
Iliyan Malchev8951a972011-04-14 16:55:59 -0700188 BnCameraService::onFirstRef();
189
Ruben Brunk99e69712015-05-26 17:25:07 -0700190 // Update battery life tracking if service is restarting
191 BatteryNotifier& notifier(BatteryNotifier::getInstance());
192 notifier.noteResetCamera();
193 notifier.noteResetFlashlight();
194
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800195 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800196
Emilian Peevf53f66e2017-04-11 14:29:43 +0100197 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800198 if (res == OK) {
199 mInitialized = true;
200 }
201
Svet Ganova453d0d2018-01-11 15:37:58 -0800202 mUidPolicy = new UidPolicy(this);
203 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800204 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
205 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800206 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800207
208 // appops function setCamerAudioRestriction uses getService which
209 // is blocking till the appops service is ready. To enable early
210 // boot availability for cameraservice, use checkService which is
211 // non blocking and register for notifications
212 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700213 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800214 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700215 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800216 } else {
217 mAppOps.setCameraAudioRestriction(mAudioRestriction);
218 }
219
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700220 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
221 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000222 // Deprecated, so it will fail to register on newer devices
223 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700224 __FUNCTION__);
225 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700226
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700227 if (!AidlCameraService::registerService(this)) {
228 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
229 }
230
Shuzhen Wang24b44152019-09-20 10:38:11 -0700231 // This needs to be last call in this function, so that it's as close to
232 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700233 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700234 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800235}
236
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800237status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800238 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100239
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800240 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000241 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800242 {
243 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800244
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800245 if (nullptr == mCameraProviderManager.get()) {
246 mCameraProviderManager = new CameraProviderManager();
247 res = mCameraProviderManager->initialize(this);
248 if (res != OK) {
249 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
250 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700251 logServiceError("Unable to initialize camera provider manager",
252 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800253 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100254 }
255 }
256
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800257
258 // Setup vendor tags before we call get_camera_info the first time
259 // because HAL might need to setup static vendor keys in get_camera_info
260 // TODO: maybe put this into CameraProviderManager::initialize()?
261 mCameraProviderManager->setUpVendorTags();
262
263 if (nullptr == mFlashlight.get()) {
264 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700265 }
266
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 res = mFlashlight->findFlashUnits();
268 if (res != OK) {
269 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
270 }
271
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000272 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800273 }
274
275
276 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700277 if (getCameraState(cameraId) == nullptr) {
278 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800279 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000280 if (unavailPhysicalIds.count(cameraId) > 0) {
281 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700282 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000283 }
284 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800285 }
286
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700287 // Derive primary rear/front cameras, and filter their charactierstics.
288 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700289 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700290 // Assume internal cameras are advertised from the same
291 // provider. If multiple providers are registered at different time,
292 // and each provider contains multiple internal color cameras, the current
293 // logic may filter the characteristics of more than one front/rear color
294 // cameras.
295 Mutex::Autolock l(mServiceLock);
296 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700297 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700298
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800299 return OK;
300}
301
Austin Borgered99f642023-06-01 16:51:35 -0700302void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700303 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800304 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800305 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700306 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
307 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000308 ALOGV("%s: Skipping torch callback for system-only camera device %s",
309 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700310 continue;
311 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700312 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700313 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700314 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
315 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000316 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
317 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700318 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000319 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
320 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700321 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000322 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
323 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
324 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800325 }
326}
327
Mathias Agopian65ab4712010-07-14 17:59:35 -0700328CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800329 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800330 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800331 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800332 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700333}
334
Emilian Peevaee727d2017-05-04 16:35:48 +0100335void CameraService::onNewProviderRegistered() {
336 enumerateProviders();
337}
338
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700339void CameraService::filterAPI1SystemCameraLocked(
340 const std::vector<std::string> &normalDeviceIds) {
341 mNormalDeviceIdsWithoutSystemCamera.clear();
342 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700343 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700344 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700345 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
346 continue;
347 }
348 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700349 // All system camera ids will necessarily come after public camera
350 // device ids as per the HAL interface contract.
351 break;
352 }
353 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
354 }
355 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
356 mNormalDeviceIdsWithoutSystemCamera.size());
357}
358
Austin Borgered99f642023-06-01 16:51:35 -0700359status_t CameraService::getSystemCameraKind(const std::string& cameraId,
360 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700361 auto state = getCameraState(cameraId);
362 if (state != nullptr) {
363 *kind = state->getSystemCameraKind();
364 return OK;
365 }
366 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700367 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700368}
369
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800370void CameraService::updateCameraNumAndIds() {
371 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700372 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
373 // Excludes hidden secure cameras
374 mNumberOfCameras =
375 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
376 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800377 mNormalDeviceIds =
378 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700379 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800380}
381
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700382void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700383 // To claim to be S Performance primary cameras, the cameras must be
384 // backward compatible. So performance class primary camera Ids must be API1
385 // compatible.
386 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
387 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
388 int facing = -1;
389 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800390 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700391 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800392 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700393 if (facing == -1) {
394 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
395 return;
396 }
397
398 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
399 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700400 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
401 if (res == OK) {
402 mPerfClassPrimaryCameraIds.insert(cameraId);
403 } else {
404 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
405 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
406 break;
407 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700408
409 if (facing == hardware::CAMERA_FACING_BACK) {
410 firstRearCameraSeen = true;
411 }
412 if (facing == hardware::CAMERA_FACING_FRONT) {
413 firstFrontCameraSeen = true;
414 }
415 }
416
417 if (firstRearCameraSeen && firstFrontCameraSeen) {
418 break;
419 }
420 }
421}
422
Austin Borgered99f642023-06-01 16:51:35 -0700423void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700424 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100425 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
426 if (res != OK) {
427 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
428 return;
429 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000430 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700431 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
432 if (res != OK) {
433 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
434 return;
435 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000436 std::vector<std::string> physicalCameraIds;
437 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700438 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100439 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700440 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100441 }
442
443 {
444 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700445 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000446 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100447 }
448
Austin Borgered99f642023-06-01 16:51:35 -0700449 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100450 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700451 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800452
Austin Borgered99f642023-06-01 16:51:35 -0700453 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100454 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800455
456 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700457 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100458}
459
Austin Borgered99f642023-06-01 16:51:35 -0700460void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800461 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700462 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100463 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700464 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100465 }
466
467 {
468 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700469 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100470 }
471}
472
Austin Borgered99f642023-06-01 16:51:35 -0700473void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800474 CameraDeviceStatus newHalStatus) {
475 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700476 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700477
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800478 StatusInternal newStatus = mapToInternal(newHalStatus);
479
Austin Borgered99f642023-06-01 16:51:35 -0700480 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800481
482 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700483 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100484 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700485 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100486
487 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700488 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100489
Austin Borgered99f642023-06-01 16:51:35 -0700490 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700491 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700492 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700493 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700494 return;
495 }
496
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800497 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800498
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800499 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800500 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700501 return;
502 }
503
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800504 if (newStatus == StatusInternal::NOT_PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -0700505 logDeviceRemoved(cameraId, fmt::sprintf("Device status changed from %d to %d", oldStatus,
Ruben Brunka8ca9152015-04-07 14:23:40 -0700506 newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800507
508 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
509 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700510 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800511
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800512 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700513 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800514 // Don't do this in updateStatus to avoid deadlock over mServiceLock
515 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700516
Ruben Brunkcc776712015-02-17 20:18:47 -0800517 // Remove cached shim parameters
518 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700519
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800520 // Remove online as well as offline client from the list of active clients,
521 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700522 clientToDisconnectOnline = removeClientLocked(cameraId);
523 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700524 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800525
Austin Borgered99f642023-06-01 16:51:35 -0700526 disconnectClient(cameraId, clientToDisconnectOnline);
527 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700528
Austin Borgered99f642023-06-01 16:51:35 -0700529 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800530 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800531 if (oldStatus == StatusInternal::NOT_PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -0700532 logDeviceAdded(cameraId, fmt::sprintf("Device status changed from %d to %d", oldStatus,
Ruben Brunka8ca9152015-04-07 14:23:40 -0700533 newStatus));
534 }
Austin Borgered99f642023-06-01 16:51:35 -0700535 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700536 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800537}
Igor Murashkincba2c162013-03-20 15:56:31 -0700538
Austin Borgered99f642023-06-01 16:51:35 -0700539void CameraService::onDeviceStatusChanged(const std::string& id,
540 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800541 CameraDeviceStatus newHalStatus) {
542 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700543 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800544
545 StatusInternal newStatus = mapToInternal(newHalStatus);
546
547 std::shared_ptr<CameraState> state = getCameraState(id);
548
549 if (state == nullptr) {
550 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700551 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800552 return;
553 }
554
555 StatusInternal logicalCameraStatus = state->getStatus();
556 if (logicalCameraStatus != StatusInternal::PRESENT &&
557 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
558 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700559 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800560 return;
561 }
562
563 bool updated = false;
564 if (newStatus == StatusInternal::PRESENT) {
565 updated = state->removeUnavailablePhysicalId(physicalId);
566 } else {
567 updated = state->addUnavailablePhysicalId(physicalId);
568 }
569
570 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700571 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800572 if (newStatus == StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -0700573 logDeviceAdded(idCombo, fmt::sprintf("Device status changed to %d", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800574 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700575 logDeviceRemoved(idCombo, fmt::sprintf("Device status changed to %d", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800576 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700577 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
578 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
579 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700580 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700581 return;
582 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800583 Mutex::Autolock lock(mStatusListenerLock);
584 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700585 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
586 listener->getListenerPid(), listener->getListenerUid())) {
587 ALOGV("Skipping discovery callback for system-only camera device %s",
588 id.c_str());
589 continue;
590 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700591 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700592 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700593 listener->handleBinderStatus(ret,
594 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
595 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
596 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800597 }
598 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700599}
600
Austin Borgered99f642023-06-01 16:51:35 -0700601void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800602 if (clientToDisconnect.get() != nullptr) {
603 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700604 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800605 // Notify the client of disconnection
606 clientToDisconnect->notifyError(
607 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
608 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800609 clientToDisconnect->disconnect();
610 }
611}
612
Austin Borgered99f642023-06-01 16:51:35 -0700613void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800614 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700615 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
616 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
617 if (res != OK) {
618 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700619 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700620 return;
621 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800622 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700623 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800624}
625
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700626
Austin Borgered99f642023-06-01 16:51:35 -0700627void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700628 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
629 Mutex::Autolock al(mTorchStatusMutex);
630 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
631}
632
Austin Borgered99f642023-06-01 16:51:35 -0700633void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800634 int32_t newStrengthLevel) {
635 Mutex::Autolock lock(mStatusListenerLock);
636 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700637 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700638 i->handleBinderStatus(ret,
639 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
640 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800641 }
642}
643
Austin Borgered99f642023-06-01 16:51:35 -0700644void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700645 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800646 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700647 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800648
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800649 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800650 status_t res = getTorchStatusLocked(cameraId, &status);
651 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700652 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700653 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800654 return;
655 }
656 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800657 return;
658 }
659
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800660 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800661 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800662 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
663 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664 return;
665 }
666
Ruben Brunkcc776712015-02-17 20:18:47 -0800667 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700668 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700669 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700670 auto iter = mTorchUidMap.find(cameraId);
671 if (iter != mTorchUidMap.end()) {
672 int oldUid = iter->second.second;
673 int newUid = iter->second.first;
674 BatteryNotifier& notifier(BatteryNotifier::getInstance());
675 if (oldUid != newUid) {
676 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800677 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700678 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700679 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800680 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700681 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700682 }
683 iter->second.second = newUid;
684 } else {
685 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800686 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700687 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700688 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700689 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700690 }
691 }
692 }
693 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700694 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800695}
696
Joanne Chung02c13d02023-01-16 12:58:05 +0000697static bool hasPermissionsForSystemCamera(int callingPid, int callingUid) {
698 permission::PermissionChecker permissionChecker;
699 AttributionSourceState attributionSource{};
700 attributionSource.pid = callingPid;
701 attributionSource.uid = callingUid;
702 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700703 toString16(sSystemCameraPermission), attributionSource, String16(),
704 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000705 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700706 toString16(sCameraPermission), attributionSource, String16(),
707 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000708 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700709}
710
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800711Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700712 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100713 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700714 bool hasSystemCameraPermissions =
715 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
716 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700717 switch (type) {
718 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700719 if (hasSystemCameraPermissions) {
720 *numCameras = static_cast<int>(mNormalDeviceIds.size());
721 } else {
722 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
723 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800724 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700725 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700726 if (hasSystemCameraPermissions) {
727 *numCameras = mNumberOfCameras;
728 } else {
729 *numCameras = mNumberOfCamerasWithoutSystemCamera;
730 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800731 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700732 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800733 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700734 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800735 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
736 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700737 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800738 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700739}
740
malikakash82ed4352023-07-21 22:44:34 +0000741Status CameraService::remapCameraIds(const hardware::CameraIdRemapping&
742 cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700743 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000744 const int pid = CameraThreadState::getCallingPid();
745 const int uid = CameraThreadState::getCallingUid();
746 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
747 __FUNCTION__, pid, uid);
748 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
749 "Permission Denial: no permission to configure camera id mapping");
750 }
751 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000752 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000753 if (!parseStatus.isOk()) {
754 return parseStatus;
755 }
756 remapCameraIds(cameraIdRemappingMap);
757 return Status::ok();
758}
759
760Status CameraService::parseCameraIdRemapping(
761 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +0000762 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700763 std::string packageName;
764 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +0000765 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +0000766 packageName = packageIdRemapping.packageName;
Austin Borgered99f642023-06-01 16:51:35 -0700767 if (packageName == "") {
malikakash82ed4352023-07-21 22:44:34 +0000768 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
769 "CameraIdRemapping: Package name cannot be empty");
770 }
malikakash214f6e62023-08-10 23:50:56 +0000771
772 if (packageIdRemapping.cameraIdsToReplace.size()
773 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +0000774 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
775 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700776 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +0000777 }
malikakash214f6e62023-08-10 23:50:56 +0000778 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700779 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
780 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
781 if (cameraIdToReplace == "" || updatedCameraId == "") {
malikakash214f6e62023-08-10 23:50:56 +0000782 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
783 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700784 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000785 }
786 if (cameraIdToReplace == updatedCameraId) {
787 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
788 "CameraIdRemapping: CameraIdToReplace cannot be the same"
789 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -0700790 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000791 }
792 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +0000793 }
794 }
795 return Status::ok();
796}
797
798void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
799 // Acquire mServiceLock and prevent other clients from connecting
800 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
801 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
802
malikakashedb38962023-09-06 00:03:35 +0000803 // Collect all existing clients for camera Ids that are being
804 // remapped in the new cameraIdRemapping, but only if they were being used by a
805 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +0000806 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -0700807 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +0000808 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
809 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700810 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +0000811 id0.c_str(), id1.c_str());
812 auto clientDescriptor = mActiveClientManager.get(id0);
813 if (clientDescriptor != nullptr) {
814 sp<BasicClient> clientSp = clientDescriptor->getValue();
815 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +0000816 // This camera is being used by a targeted packageName and
817 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +0000818 clientsToDisconnect.push_back(clientSp);
819 cameraIdsToUpdate.push_back(id0);
820 }
821 }
822 }
823 }
824
malikakashedb38962023-09-06 00:03:35 +0000825 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +0000826 // Notify the clients about the disconnection.
827 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +0000828 CaptureResultExtras{});
829 }
malikakash82ed4352023-07-21 22:44:34 +0000830
831 // Do not hold mServiceLock while disconnecting clients, but retain the condition
832 // blocking other clients from connecting in mServiceLockWrapper if held.
833 mServiceLock.unlock();
834
malikakashedb38962023-09-06 00:03:35 +0000835 // Clear calling identity for disconnect() PID checks.
836 int64_t token = CameraThreadState::clearCallingIdentity();
837
malikakash82ed4352023-07-21 22:44:34 +0000838 // Disconnect clients.
839 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +0000840 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
841 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +0000842 clientSp->disconnect();
843 }
844
malikakashedb38962023-09-06 00:03:35 +0000845 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
846 clientsToDisconnect.clear();
847
848 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +0000849 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +0000850
851 {
852 Mutex::Autolock lock(mCameraIdRemappingLock);
853 // Update mCameraIdRemapping.
854 mCameraIdRemapping.clear();
855 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
856 }
malikakash82ed4352023-07-21 22:44:34 +0000857}
858
Austin Borgered99f642023-06-01 16:51:35 -0700859std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
860 const std::string& inputCameraId, int clientUid) {
861 std::string packageName = getPackageNameFromUid(clientUid);
862 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +0000863 Mutex::Autolock lock(mCameraIdRemappingLock);
864 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
865 packageMapIter != mCameraIdRemapping.end()) {
866 for (auto& [id0, id1]: packageMapIter->second) {
867 if (id1 == inputCameraId) {
868 cameraIds.push_back(id0);
869 }
870 }
871 }
872 return cameraIds;
873}
874
Austin Borgered99f642023-06-01 16:51:35 -0700875std::string CameraService::resolveCameraId(
876 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +0000877 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -0700878 const std::string& packageName) {
879 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +0000880 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +0000881 packageNameVal = getPackageNameFromUid(clientUid);
882 }
malikakashedb38962023-09-06 00:03:35 +0000883 if (clientUid < AID_APP_START || packageNameVal.empty()) {
884 // We shouldn't remap cameras for processes with system/vendor UIDs.
885 return inputCameraId;
886 }
malikakash82ed4352023-07-21 22:44:34 +0000887 Mutex::Autolock lock(mCameraIdRemappingLock);
888 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
889 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +0000890 auto packageMap = packageMapIter->second;
891 if (auto replacementIdIter = packageMap.find(inputCameraId);
892 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +0000893 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +0000894 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +0000895 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +0000896 replacementIdIter->second.c_str());
897 return replacementIdIter->second;
898 }
899 }
900 return inputCameraId;
901}
902
Austin Borger18b30a72022-10-27 12:20:29 -0700903Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800904 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700905 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100906 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +0000907 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
908 std::string cameraIdStr = resolveCameraId(
909 unresolvedCameraId, CameraThreadState::getCallingUid());
910
Austin Borgered99f642023-06-01 16:51:35 -0700911 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700912 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
913 "characteristics for system only device %s: ", cameraIdStr.c_str());
914 }
Emilian Peevaee727d2017-05-04 16:35:48 +0100915
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800916 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -0700917 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800918 return STATUS_ERROR(ERROR_DISCONNECTED,
919 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -0700920 }
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700921 bool hasSystemCameraPermissions =
922 hasPermissionsForSystemCamera(CameraThreadState::getCallingPid(),
923 CameraThreadState::getCallingUid());
924 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
925 if (hasSystemCameraPermissions) {
926 cameraIdBound = mNumberOfCameras;
927 }
928 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800929 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
930 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -0700931 }
932
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800933 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -0700934 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800935 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -0700936 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +0100937 if (err != OK) {
938 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
939 "Error retrieving camera info from device %d: %s (%d)", cameraId,
940 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -0700941 logServiceError(std::string("Error retrieving camera info from device ")
942 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -0800943 }
Emilian Peevf53f66e2017-04-11 14:29:43 +0100944
Ruben Brunkcc776712015-02-17 20:18:47 -0800945 return ret;
946}
Ruben Brunkb2119af2014-05-09 19:57:56 -0700947
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800948std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700949 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
950 auto callingPid = CameraThreadState::getCallingPid();
951 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +0000952 permission::PermissionChecker permissionChecker;
953 AttributionSourceState attributionSource{};
954 attributionSource.pid = callingPid;
955 attributionSource.uid = callingUid;
956 bool checkPermissionForSystemCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -0700957 toString16(sSystemCameraPermission), attributionSource, String16(),
958 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +0000959 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700960 deviceIds = &mNormalDeviceIds;
961 }
962 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800963 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700964 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800965 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800966 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800967
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700968 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800969}
970
Austin Borgered99f642023-06-01 16:51:35 -0700971std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800972 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -0700973 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800974}
975
Austin Borgered99f642023-06-01 16:51:35 -0700976Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -0700977 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700978 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -0700979
malikakashedb38962023-09-06 00:03:35 +0000980 const std::string cameraId = resolveCameraId(unresolvedCameraId,
981 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -0700982
Zhijun He2b59be82013-09-25 10:14:30 -0700983 if (!cameraInfo) {
984 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800985 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -0700986 }
987
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800988 if (!mInitialized) {
989 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -0700990 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800991 return STATUS_ERROR(ERROR_DISCONNECTED,
992 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -0700993 }
994
Austin Borgered99f642023-06-01 16:51:35 -0700995 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700996 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -0700997 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700998 }
999
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001000 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001001
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001002 bool overrideForPerfClass =
1003 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001004 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001005 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001006 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001007 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001008 if (res == NAME_NOT_FOUND) {
1009 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001010 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001011 strerror(-res), res);
1012 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001013 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1014 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001015 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001016 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001017 strerror(-res), res);
1018 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001019 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001020 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001021 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1022 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001023 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001024 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001025 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001026 int callingPid = CameraThreadState::getCallingPid();
1027 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001028 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001029 // If it's not calling from cameraserver, check the permission only if
1030 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1031 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +00001032 permission::PermissionChecker permissionChecker;
1033 AttributionSourceState attributionSource{};
1034 attributionSource.pid = callingPid;
1035 attributionSource.uid = callingUid;
1036 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001037 toString16(sCameraPermission), attributionSource, String16(),
1038 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Emilian Peeve20c6372018-08-14 18:45:53 +01001039 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001040 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001041 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001042 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001043 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001044 &tagsRemoved);
1045 if (res != OK) {
1046 cameraInfo->clear();
1047 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1048 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001049 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001050 }
1051 }
1052
1053 if (!tagsRemoved.empty()) {
1054 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1055 tagsRemoved.data(), tagsRemoved.size());
1056 if (res != OK) {
1057 cameraInfo->clear();
1058 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001059 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001060 strerror(-res), res);
1061 }
1062 }
1063
Zhijun He2b59be82013-09-25 10:14:30 -07001064 return ret;
1065}
1066
malikakashedb38962023-09-06 00:03:35 +00001067Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001068 int32_t* torchStrength) {
1069 ATRACE_CALL();
1070 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001071 const std::string cameraId = resolveCameraId(
1072 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001073 if (!mInitialized) {
1074 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1075 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1076 }
1077
1078 if(torchStrength == NULL) {
1079 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1080 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1081 }
1082
Austin Borgered99f642023-06-01 16:51:35 -07001083 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001084 if (res != OK) {
1085 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001086 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001087 strerror(-res), res);
1088 }
1089 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1090 return Status::ok();
1091}
1092
Austin Borgered99f642023-06-01 16:51:35 -07001093std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001094 time_t now = time(nullptr);
1095 char formattedTime[64];
1096 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001097 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001098}
1099
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001100Status CameraService::getCameraVendorTagDescriptor(
1101 /*out*/
1102 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001103 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001104 if (!mInitialized) {
1105 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001106 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001107 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001108 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1109 if (globalDescriptor != nullptr) {
1110 *desc = *(globalDescriptor.get());
1111 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001112 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001113}
1114
Emilian Peev71c73a22017-03-21 16:35:51 +00001115Status CameraService::getCameraVendorTagCache(
1116 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1117 ATRACE_CALL();
1118 if (!mInitialized) {
1119 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1120 return STATUS_ERROR(ERROR_DISCONNECTED,
1121 "Camera subsystem not available");
1122 }
1123 sp<VendorTagDescriptorCache> globalCache =
1124 VendorTagDescriptorCache::getGlobalVendorTagCache();
1125 if (globalCache != nullptr) {
1126 *cache = *(globalCache.get());
1127 }
1128 return Status::ok();
1129}
1130
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001131void CameraService::clearCachedVariables() {
1132 BasicClient::BasicClient::sCameraService = nullptr;
1133}
1134
Austin Borgered99f642023-06-01 16:51:35 -07001135std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001136 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001137 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001138
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001139 int deviceVersion = 0;
1140
Emilian Peevf53f66e2017-04-11 14:29:43 +01001141 status_t res;
1142 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001143 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001144 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001145 if (res != OK || transport == IPCTransport::INVALID) {
1146 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001147 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001148 return std::make_pair(-1, IPCTransport::INVALID) ;
1149 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001150 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001151
Emilian Peevf53f66e2017-04-11 14:29:43 +01001152 hardware::CameraInfo info;
1153 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001154 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001155 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001156 if (res != OK) {
1157 return std::make_pair(-1, IPCTransport::INVALID);
1158 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001159 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001160 if (orientation) {
1161 *orientation = info.orientation;
1162 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001163 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001164
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001165 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001166}
1167
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001168Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001169 switch(err) {
1170 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001171 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001172 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001173 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1174 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001175 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001176 return STATUS_ERROR(ERROR_DISCONNECTED,
1177 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001178 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001179 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1180 "Camera HAL encountered error %d: %s",
1181 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001182 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001183}
1184
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001185Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001186 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1187 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001188 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001189 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001190 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
Austin Borgered99f642023-06-01 16:51:35 -07001191 bool forceSlowJpegMode, const std::string& originalCameraId, /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001192 // For HIDL devices
1193 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1194 // Create CameraClient based on device version reported by the HAL.
1195 int deviceVersion = deviceVersionAndTransport.first;
1196 switch(deviceVersion) {
1197 case CAMERA_DEVICE_API_VERSION_1_0:
1198 ALOGE("Camera using old HAL version: %d", deviceVersion);
1199 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1200 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001201 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001202 break;
1203 case CAMERA_DEVICE_API_VERSION_3_0:
1204 case CAMERA_DEVICE_API_VERSION_3_1:
1205 case CAMERA_DEVICE_API_VERSION_3_2:
1206 case CAMERA_DEVICE_API_VERSION_3_3:
1207 case CAMERA_DEVICE_API_VERSION_3_4:
1208 case CAMERA_DEVICE_API_VERSION_3_5:
1209 case CAMERA_DEVICE_API_VERSION_3_6:
1210 case CAMERA_DEVICE_API_VERSION_3_7:
1211 break;
1212 default:
1213 // Should not be reachable
1214 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1215 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1216 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001217 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001218 }
1219 }
1220 if (effectiveApiLevel == API_1) { // Camera1 API route
1221 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001222 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borgered99f642023-06-01 16:51:35 -07001223 packageName, featureId, cameraId,
1224 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001225 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1226 forceSlowJpegMode);
1227 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1228 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001229 } else { // Camera2 API route
1230 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1231 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001232 *client = new CameraDeviceClient(cameraService, tmp,
1233 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1234 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001235 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001236 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001237 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001238 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001239}
1240
Austin Borgered99f642023-06-01 16:51:35 -07001241std::string CameraService::toString(std::set<userid_t> intSet) {
1242 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001243 bool first = true;
1244 for (userid_t i : intSet) {
1245 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001246 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001247 first = false;
1248 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001249 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001250 }
1251 }
Austin Borgered99f642023-06-01 16:51:35 -07001252 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001253}
1254
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001255int32_t CameraService::mapToInterface(TorchModeStatus status) {
1256 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1257 switch (status) {
1258 case TorchModeStatus::NOT_AVAILABLE:
1259 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1260 break;
1261 case TorchModeStatus::AVAILABLE_OFF:
1262 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1263 break;
1264 case TorchModeStatus::AVAILABLE_ON:
1265 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1266 break;
1267 default:
1268 ALOGW("Unknown new flash status: %d", status);
1269 }
1270 return serviceStatus;
1271}
1272
1273CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1274 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1275 switch (status) {
1276 case CameraDeviceStatus::NOT_PRESENT:
1277 serviceStatus = StatusInternal::NOT_PRESENT;
1278 break;
1279 case CameraDeviceStatus::PRESENT:
1280 serviceStatus = StatusInternal::PRESENT;
1281 break;
1282 case CameraDeviceStatus::ENUMERATING:
1283 serviceStatus = StatusInternal::ENUMERATING;
1284 break;
1285 default:
1286 ALOGW("Unknown new HAL device status: %d", status);
1287 }
1288 return serviceStatus;
1289}
1290
1291int32_t CameraService::mapToInterface(StatusInternal status) {
1292 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1293 switch (status) {
1294 case StatusInternal::NOT_PRESENT:
1295 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1296 break;
1297 case StatusInternal::PRESENT:
1298 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1299 break;
1300 case StatusInternal::ENUMERATING:
1301 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1302 break;
1303 case StatusInternal::NOT_AVAILABLE:
1304 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1305 break;
1306 case StatusInternal::UNKNOWN:
1307 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1308 break;
1309 default:
1310 ALOGW("Unknown new internal device status: %d", status);
1311 }
1312 return serviceStatus;
1313}
1314
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001315Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001316 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001317
Austin Borgered99f642023-06-01 16:51:35 -07001318 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001319 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001320 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001321 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001322 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1323 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001324 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001325 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001326 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001327 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001328 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001329 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001330 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001331}
1332
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001333Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001334 /*out*/
1335 CameraParameters* parameters) {
1336
1337 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1338
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001339 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001340
1341 if (parameters == NULL) {
1342 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001343 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001344 }
1345
malikakashedb38962023-09-06 00:03:35 +00001346 std::string unresolvedCameraId = std::to_string(cameraId);
1347 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1348 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001349
1350 // Check if we already have parameters
1351 {
1352 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001353 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001354 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001355 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001356 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001357 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001358 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001359 }
1360 CameraParameters p = cameraState->getShimParams();
1361 if (!p.isEmpty()) {
1362 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001363 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001364 }
1365 }
1366
Jayant Chowdhary12361932018-08-27 14:46:13 -07001367 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001368 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001369 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001370 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001371 // Error already logged by callee
1372 return ret;
1373 }
1374
1375 // Check for parameters again
1376 {
1377 // Scope for service lock
1378 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001379 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001380 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001381 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001382 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001383 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001384 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001385 CameraParameters p = cameraState->getShimParams();
1386 if (!p.isEmpty()) {
1387 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001388 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001389 }
1390 }
1391
Ruben Brunkcc776712015-02-17 20:18:47 -08001392 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1393 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001394 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001395}
1396
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001397// Can camera service trust the caller based on the calling UID?
1398static bool isTrustedCallingUid(uid_t uid) {
1399 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001400 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001401 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001402 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001403 return true;
1404 default:
1405 return false;
1406 }
1407}
1408
Austin Borgered99f642023-06-01 16:51:35 -07001409static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
1410 int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07001411 PermissionController pc;
Austin Borgered99f642023-06-01 16:51:35 -07001412 uid = pc.getPackageUid(toString16(packageName), 0);
Nicholas Sauera3620332019-04-03 14:05:17 -07001413 if (uid <= 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001414 ALOGE("Unknown package: '%s'", packageName.c_str());
1415 dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07001416 return BAD_VALUE;
1417 }
1418
1419 if (userId < 0) {
1420 ALOGE("Invalid user: %d", userId);
1421 dprintf(err, "Invalid user: %d\n", userId);
1422 return BAD_VALUE;
1423 }
1424
1425 uid = multiuser_get_uid(userId, uid);
1426 return NO_ERROR;
1427}
1428
Austin Borgered99f642023-06-01 16:51:35 -07001429Status CameraService::validateConnectLocked(const std::string& cameraId,
1430 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001431 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001432
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001433#ifdef __BRILLO__
1434 UNUSED(clientName8);
1435 UNUSED(clientUid);
1436 UNUSED(clientPid);
1437 UNUSED(originalClientPid);
1438#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001439 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1440 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001441 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001442 return allowed;
1443 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001444#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001445
Jayant Chowdhary12361932018-08-27 14:46:13 -07001446 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001447
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001448 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001449 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1450 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001451 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001452 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001453 }
1454
Ruben Brunkcc776712015-02-17 20:18:47 -08001455 if (getCameraState(cameraId) == nullptr) {
1456 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001457 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001458 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001459 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001460 }
1461
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001462 status_t err = checkIfDeviceIsUsable(cameraId);
1463 if (err != NO_ERROR) {
1464 switch(err) {
1465 case -ENODEV:
1466 case -EBUSY:
1467 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001468 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001469 default:
1470 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001471 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001472 }
1473 }
1474 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001475}
1476
Austin Borgered99f642023-06-01 16:51:35 -07001477Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1478 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001479 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001480 permission::PermissionChecker permissionChecker;
1481 AttributionSourceState attributionSource{};
1482
Jayant Chowdhary12361932018-08-27 14:46:13 -07001483 int callingPid = CameraThreadState::getCallingPid();
1484 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001485
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001486 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001487 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001488 clientUid = callingUid;
1489 } else if (!isTrustedCallingUid(callingUid)) {
1490 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1491 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001492 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1493 "Untrusted caller (calling PID %d, UID %d) trying to "
1494 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001495 callingPid, callingUid, cameraId.c_str(),
1496 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001497 }
1498
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001499 // Check if we can trust clientPid
1500 if (clientPid == USE_CALLING_PID) {
1501 clientPid = callingPid;
1502 } else if (!isTrustedCallingUid(callingUid)) {
1503 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1504 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001505 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1506 "Untrusted caller (calling PID %d, UID %d) trying to "
1507 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001508 callingPid, callingUid, cameraId.c_str(),
1509 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001510 }
1511
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001512 if (shouldRejectSystemCameraConnection(cameraId)) {
1513 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1514 cameraId.c_str());
1515 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001516 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001517 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001518 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1519 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001520 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001521 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001522 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001523
1524 }
1525
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001526 // If it's not calling from cameraserver, check the permission if the
1527 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1528 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001529 attributionSource.pid = clientPid;
1530 attributionSource.uid = clientUid;
Austin Borgered99f642023-06-01 16:51:35 -07001531 attributionSource.packageName = clientName;
Joanne Chung02c13d02023-01-16 12:58:05 +00001532 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07001533 toString16(sCameraPermission), attributionSource, String16(), AppOpsManager::OP_NONE)
Joanne Chung02c13d02023-01-16 12:58:05 +00001534 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001535 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001536 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001537 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001538 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1539 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001540 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001541 }
1542
Svet Ganova453d0d2018-01-11 15:37:58 -08001543 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001544 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001545 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001546 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1547 clientPid, clientUid);
1548 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001549 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1550 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001551 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001552 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001553 }
1554
Michael Grooverd1d435a2018-12-18 17:39:42 -08001555 // If sensor privacy is enabled then prevent access to the camera
1556 if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
1557 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1558 return STATUS_ERROR_FMT(ERROR_DISABLED,
1559 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001560 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001561 }
1562
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001563 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1564 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001565 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001566 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001567
Ruben Brunk6267b532015-04-30 17:44:07 -07001568 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001569
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001570 // For non-system clients : Only allow clients who are being used by the current foreground
1571 // device user, unless calling from our own process.
1572 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001573 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001574 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1575 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001576 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1578 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001579 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001580 }
1581
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001582 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001583}
1584
Austin Borgered99f642023-06-01 16:51:35 -07001585status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001586 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001587 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001588 if (cameraState == nullptr) {
1589 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001590 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001591 return -ENODEV;
1592 }
1593
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001594 StatusInternal currentStatus = cameraState->getStatus();
1595 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001596 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001597 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001598 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001599 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001600 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001601 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001602 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001603 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001604
Ruben Brunkcc776712015-02-17 20:18:47 -08001605 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001606}
1607
Ruben Brunkcc776712015-02-17 20:18:47 -08001608void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001609 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001610
Ruben Brunkcc776712015-02-17 20:18:47 -08001611 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001612 auto clientDescriptor =
1613 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001614 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001615 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1616
1617 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001618 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001619
1620 if (evicted.size() > 0) {
1621 // This should never happen - clients should already have been removed in disconnect
1622 for (auto& i : evicted) {
1623 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001624 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001625 }
1626
1627 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1628 __FUNCTION__);
1629 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001630
1631 // And register a death notification for the client callback. Do
1632 // this last to avoid Binder policy where a nested Binder
1633 // transaction might be pre-empted to service the client death
1634 // notification if the client process dies before linkToDeath is
1635 // invoked.
1636 sp<IBinder> remoteCallback = client->getRemote();
1637 if (remoteCallback != nullptr) {
1638 remoteCallback->linkToDeath(this);
1639 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001640}
1641
Austin Borgered99f642023-06-01 16:51:35 -07001642status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1643 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1644 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001645 /*out*/
1646 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001647 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001648 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001649 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001650 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001651 DescriptorPtr clientDescriptor;
1652 {
1653 if (effectiveApiLevel == API_1) {
1654 // If we are using API1, any existing client for this camera ID with the same remote
1655 // should be returned rather than evicted to allow MediaRecorder to work properly.
1656
1657 auto current = mActiveClientManager.get(cameraId);
1658 if (current != nullptr) {
1659 auto clientSp = current->getValue();
1660 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001661 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001662 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001663 " API level, evicting prior client...");
1664 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001665 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001666 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 *client = clientSp;
1668 return NO_ERROR;
1669 }
1670 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001671 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001672 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001673
Ruben Brunkcc776712015-02-17 20:18:47 -08001674 // Get current active client PIDs
1675 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1676 ownerPids.push_back(clientPid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08001677
Emilian Peev8131a262017-02-01 12:33:43 +00001678 std::vector<int> priorityScores(ownerPids.size());
1679 std::vector<int> states(ownerPids.size());
Igor Murashkine6800ce2013-03-04 17:25:57 -08001680
Emilian Peev8131a262017-02-01 12:33:43 +00001681 // Get priority scores of all active PIDs
1682 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(
1683 ownerPids.size(), &ownerPids[0], /*out*/&states[0],
1684 /*out*/&priorityScores[0]);
1685 if (err != OK) {
1686 ALOGE("%s: Priority score query failed: %d",
1687 __FUNCTION__, err);
1688 return err;
1689 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001690
Ruben Brunkcc776712015-02-17 20:18:47 -08001691 // Update all active clients' priorities
Emilian Peev8131a262017-02-01 12:33:43 +00001692 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
Ruben Brunkcc776712015-02-17 20:18:47 -08001693 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
Emilian Peev8131a262017-02-01 12:33:43 +00001694 pidToPriorityMap.emplace(ownerPids[i],
Jayant Chowdharyc578a502019-05-08 10:57:54 -07001695 resource_policy::ClientPriority(priorityScores[i], states[i],
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001696 /* isVendorClient won't get copied over*/ false,
1697 /* oomScoreOffset won't get copied over*/ 0));
Ruben Brunkcc776712015-02-17 20:18:47 -08001698 }
1699 mActiveClientManager.updatePriorities(pidToPriorityMap);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08001700
Ruben Brunkcc776712015-02-17 20:18:47 -08001701 // Get state for the given cameraId
1702 auto state = getCameraState(cameraId);
1703 if (state == nullptr) {
1704 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001705 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001706 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001707 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001708 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001709
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001710 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1711 int32_t actualState = states[states.size() - 1];
1712
1713 // Make descriptor for incoming client. We store the oomScoreOffset
1714 // since we might need it later on new handleEvictionsLocked and
1715 // ProcessInfoService would not take that into account.
Shuzhen Wang2db86ff2018-04-25 01:11:17 +00001716 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
Ruben Brunkcc776712015-02-17 20:18:47 -08001717 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001718 state->getConflicting(), actualScore, clientPid, actualState,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001719 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001720
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001721 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1722
Ruben Brunkcc776712015-02-17 20:18:47 -08001723 // Find clients that would be evicted
1724 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1725
1726 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1727 // background, so we cannot do evictions
1728 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1729 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1730 " priority).", clientPid);
1731
1732 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001733 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001734 auto incompatibleClients =
1735 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1736
Austin Borgered99f642023-06-01 16:51:35 -07001737 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1738 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1739 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001740 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001741
1742 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001743 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001744 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001745 i->getKey().c_str(),
1746 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001747 i->getOwnerId(), i->getPriority().getScore(),
1748 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001749 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07001750 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
1751 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001752 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001753 }
1754
1755 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001756 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001757 mEventLog.add(msg);
1758
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001759 auto current = mActiveClientManager.get(cameraId);
1760 if (current != nullptr) {
1761 return -EBUSY; // CAMERA_IN_USE
1762 } else {
1763 return -EUSERS; // MAX_CAMERAS_IN_USE
1764 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001765 }
1766
1767 for (auto& i : evicted) {
1768 sp<BasicClient> clientSp = i->getValue();
1769 if (clientSp.get() == nullptr) {
1770 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1771
1772 // TODO: Remove this
1773 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1774 __FUNCTION__);
1775 mActiveClientManager.remove(i);
1776 continue;
1777 }
1778
1779 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07001780 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001781 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08001782
Ruben Brunkcc776712015-02-17 20:18:47 -08001783 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07001784 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00001785 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
1786 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001787 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001788 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07001789 i->getPriority().getState(), cameraId.c_str(),
1790 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001791 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001792
1793 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001794 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08001795 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07001796 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001797 }
1798
Ruben Brunkcc776712015-02-17 20:18:47 -08001799 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
1800 // other clients from connecting in mServiceLockWrapper if held
1801 mServiceLock.unlock();
1802
1803 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07001804 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001805
1806 // Destroy evicted clients
1807 for (auto& i : evictedClients) {
1808 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001809 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08001810 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001811
Jayant Chowdhary12361932018-08-27 14:46:13 -07001812 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08001813
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001814 for (const auto& i : evictedClients) {
1815 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001816 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001817 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
1818 if (ret == TIMED_OUT) {
1819 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07001820 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
1821 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001822 return -EBUSY;
1823 }
1824 if (ret != NO_ERROR) {
1825 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07001826 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
1827 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001828 return ret;
1829 }
1830 }
1831
1832 evictedClients.clear();
1833
Ruben Brunkcc776712015-02-17 20:18:47 -08001834 // Once clients have been disconnected, relock
1835 mServiceLock.lock();
1836
1837 // Check again if the device was unplugged or something while we weren't holding mServiceLock
1838 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
1839 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001840 }
1841
Ruben Brunkcc776712015-02-17 20:18:47 -08001842 *partial = clientDescriptor;
1843 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001844}
1845
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001846Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08001847 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001848 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001849 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001850 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001851 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001852 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001853 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00001854 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001855 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001856 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001857
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001858 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001859 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001860
malikakashedb38962023-09-06 00:03:35 +00001861 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
1862 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1863 CameraThreadState::getCallingUid());
1864
Ruben Brunkcc776712015-02-17 20:18:47 -08001865 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001866 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
1867 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07001868 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07001869 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07001870
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001871 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07001872 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
1873 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08001874 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001875 }
1876
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001877 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00001878
1879 const sp<IServiceManager> sm(defaultServiceManager());
1880 const auto& mActivityManager = getActivityManager();
1881 if (mActivityManager) {
1882 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
1883 CameraThreadState::getCallingUid(),
1884 CameraThreadState::getCallingPid());
1885 }
1886
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001887 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001888}
1889
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001890bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
1891 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001892 // If the client is not a vendor client, don't add listener if
1893 // a) the camera is a publicly hidden secure camera OR
1894 // b) the camera is a system only camera and the client doesn't
1895 // have android.permission.SYSTEM_CAMERA permissions.
1896 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
1897 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
1898 !hasPermissionsForSystemCamera(clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08001899 return true;
1900 }
1901 return false;
1902}
1903
Austin Borgered99f642023-06-01 16:51:35 -07001904bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001905 // Rules for rejection:
1906 // 1) If cameraserver tries to access this camera device, accept the
1907 // connection.
1908 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001909 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001910 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
1911 // and the serving thread is a non hwbinder thread, the client must have
1912 // android.permission.SYSTEM_CAMERA permissions to connect.
1913
1914 int cPid = CameraThreadState::getCallingPid();
1915 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001916 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001917 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
1918 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001919 // This isn't a known camera ID, so it's not a system camera
1920 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
1921 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001922 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001923
1924 // (1) Cameraserver trying to connect, accept.
1925 if (CameraThreadState::getCallingPid() == getpid()) {
1926 return false;
1927 }
1928 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001929 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001930 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
1931 return true;
1932 }
1933 // (3) Here we only check for permissions if it is a system only camera device. This is since
1934 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
1935 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
1936 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001937 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001938 !hasPermissionsForSystemCamera(cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001939 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
1940 cameraId.c_str());
1941 return true;
1942 }
1943
1944 return false;
1945}
1946
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001947Status CameraService::connectDevice(
1948 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07001949 const std::string& unresolvedCameraId,
1950 const std::string& clientPackageName,
1951 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001952 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07001953 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08001954 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001955 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001956
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001957 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001958 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001959 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07001960 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001961 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001962 bool systemNativeClient = false;
1963 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
1964 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07001965 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
1966 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001967 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001968 }
malikakashedb38962023-09-06 00:03:35 +00001969 const std::string cameraId = resolveCameraId(
1970 unresolvedCameraId,
1971 CameraThreadState::getCallingUid(),
1972 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001973
1974 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001975 std::string msg =
1976 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
1977 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
1978 cameraId.c_str());
1979 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1980 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001981 }
1982
Austin Borger9bfa0a72022-08-03 17:50:40 -07001983 userid_t clientUserId = multiuser_get_user_id(clientUid);
1984 int callingUid = CameraThreadState::getCallingUid();
1985 if (clientUid == USE_CALLING_UID) {
1986 clientUserId = multiuser_get_user_id(callingUid);
1987 }
1988
1989 if (mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07001990 std::string msg = "Camera disabled by device policy";
1991 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1992 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07001993 }
1994
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001995 // enforce system camera permissions
1996 if (oomScoreOffset > 0 &&
Austin Borger86a588e2022-05-23 12:41:58 -07001997 !hasPermissionsForSystemCamera(callingPid, CameraThreadState::getCallingUid()) &&
1998 !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07001999 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002000 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002001 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2002 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2003 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002004 }
2005
Austin Borgered99f642023-06-01 16:51:35 -07002006 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2007 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002008 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
Chengfei Taobe683db2023-01-31 18:52:49 +00002009 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false,
Austin Borgered99f642023-06-01 16:51:35 -07002010 unresolvedCameraId, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002011
Austin Borgered99f642023-06-01 16:51:35 -07002012 if (!ret.isOk()) {
2013 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002014 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002015 }
2016
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002017 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002018 Mutex::Autolock lock(mServiceLock);
2019
2020 // Clear the previous cached logs and reposition the
2021 // file offset to beginning of the file to log new data.
2022 // If either truncate or lseek fails, close the previous file and create a new one.
2023 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2024 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2025 // Close the previous memfd.
2026 close(mMemFd);
2027 // If failure to wipe the data, then create a new file and
2028 // assign the new value to mMemFd.
2029 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2030 if (mMemFd == -1) {
2031 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2032 }
2033 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002034 const sp<IServiceManager> sm(defaultServiceManager());
2035 const auto& mActivityManager = getActivityManager();
2036 if (mActivityManager) {
2037 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2038 CameraThreadState::getCallingUid(),
2039 CameraThreadState::getCallingPid());
2040 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002041 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002042}
2043
Austin Borgered99f642023-06-01 16:51:35 -07002044std::string CameraService::getPackageNameFromUid(int clientUid) {
2045 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002046
2047 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002048 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002049 if (binder == 0) {
2050 ALOGE("Cannot get permission service");
2051 // Return empty package name and the further interaction
2052 // with camera will likely fail
2053 return packageName;
2054 }
2055
2056 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2057 Vector<String16> packages;
2058
2059 permCtrl->getPackagesForUid(clientUid, packages);
2060
2061 if (packages.isEmpty()) {
2062 ALOGE("No packages for calling UID %d", clientUid);
2063 // Return empty package name and the further interaction
2064 // with camera will likely fail
2065 return packageName;
2066 }
2067
2068 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002069 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002070
2071 return packageName;
2072}
2073
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002074template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002075Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2076 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2077 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002078 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002079 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002080 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002081 binder::Status ret = binder::Status::ok();
2082
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002083 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002084 std::string clientPackageName;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002085 if (clientPackageNameMaybe.size() <= 0) {
2086 // NDK calls don't come with package names, but we need one for various cases.
2087 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2088 // do exist. For all authentication cases, all packages under the same UID get the
2089 // same permissions, so picking any associated package name is sufficient. For some
2090 // other cases, this may give inaccurate names for clients in logs.
2091 isNonSystemNdk = true;
2092 int packageUid = (clientUid == USE_CALLING_UID) ?
2093 CameraThreadState::getCallingUid() : clientUid;
2094 clientPackageName = getPackageNameFromUid(packageUid);
2095 } else {
2096 clientPackageName = clientPackageNameMaybe;
2097 }
2098
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002099 int originalClientPid = 0;
2100
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002101 int packagePid = (clientPid == USE_CALLING_PID) ?
2102 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002103 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002104 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002105 static_cast<int>(effectiveApiLevel));
2106
Shuzhen Wang316781a2020-08-18 18:11:01 -07002107 nsecs_t openTimeNs = systemTime();
2108
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002109 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002110 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002111 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002112
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002113 {
2114 // Acquire mServiceLock and prevent other clients from connecting
2115 std::unique_ptr<AutoConditionLock> lock =
2116 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2117
2118 if (lock == nullptr) {
2119 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2120 , clientPid);
2121 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2122 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002123 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002124 }
2125
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002126 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002127 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002128 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2129 return ret;
2130 }
2131
2132 // Check the shim parameters after acquiring lock, if they have already been updated and
2133 // we were doing a shim update, return immediately
2134 if (shimUpdateOnly) {
2135 auto cameraState = getCameraState(cameraId);
2136 if (cameraState != nullptr) {
2137 if (!cameraState->getShimParams().isEmpty()) return ret;
2138 }
2139 }
2140
2141 status_t err;
2142
2143 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002144 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002145 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002146 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2147 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002148 switch (err) {
2149 case -ENODEV:
2150 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2151 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002152 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002153 case -EBUSY:
2154 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2155 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002156 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002157 case -EUSERS:
2158 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2159 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002160 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002161 default:
2162 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2163 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002164 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002165 }
2166 }
2167
2168 if (clientTmp.get() != nullptr) {
2169 // Handle special case for API1 MediaRecorder where the existing client is returned
2170 device = static_cast<CLIENT*>(clientTmp.get());
2171 return ret;
2172 }
2173
2174 // give flashlight a chance to close devices if necessary.
2175 mFlashlight->prepareDeviceOpen(cameraId);
2176
Austin Borger18b30a72022-10-27 12:20:29 -07002177 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002178 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002179 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2180 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002181 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002182 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002183 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002184 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002185 }
2186
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002187 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002188 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002189 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002190 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002191 clientFeatureId, cameraId, api1CameraId, facing,
2192 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002193 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002194 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002195 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002196 return ret;
2197 }
2198 client = static_cast<CLIENT*>(tmp.get());
2199
2200 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2201 __FUNCTION__);
2202
Austin Borgered99f642023-06-01 16:51:35 -07002203 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002204 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002205 if (err != OK) {
2206 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002207 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002208 mServiceLock.unlock();
2209 client->disconnect();
2210 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002211 switch(err) {
2212 case BAD_VALUE:
2213 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002214 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002215 case -EBUSY:
2216 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002217 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002218 case -EUSERS:
2219 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2220 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002221 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002222 case PERMISSION_DENIED:
2223 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002224 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002225 case -EACCES:
2226 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002227 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002228 case -ENODEV:
2229 default:
2230 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002231 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002232 strerror(-err), err);
2233 }
2234 }
2235
2236 // Update shim paremeters for legacy clients
2237 if (effectiveApiLevel == API_1) {
2238 // Assume we have always received a Client subclass for API1
2239 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2240 String8 rawParams = shimClient->getParameters();
2241 CameraParameters params(rawParams);
2242
2243 auto cameraState = getCameraState(cameraId);
2244 if (cameraState != nullptr) {
2245 cameraState->setShimParams(params);
2246 } else {
2247 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002248 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002249 }
2250 }
2251
Ravneetaeb20dc2022-03-30 05:33:03 +00002252 // Enable/disable camera service watchdog
2253 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2254
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002255 // Set rotate-and-crop override behavior
2256 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2257 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Austin Borger18b30a72022-10-27 12:20:29 -07002258 } else if (overrideToPortrait && portraitRotation != 0) {
2259 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2260 switch (portraitRotation) {
2261 case 90:
2262 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2263 break;
2264 case 180:
2265 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2266 break;
2267 case 270:
2268 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2269 break;
2270 default:
2271 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2272 break;
2273 }
2274 client->setRotateAndCropOverride(rotateAndCropMode);
Emilian Peev13f35ad2022-04-27 11:28:48 -07002275 } else {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002276 client->setRotateAndCropOverride(
2277 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2278 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2279 }
2280
2281 // Set autoframing override behaviour
2282 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2283 client->setAutoframingOverride(mOverrideAutoframingMode);
2284 } else {
2285 client->setAutoframingOverride(
2286 mCameraServiceProxyWrapper->getAutoframingOverride(
2287 clientPackageName));
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002288 }
2289
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002290 // Set camera muting behavior
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002291 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08002292 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002293 if (client->supportsCameraMute()) {
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002294 client->setCameraMute(
2295 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2296 } else if (isCameraPrivacyEnabled) {
2297 // no camera mute supported, but privacy is on! => disconnect
2298 ALOGI("Camera mute not supported for package: %s, camera id: %s",
Austin Borgered99f642023-06-01 16:51:35 -07002299 client->getPackageName().c_str(), cameraId.c_str());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002300 // Do not hold mServiceLock while disconnecting clients, but
2301 // retain the condition blocking other clients from connecting
2302 // in mServiceLockWrapper if held.
2303 mServiceLock.unlock();
2304 // Clear caller identity temporarily so client disconnect PID
2305 // checks work correctly
2306 int64_t token = CameraThreadState::clearCallingIdentity();
2307 // Note AppOp to trigger the "Unblock" dialog
2308 client->noteAppOp();
2309 client->disconnect();
2310 CameraThreadState::restoreCallingIdentity(token);
2311 // Reacquire mServiceLock
2312 mServiceLock.lock();
2313
2314 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002315 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002316 }
2317
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002318 if (shimUpdateOnly) {
2319 // If only updating legacy shim parameters, immediately disconnect client
2320 mServiceLock.unlock();
2321 client->disconnect();
2322 mServiceLock.lock();
2323 } else {
2324 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002325 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002326 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002327
2328 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002329 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002330 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002331 } // lock is destroyed, allow further connect calls
2332
2333 // Important: release the mutex here so the client can call back into the service from its
2334 // destructor (can be at the end of the call)
2335 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002336
2337 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002338 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002339 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002340
Cliff Wud3a05312021-04-26 23:07:31 +08002341 {
2342 Mutex::Autolock lock(mInjectionParametersLock);
2343 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2344 mInjectionInitPending = false;
2345 status_t res = NO_ERROR;
2346 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2347 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002348 sp<BasicClient> clientSp = clientDescriptor->getValue();
2349 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2350 if(res != OK) {
2351 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2352 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002353 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002354 }
2355 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002356 if (res != OK) {
2357 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2358 }
2359 } else {
2360 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002361 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002362 res = NO_INIT;
2363 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2364 }
2365 }
2366 }
2367
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002368 return ret;
2369}
2370
Austin Borgered99f642023-06-01 16:51:35 -07002371status_t CameraService::addOfflineClient(const std::string &cameraId,
2372 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002373 if (offlineClient.get() == nullptr) {
2374 return BAD_VALUE;
2375 }
2376
2377 {
2378 // Acquire mServiceLock and prevent other clients from connecting
2379 std::unique_ptr<AutoConditionLock> lock =
2380 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2381
2382 if (lock == nullptr) {
2383 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2384 , __FUNCTION__, offlineClient->getClientPid());
2385 return TIMED_OUT;
2386 }
2387
2388 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2389 if (onlineClientDesc.get() == nullptr) {
2390 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2391 cameraId.c_str());
2392 return BAD_VALUE;
2393 }
2394
2395 // Offline clients do not evict or conflict with other online devices. Resource sharing
2396 // conflicts are handled by the camera provider which will either succeed or fail before
2397 // reaching this method.
2398 const auto& onlinePriority = onlineClientDesc->getPriority();
2399 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2400 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002401 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002402 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002403 // native clients don't have offline processing support.
2404 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002405 if (offlineClientDesc == nullptr) {
2406 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2407 return BAD_VALUE;
2408 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002409
2410 // Allow only one offline device per camera
2411 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2412 if (!incompatibleClients.empty()) {
2413 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2414 return BAD_VALUE;
2415 }
2416
Austin Borgered99f642023-06-01 16:51:35 -07002417 std::string monitorTags = isClientWatched(offlineClient.get())
2418 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002419 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002420 if (err != OK) {
2421 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2422 return err;
2423 }
2424
2425 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2426 if (evicted.size() > 0) {
2427 for (auto& i : evicted) {
2428 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002429 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002430 }
2431
2432 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2433 "properly", __FUNCTION__);
2434
2435 return BAD_VALUE;
2436 }
2437
2438 logConnectedOffline(offlineClientDesc->getKey(),
2439 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002440 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002441
2442 sp<IBinder> remoteCallback = offlineClient->getRemote();
2443 if (remoteCallback != nullptr) {
2444 remoteCallback->linkToDeath(this);
2445 }
2446 } // lock is destroyed, allow further connect calls
2447
2448 return OK;
2449}
2450
Austin Borgered99f642023-06-01 16:51:35 -07002451Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002452 int32_t torchStrength,
Rucha Katakwar38284522021-11-10 11:25:21 -08002453 const sp<IBinder>& clientBinder) {
2454 Mutex::Autolock lock(mServiceLock);
2455
2456 ATRACE_CALL();
2457 if (clientBinder == nullptr) {
2458 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2459 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2460 "Torch client binder in null.");
2461 }
2462
Rucha Katakwar38284522021-11-10 11:25:21 -08002463 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002464 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002465 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002466 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002467 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002468 }
2469
2470 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002471 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002472 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002473 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002474 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002475 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002476 }
2477
2478 StatusInternal cameraStatus = state->getStatus();
2479 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2480 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002481 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002482 (int)cameraStatus);
2483 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002484 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002485 }
2486
2487 {
2488 Mutex::Autolock al(mTorchStatusMutex);
2489 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002490 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002491 if (err != OK) {
2492 if (err == NAME_NOT_FOUND) {
2493 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002494 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002495 }
2496 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002497 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002498 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2499 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002500 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002501 }
2502
2503 if (status == TorchModeStatus::NOT_AVAILABLE) {
2504 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2505 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002506 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002507 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2508 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002509 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002510 } else {
2511 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002512 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002513 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2514 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002515 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002516 }
2517 }
2518 }
2519
2520 {
2521 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002522 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002523 }
2524 // Check if the current torch strength level is same as the new one.
2525 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002526 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002527
Austin Borgered99f642023-06-01 16:51:35 -07002528 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002529
2530 if (err != OK) {
2531 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002532 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002533 switch (err) {
2534 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002535 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2536 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002537 errorCode = ERROR_ILLEGAL_ARGUMENT;
2538 break;
2539 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002540 msg = fmt::sprintf("Camera \"%s\" is in use",
2541 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002542 errorCode = ERROR_CAMERA_IN_USE;
2543 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002544 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002545 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002546 "valid range.", torchStrength);
2547 errorCode = ERROR_ILLEGAL_ARGUMENT;
2548 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002549 default:
Austin Borgered99f642023-06-01 16:51:35 -07002550 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002551 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002552 }
Austin Borgered99f642023-06-01 16:51:35 -07002553 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2554 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002555 }
2556
2557 {
2558 // update the link to client's death
2559 // Store the last client that turns on each camera's torch mode.
2560 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002561 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002562 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002563 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002564 } else {
2565 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2566 mTorchClientMap.replaceValueAt(index, clientBinder);
2567 }
2568 clientBinder->linkToDeath(this);
2569 }
2570
2571 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002572 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002573 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002574 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002575 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002576 }
2577 return Status::ok();
2578}
2579
Austin Borgered99f642023-06-01 16:51:35 -07002580Status CameraService::setTorchMode(const std::string& unresolvedCameraId,
malikakash82ed4352023-07-21 22:44:34 +00002581 bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002582 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002583 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002584
2585 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002586 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002587 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002588 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2589 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002590 }
2591
Jayant Chowdhary12361932018-08-27 14:46:13 -07002592 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002593 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002594
Austin Borgered99f642023-06-01 16:51:35 -07002595 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002596 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002597 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002598 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002599 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002600 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002601 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002602 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002603 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002604 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002605 }
2606
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002607 StatusInternal cameraStatus = state->getStatus();
2608 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002609 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002610 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2611 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002612 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002613 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002614 }
2615
2616 {
2617 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002618 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002619 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002620 if (err != OK) {
2621 if (err == NAME_NOT_FOUND) {
2622 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002623 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002624 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002625 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002626 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002627 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002628 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002629 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002630 }
2631
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002632 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002633 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002634 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002635 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002636 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2637 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002638 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002639 } else {
2640 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002641 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002642 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2643 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002644 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002645 }
2646 }
2647 }
2648
Ruben Brunk99e69712015-05-26 17:25:07 -07002649 {
2650 // Update UID map - this is used in the torch status changed callbacks, so must be done
2651 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002652 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002653 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002654 }
2655
Austin Borgered99f642023-06-01 16:51:35 -07002656 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002657
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002658 if (err != OK) {
2659 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002660 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002661 switch (err) {
2662 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002663 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2664 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002665 errorCode = ERROR_ILLEGAL_ARGUMENT;
2666 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002667 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002668 msg = fmt::sprintf("Camera \"%s\" is in use",
2669 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002670 errorCode = ERROR_CAMERA_IN_USE;
2671 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002672 default:
Austin Borgered99f642023-06-01 16:51:35 -07002673 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002674 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002675 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002676 errorCode = ERROR_INVALID_OPERATION;
2677 }
Austin Borgered99f642023-06-01 16:51:35 -07002678 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2679 logServiceError(msg, errorCode);
2680 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002681 }
2682
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002683 {
2684 // update the link to client's death
2685 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002686 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002687 if (enabled) {
2688 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002689 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002690 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002691 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002692 mTorchClientMap.replaceValueAt(index, clientBinder);
2693 }
2694 clientBinder->linkToDeath(this);
2695 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002696 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002697 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002698 }
2699
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002700 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07002701 std::string torchState = enabled ? "on" : "off";
2702 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
2703 torchState.c_str(), clientPid);
2704 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002705 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002706}
2707
Austin Borgered99f642023-06-01 16:51:35 -07002708void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
2709 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
2710 mTorchUidMap[cameraId].first = uid;
2711 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002712 } else {
2713 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07002714 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08002715 }
2716}
2717
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002718Status CameraService::notifySystemEvent(int32_t eventId,
2719 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002720 const int pid = CameraThreadState::getCallingPid();
2721 const int selfPid = getpid();
2722
2723 // Permission checks
2724 if (pid != selfPid) {
2725 // Ensure we're being called by system_server, or similar process with
2726 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002727 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002728 const int uid = CameraThreadState::getCallingUid();
2729 ALOGE("Permission Denial: cannot send updates to camera service about system"
2730 " events from pid=%d, uid=%d", pid, uid);
2731 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09002732 "No permission to send updates to camera service about system events"
2733 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09002734 }
2735 }
2736
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002737 ATRACE_CALL();
2738
Ruben Brunk36597b22015-03-20 22:15:57 -07002739 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002740 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08002741 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07002742 // from a system server crash
2743 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08002744 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002745 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07002746 break;
2747 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02002748 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
2749 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00002750 if (args.size() != 1) {
2751 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
2752 "USB Device Event requires 1 argument");
2753 }
2754
Valentin Iftime29e2e152021-08-13 15:17:33 +02002755 // Notify CameraProviderManager for lazy HALs
2756 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
2757 std::to_string(args[0]));
2758 break;
2759 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002760 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07002761 default: {
2762 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
2763 eventId);
2764 break;
2765 }
2766 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002767 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07002768}
2769
Emilian Peev53722fa2019-02-22 17:47:20 -08002770void CameraService::notifyMonitoredUids() {
2771 Mutex::Autolock lock(mStatusListenerLock);
2772
2773 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002774 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07002775 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2776 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08002777 }
2778}
2779
Austin Borgerdddb7552023-03-30 17:53:01 -07002780void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
2781 Mutex::Autolock lock(mStatusListenerLock);
2782
2783 for (const auto& it : mListenerList) {
2784 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
2785 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
2786 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
2787 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
2788 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
2789 }
2790 }
2791}
2792
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002793Status CameraService::notifyDeviceStateChange(int64_t newState) {
2794 const int pid = CameraThreadState::getCallingPid();
2795 const int selfPid = getpid();
2796
2797 // Permission checks
2798 if (pid != selfPid) {
2799 // Ensure we're being called by system_server, or similar process with
2800 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002801 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002802 const int uid = CameraThreadState::getCallingUid();
2803 ALOGE("Permission Denial: cannot send updates to camera service about device"
2804 " state changes from pid=%d, uid=%d", pid, uid);
2805 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2806 "No permission to send updates to camera service about device state"
2807 " changes from pid=%d, uid=%d", pid, uid);
2808 }
2809 }
2810
2811 ATRACE_CALL();
2812
Austin Borger18b30a72022-10-27 12:20:29 -07002813 {
2814 Mutex::Autolock lock(mServiceLock);
2815 mDeviceState = newState;
2816 }
2817
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07002818 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08002819
2820 return Status::ok();
2821}
2822
Emilian Peev8b64f282021-03-25 16:49:57 -07002823Status CameraService::notifyDisplayConfigurationChange() {
2824 ATRACE_CALL();
2825 const int callingPid = CameraThreadState::getCallingPid();
2826 const int selfPid = getpid();
2827
2828 // Permission checks
2829 if (callingPid != selfPid) {
2830 // Ensure we're being called by system_server, or similar process with
2831 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07002832 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07002833 const int uid = CameraThreadState::getCallingUid();
2834 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
2835 " changes from pid=%d, uid=%d", callingPid, uid);
2836 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2837 "No permission to send updates to camera service about orientation"
2838 " changes from pid=%d, uid=%d", callingPid, uid);
2839 }
2840 }
2841
2842 Mutex::Autolock lock(mServiceLock);
2843
2844 // Don't do anything if rotate-and-crop override via cmd is active
2845 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
2846
2847 const auto clients = mActiveClientManager.getAll();
2848 for (auto& current : clients) {
2849 if (current != nullptr) {
2850 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07002851 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
2852 basicClient->setRotateAndCropOverride(
2853 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2854 basicClient->getPackageName(),
2855 basicClient->getCameraFacing(),
2856 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07002857 }
2858 }
2859 }
2860
2861 return Status::ok();
2862}
2863
2864Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002865 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
2866 ATRACE_CALL();
2867 if (!concurrentCameraIds) {
2868 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
2869 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
2870 }
2871
2872 if (!mInitialized) {
2873 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07002874 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002875 return STATUS_ERROR(ERROR_DISCONNECTED,
2876 "Camera subsystem is not available");
2877 }
2878 // First call into the provider and get the set of concurrent camera
2879 // combinations
2880 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07002881 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002882 for (auto &combination : concurrentCameraCombinations) {
2883 std::vector<std::string> validCombination;
2884 for (auto &cameraId : combination) {
2885 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07002886 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002887 if (state == nullptr) {
2888 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
2889 continue;
2890 }
2891 StatusInternal status = state->getStatus();
2892 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
2893 continue;
2894 }
Austin Borgered99f642023-06-01 16:51:35 -07002895 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002896 continue;
2897 }
2898 validCombination.push_back(cameraId);
2899 }
2900 if (validCombination.size() != 0) {
2901 concurrentCameraIds->push_back(std::move(validCombination));
2902 }
2903 }
2904 return Status::ok();
2905}
2906
2907Status CameraService::isConcurrentSessionConfigurationSupported(
2908 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002909 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002910 if (!isSupported) {
2911 ALOGE("%s: isSupported is NULL", __FUNCTION__);
2912 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
2913 }
2914
2915 if (!mInitialized) {
2916 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
2917 return STATUS_ERROR(ERROR_DISCONNECTED,
2918 "Camera subsystem is not available");
2919 }
2920
2921 // Check for camera permissions
2922 int callingPid = CameraThreadState::getCallingPid();
2923 int callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002924 permission::PermissionChecker permissionChecker;
2925 AttributionSourceState attributionSource{};
2926 attributionSource.pid = callingPid;
2927 attributionSource.uid = callingUid;
2928 bool checkPermissionForCamera = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07002929 toString16(sCameraPermission), attributionSource, String16(),
2930 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Joanne Chung02c13d02023-01-16 12:58:05 +00002931 if ((callingPid != getpid()) && !checkPermissionForCamera) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002932 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
2933 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
2934 "android.permission.CAMERA needed to call"
2935 "isConcurrentSessionConfigurationSupported");
2936 }
2937
2938 status_t res =
2939 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002940 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
2941 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002942 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07002943 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07002944 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08002945 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
2946 "support %s (%d)", strerror(-res), res);
2947 }
2948 return Status::ok();
2949}
2950
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002951Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
2952 /*out*/
2953 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002954 return addListenerHelper(listener, cameraStatuses);
2955}
2956
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002957binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
2958 std::vector<hardware::CameraStatus>* cameraStatuses) {
2959 return addListenerHelper(listener, cameraStatuses, false, true);
2960}
2961
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002962Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
2963 /*out*/
2964 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07002965 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002966
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002967 ATRACE_CALL();
2968
Igor Murashkinbfc99152013-02-27 12:55:20 -08002969 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08002970
Ruben Brunk3450ba72015-06-16 11:00:37 -07002971 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002972 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002973 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07002974 }
2975
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002976 auto clientUid = CameraThreadState::getCallingUid();
2977 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00002978 permission::PermissionChecker permissionChecker;
2979 AttributionSourceState attributionSource{};
2980 attributionSource.uid = clientUid;
2981 attributionSource.pid = clientPid;
2982 bool openCloseCallbackAllowed = permissionChecker.checkPermissionForPreflight(
Austin Borgered99f642023-06-01 16:51:35 -07002983 toString16(sCameraOpenCloseListenerPermission), attributionSource, String16(),
Joanne Chung02c13d02023-01-16 12:58:05 +00002984 AppOpsManager::OP_NONE) != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002985
Igor Murashkinbfc99152013-02-27 12:55:20 -08002986 Mutex::Autolock lock(mServiceLock);
2987
Ruben Brunkcc776712015-02-17 20:18:47 -08002988 {
2989 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08002990 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002991 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002992 ALOGW("%s: Tried to add listener %p which was already subscribed",
2993 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002994 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08002995 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08002996 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002997
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002998 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08002999 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3000 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003001 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003002 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003003 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003004 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003005 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3006 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3007 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003008 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003009 // The listener still needs to be added to the list of listeners, regardless of what
3010 // permissions the listener process has / whether it is a vendor listener. Since it might be
3011 // eligible to listen to other camera ids.
3012 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003013 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003014 }
3015
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003016 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003017 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003018 Mutex::Autolock lock(mCameraStatesLock);
3019 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003020 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003021 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003022 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003023 }
3024 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003025 // Remove the camera statuses that should be hidden from the client, we do
3026 // this after collecting the states in order to avoid holding
3027 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3028 // the same time.
3029 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3030 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3031 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3032 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3033 ALOGE("%s: Invalid camera id %s, skipping status update",
3034 __FUNCTION__, s.cameraId.c_str());
3035 return true;
3036 }
3037 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3038 clientUid);}), cameraStatuses->end());
3039
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003040 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003041 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003042 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003043 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003044 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003045
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003046 /*
3047 * Immediately signal current torch status to this listener only
3048 * This may be a subset of all the devices, so don't include it in the response directly
3049 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003050 {
3051 Mutex::Autolock al(mTorchStatusMutex);
3052 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003053 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003054 // The camera id is visible to the client. Fine to send torch
3055 // callback.
3056 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3057 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3058 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003059 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003060 }
3061
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003062 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003063}
Ruben Brunkcc776712015-02-17 20:18:47 -08003064
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003065Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003066 ATRACE_CALL();
3067
Igor Murashkinbfc99152013-02-27 12:55:20 -08003068 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3069
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003070 if (listener == 0) {
3071 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003072 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003073 }
3074
Igor Murashkinbfc99152013-02-27 12:55:20 -08003075 Mutex::Autolock lock(mServiceLock);
3076
Ruben Brunkcc776712015-02-17 20:18:47 -08003077 {
3078 Mutex::Autolock lock(mStatusListenerLock);
3079 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003080 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003081 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003082 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003083 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003084 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003085 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003086 }
3087 }
3088
3089 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3090 __FUNCTION__, listener.get());
3091
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003092 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003093}
3094
Austin Borgered99f642023-06-01 16:51:35 -07003095Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003096
3097 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003098 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3099
3100 if (parameters == NULL) {
3101 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003102 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003103 }
3104
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003105 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003106
3107 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003108 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003109 // Error logged by caller
3110 return ret;
3111 }
3112
3113 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003114
Austin Borgered99f642023-06-01 16:51:35 -07003115 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003116
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003117 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003118}
3119
Austin Borgered99f642023-06-01 16:51:35 -07003120Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003121 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003122 ATRACE_CALL();
3123
malikakashedb38962023-09-06 00:03:35 +00003124 const std::string cameraId = resolveCameraId(
3125 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003126
Austin Borgered99f642023-06-01 16:51:35 -07003127 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003128
3129 switch (apiVersion) {
3130 case API_VERSION_1:
3131 case API_VERSION_2:
3132 break;
3133 default:
Austin Borgered99f642023-06-01 16:51:35 -07003134 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3135 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3136 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003137 }
3138
Austin Borger18b30a72022-10-27 12:20:29 -07003139 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003140 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003141 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003142 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3143 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3144 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003145 }
3146 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3147 int deviceVersion = deviceVersionAndTransport.first;
3148 switch (deviceVersion) {
3149 case CAMERA_DEVICE_API_VERSION_1_0:
3150 case CAMERA_DEVICE_API_VERSION_3_0:
3151 case CAMERA_DEVICE_API_VERSION_3_1:
3152 if (apiVersion == API_VERSION_2) {
3153 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003154 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003155 *isSupported = false;
3156 } else { // if (apiVersion == API_VERSION_1) {
3157 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003158 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003159 *isSupported = true;
3160 }
3161 break;
3162 case CAMERA_DEVICE_API_VERSION_3_2:
3163 case CAMERA_DEVICE_API_VERSION_3_3:
3164 case CAMERA_DEVICE_API_VERSION_3_4:
3165 case CAMERA_DEVICE_API_VERSION_3_5:
3166 case CAMERA_DEVICE_API_VERSION_3_6:
3167 case CAMERA_DEVICE_API_VERSION_3_7:
3168 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003169 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003170 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003171 break;
3172 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003173 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3174 deviceVersion, cameraId.c_str());
3175 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3176 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003177 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003178 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003179 } else {
3180 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003181 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003182 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003183}
3184
Austin Borgered99f642023-06-01 16:51:35 -07003185Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003186 /*out*/ bool *isSupported) {
3187 ATRACE_CALL();
3188
malikakashedb38962023-09-06 00:03:35 +00003189 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3190 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003191
Austin Borgered99f642023-06-01 16:51:35 -07003192 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3193 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003194
3195 return Status::ok();
3196}
3197
Cliff Wud8cae102021-03-11 01:37:42 +08003198Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003199 const std::string& packageName, const std::string& internalCamId,
3200 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003201 const sp<ICameraInjectionCallback>& callback,
3202 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003203 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003204 ATRACE_CALL();
3205
Austin Borgered99f642023-06-01 16:51:35 -07003206 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003207 const int pid = CameraThreadState::getCallingPid();
3208 const int uid = CameraThreadState::getCallingUid();
3209 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3210 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3211 "Permission Denial: no permission to inject camera");
3212 }
3213
3214 ALOGV(
3215 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3216 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003217 __FUNCTION__, packageName.c_str(),
3218 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003219
Cliff Wud3a05312021-04-26 23:07:31 +08003220 {
3221 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003222 mInjectionInternalCamId = internalCamId;
3223 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003224 mInjectionStatusListener->addListener(callback);
3225 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003226 status_t res = NO_ERROR;
3227 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3228 // If the client already exists, we can directly connect to the camera device through the
3229 // client's injectCamera(), otherwise we need to wait until the client is established
3230 // (execute connectHelper()) before injecting the camera to the camera device.
3231 if (clientDescriptor != nullptr) {
3232 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003233 sp<BasicClient> clientSp = clientDescriptor->getValue();
3234 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3235 if(res != OK) {
3236 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3237 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003238 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003239 }
3240 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003241 if(res != OK) {
3242 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3243 }
3244 } else {
3245 mInjectionInitPending = true;
3246 }
3247 }
Cliff Wud8cae102021-03-11 01:37:42 +08003248
Cliff Wud3a05312021-04-26 23:07:31 +08003249 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003250}
3251
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003252Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003253 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003254 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3255 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3256 return Status::ok();
3257}
3258
Ruben Brunkcc776712015-02-17 20:18:47 -08003259void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003260 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003261 for (auto& i : mActiveClientManager.getAll()) {
3262 auto clientSp = i->getValue();
3263 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003264 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003265 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003266 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003267 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003268 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003269}
3270
Ruben Brunkcc776712015-02-17 20:18:47 -08003271bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003272 bool ret = false;
3273 {
3274 // Acquire mServiceLock and prevent other clients from connecting
3275 std::unique_ptr<AutoConditionLock> lock =
3276 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003277
Igor Murashkin634a5152013-02-20 17:15:11 -08003278
Ruben Brunkcc776712015-02-17 20:18:47 -08003279 std::vector<sp<BasicClient>> evicted;
3280 for (auto& i : mActiveClientManager.getAll()) {
3281 auto clientSp = i->getValue();
3282 if (clientSp.get() == nullptr) {
3283 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3284 mActiveClientManager.remove(i);
3285 continue;
3286 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003287 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003288 mActiveClientManager.remove(i);
3289 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003290
Ruben Brunkcc776712015-02-17 20:18:47 -08003291 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003292 clientSp->notifyError(
3293 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003294 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003295 }
3296 }
3297
Ruben Brunkcc776712015-02-17 20:18:47 -08003298 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3299 // other clients from connecting in mServiceLockWrapper if held
3300 mServiceLock.unlock();
3301
Ruben Brunk36597b22015-03-20 22:15:57 -07003302 // Do not clear caller identity, remote caller should be client proccess
3303
Ruben Brunkcc776712015-02-17 20:18:47 -08003304 for (auto& i : evicted) {
3305 if (i.get() != nullptr) {
3306 i->disconnect();
3307 ret = true;
3308 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003309 }
3310
Ruben Brunkcc776712015-02-17 20:18:47 -08003311 // Reacquire mServiceLock
3312 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003313
Ruben Brunkcc776712015-02-17 20:18:47 -08003314 } // lock is destroyed, allow further connect calls
3315
3316 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003317}
3318
Ruben Brunkcc776712015-02-17 20:18:47 -08003319std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003320 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003321 std::shared_ptr<CameraState> state;
3322 {
3323 Mutex::Autolock lock(mCameraStatesLock);
3324 auto iter = mCameraStates.find(cameraId);
3325 if (iter != mCameraStates.end()) {
3326 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003327 }
3328 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003329 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003330}
3331
Austin Borgered99f642023-06-01 16:51:35 -07003332sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003333 // Remove from active clients list
3334 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3335 if (clientDescriptorPtr == nullptr) {
3336 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003337 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003338 return sp<BasicClient>{nullptr};
3339 }
3340
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003341 sp<BasicClient> client = clientDescriptorPtr->getValue();
3342 if (client.get() != nullptr) {
3343 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3344 }
3345 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003346}
3347
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003348void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003349 // Acquire mServiceLock and prevent other clients from connecting
3350 std::unique_ptr<AutoConditionLock> lock =
3351 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3352
Ruben Brunk6267b532015-04-30 17:44:07 -07003353 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003354 for (size_t i = 0; i < newUserIds.size(); i++) {
3355 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003356 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003357 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003358 return;
3359 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003360 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003361 }
3362
Ruben Brunka8ca9152015-04-07 14:23:40 -07003363
Ruben Brunk6267b532015-04-30 17:44:07 -07003364 if (newAllowedUsers == mAllowedUsers) {
3365 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3366 return;
3367 }
3368
3369 logUserSwitch(mAllowedUsers, newAllowedUsers);
3370
3371 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003372
3373 // Current user has switched, evict all current clients.
3374 std::vector<sp<BasicClient>> evicted;
3375 for (auto& i : mActiveClientManager.getAll()) {
3376 auto clientSp = i->getValue();
3377
3378 if (clientSp.get() == nullptr) {
3379 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3380 continue;
3381 }
3382
Ruben Brunk6267b532015-04-30 17:44:07 -07003383 // Don't evict clients that are still allowed.
3384 uid_t clientUid = clientSp->getClientUid();
3385 userid_t clientUserId = multiuser_get_user_id(clientUid);
3386 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3387 continue;
3388 }
3389
Ruben Brunk36597b22015-03-20 22:15:57 -07003390 evicted.push_back(clientSp);
3391
Ruben Brunk36597b22015-03-20 22:15:57 -07003392 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003393 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003394
Ruben Brunk36597b22015-03-20 22:15:57 -07003395 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003396 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003397 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003398 " to user switch.", i->getKey().c_str(),
3399 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003400 i->getOwnerId(), i->getPriority().getScore(),
3401 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003402
3403 }
3404
3405 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3406 // blocking other clients from connecting in mServiceLockWrapper if held.
3407 mServiceLock.unlock();
3408
3409 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003410 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003411
3412 for (auto& i : evicted) {
3413 i->disconnect();
3414 }
3415
Jayant Chowdhary12361932018-08-27 14:46:13 -07003416 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003417
3418 // Reacquire mServiceLock
3419 mServiceLock.lock();
3420}
Ruben Brunkcc776712015-02-17 20:18:47 -08003421
Austin Borgered99f642023-06-01 16:51:35 -07003422void CameraService::logEvent(const std::string &event) {
3423 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003424 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003425 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003426 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003427 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003428 mEventLog.add(msg);
3429 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3430 // Error event not added to the dumpsys log before
3431 mEventLog.add(msg);
3432 sServiceErrorEventSet.insert(msg);
3433 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003434}
3435
Austin Borgered99f642023-06-01 16:51:35 -07003436void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3437 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003438 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003439 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3440 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003441}
3442
Austin Borgered99f642023-06-01 16:51:35 -07003443void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3444 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003445 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003446 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3447 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003448}
3449
Austin Borgered99f642023-06-01 16:51:35 -07003450void CameraService::logConnected(const std::string &cameraId, int clientPid,
3451 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003452 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003453 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3454 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003455}
3456
Austin Borgered99f642023-06-01 16:51:35 -07003457void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3458 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003459 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003460 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3461 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003462}
3463
Austin Borgered99f642023-06-01 16:51:35 -07003464void CameraService::logRejected(const std::string &cameraId, int clientPid,
3465 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003466 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003467 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3468 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003469}
3470
Austin Borgered99f642023-06-01 16:51:35 -07003471void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3472 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003473 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003474 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3475 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003476}
3477
Ruben Brunk6267b532015-04-30 17:44:07 -07003478void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3479 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003480 std::string newUsers = toString(newUserIds);
3481 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003482 if (oldUsers.size() == 0) {
3483 oldUsers = "<None>";
3484 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003485 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003486 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3487 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003488}
3489
Austin Borgered99f642023-06-01 16:51:35 -07003490void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003491 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003492 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003493}
3494
Austin Borgered99f642023-06-01 16:51:35 -07003495void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003496 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003497 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003498}
3499
Austin Borgered99f642023-06-01 16:51:35 -07003500void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003501 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003502 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003503}
3504
Austin Borgered99f642023-06-01 16:51:35 -07003505void CameraService::logServiceError(const std::string &msg, int errorCode) {
3506 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3507 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003508}
3509
Ruben Brunk36597b22015-03-20 22:15:57 -07003510status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3511 uint32_t flags) {
3512
Mathias Agopian65ab4712010-07-14 17:59:35 -07003513 // Permission checks
3514 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003515 case SHELL_COMMAND_TRANSACTION: {
3516 int in = data.readFileDescriptor();
3517 int out = data.readFileDescriptor();
3518 int err = data.readFileDescriptor();
3519 int argc = data.readInt32();
3520 Vector<String16> args;
3521 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3522 args.add(data.readString16());
3523 }
3524 sp<IBinder> unusedCallback;
3525 sp<IResultReceiver> resultReceiver;
3526 status_t status;
3527 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3528 return status;
3529 }
3530 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3531 return status;
3532 }
3533 status = shellCommand(in, out, err, args);
3534 if (resultReceiver != nullptr) {
3535 resultReceiver->send(status);
3536 }
3537 return NO_ERROR;
3538 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003539 }
3540
3541 return BnCameraService::onTransact(code, data, reply, flags);
3542}
3543
Mathias Agopian65ab4712010-07-14 17:59:35 -07003544// We share the media players for shutter and recording sound for all clients.
3545// A reference count is kept to determine when we will actually release the
3546// media players.
3547
Jaekyun Seokef498052018-03-23 13:09:44 +09003548sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3549 sp<MediaPlayer> mp = new MediaPlayer();
3550 status_t error;
3551 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003552 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003553 error = mp->prepare();
3554 }
3555 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003556 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003557 mp->disconnect();
3558 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003559 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003560 }
3561 return mp;
3562}
3563
username5755fea2018-12-27 09:48:08 +08003564void CameraService::increaseSoundRef() {
3565 Mutex::Autolock lock(mSoundLock);
3566 mSoundRef++;
3567}
3568
3569void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003570 ATRACE_CALL();
3571
username5755fea2018-12-27 09:48:08 +08003572 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3573 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3574 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3575 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3576 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3577 }
3578 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3579 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3580 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3581 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003582 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003583 }
3584 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3585 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3586 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3587 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3588 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003589 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003590}
3591
username5755fea2018-12-27 09:48:08 +08003592void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003593 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003594 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003595 if (--mSoundRef) return;
3596
3597 for (int i = 0; i < NUM_SOUNDS; i++) {
3598 if (mSoundPlayer[i] != 0) {
3599 mSoundPlayer[i]->disconnect();
3600 mSoundPlayer[i].clear();
3601 }
3602 }
3603}
3604
3605void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003606 ATRACE_CALL();
3607
Mathias Agopian65ab4712010-07-14 17:59:35 -07003608 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003609 if (kind < 0 || kind >= NUM_SOUNDS) {
3610 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3611 return;
3612 }
3613
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003615 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003616 sp<MediaPlayer> player = mSoundPlayer[kind];
3617 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003618 player->seekTo(0);
3619 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003620 }
3621}
3622
3623// ----------------------------------------------------------------------------
3624
3625CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003626 const sp<ICameraClient>& cameraClient,
Austin Borgered99f642023-06-01 16:51:35 -07003627 const std::string& clientPackageName, bool systemNativeClient,
3628 const std::optional<std::string>& clientFeatureId,
3629 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003630 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003631 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003632 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003633 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003634 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003635 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003636 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003637 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003638 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003639 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003640{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003641 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003642 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003643
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003644 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003645
username5755fea2018-12-27 09:48:08 +08003646 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003647
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003648 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003649}
3650
Mathias Agopian65ab4712010-07-14 17:59:35 -07003651// tear down the client
3652CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003653 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003654 mDestructionStarted = true;
3655
username5755fea2018-12-27 09:48:08 +08003656 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003657 // unconditionally disconnect. function is idempotent
3658 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003659}
3660
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003661sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3662
Igor Murashkin634a5152013-02-20 17:15:11 -08003663CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003664 const sp<IBinder>& remoteCallback,
Austin Borgered99f642023-06-01 16:51:35 -07003665 const std::string& clientPackageName, bool nativeClient,
3666 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003667 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003668 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003669 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003670 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003671 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3672 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003673 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003674 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003675 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003676 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003677 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003678 mRemoteBinder(remoteCallback),
3679 mOpsActive(false),
3680 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003681{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003682 if (sCameraService == nullptr) {
3683 sCameraService = cameraService;
3684 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003685
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003686 // There are 2 scenarios in which a client won't have AppOps operations
3687 // (both scenarios : native clients)
3688 // 1) It's an system native client*, the package name will be empty
3689 // and it will return from this function in the previous if condition
3690 // (This is the same as the previously existing behavior).
3691 // 2) It is a system native client, but its package name has been
3692 // modified for debugging, however it still must not use AppOps since
3693 // the package name is not a real one.
3694 //
3695 // * system native client - native client with UID < AID_APP_START. It
3696 // doesn't exclude clients not on the system partition.
3697 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003698 mAppOpsManager = std::make_unique<AppOpsManager>();
3699 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003700
3701 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003702}
3703
3704CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003705 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003706 mDestructionStarted = true;
3707}
3708
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003709binder::Status CameraService::BasicClient::disconnect() {
3710 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003711 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003712 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07003713 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07003714 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08003715
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003716 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07003717 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07003718 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003719 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08003720
3721 sp<IBinder> remote = getRemote();
3722 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003723 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08003724 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003725
3726 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07003727 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003728 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07003729 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003730 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08003731
Igor Murashkincba2c162013-03-20 15:56:31 -07003732 // client shouldn't be able to call into us anymore
3733 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003734
Kunal Malhotrabfc96052023-02-28 23:25:34 +00003735 const auto& mActivityManager = getActivityManager();
3736 if (mActivityManager) {
3737 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
3738 CameraThreadState::getCallingUid(),
3739 CameraThreadState::getCallingPid());
3740 }
3741
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003742 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08003743}
3744
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003745status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
3746 // No dumping of clients directly over Binder,
3747 // must go through CameraService::dump
3748 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07003749 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08003750 return OK;
3751}
3752
Austin Borgered99f642023-06-01 16:51:35 -07003753status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07003754 // Can't watch tags directly, must go through CameraService::startWatchingTags
3755 return OK;
3756}
3757
3758status_t CameraService::BasicClient::stopWatchingTags(int) {
3759 // Can't watch tags directly, must go through CameraService::stopWatchingTags
3760 return OK;
3761}
3762
3763status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
3764 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
3765 return OK;
3766}
3767
Austin Borgered99f642023-06-01 16:51:35 -07003768std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00003769 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08003770}
3771
Emilian Peev8b64f282021-03-25 16:49:57 -07003772int CameraService::BasicClient::getCameraFacing() const {
3773 return mCameraFacing;
3774}
3775
3776int CameraService::BasicClient::getCameraOrientation() const {
3777 return mOrientation;
3778}
Ruben Brunkcc776712015-02-17 20:18:47 -08003779
3780int CameraService::BasicClient::getClientPid() const {
3781 return mClientPid;
3782}
3783
Ruben Brunk6267b532015-04-30 17:44:07 -07003784uid_t CameraService::BasicClient::getClientUid() const {
3785 return mClientUid;
3786}
3787
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07003788bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
3789 // Defaults to API2.
3790 return level == API_2;
3791}
3792
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003793status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003794 {
3795 Mutex::Autolock l(mAudioRestrictionLock);
3796 mAudioRestriction = mode;
3797 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07003798 sCameraService->updateAudioRestriction();
3799 return OK;
3800}
3801
3802int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003803 return sCameraService->updateAudioRestriction();
3804}
3805
3806int32_t CameraService::BasicClient::getAudioRestriction() const {
3807 Mutex::Autolock l(mAudioRestrictionLock);
3808 return mAudioRestriction;
3809}
3810
3811bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
3812 switch (mode) {
3813 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
3814 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
3815 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
3816 return true;
3817 default:
3818 return false;
3819 }
3820}
3821
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003822status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
3823 if (mode == AppOpsManager::MODE_ERRORED) {
3824 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07003825 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003826 return PERMISSION_DENIED;
3827 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
3828 // If the calling Uid is trusted (a native service), the AppOpsManager could
3829 // return MODE_IGNORED. Do not treat such case as error.
3830 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
3831 mClientPackageName);
3832 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08003833 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08003834 // We don't want to return EACCESS if the CameraPrivacy is enabled.
3835 // We prefer to successfully open the camera and perform camera muting
3836 // or blocking in connectHelper as handleAppOpMode can be called before the
3837 // connection has been fully established and at that time camera muting
3838 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003839 if (!isUidActive || !isCameraPrivacyEnabled) {
3840 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07003841 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003842 // Return the same error as for device policy manager rejection
3843 return -EACCES;
3844 }
3845 }
3846 return OK;
3847}
3848
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003849status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003850 ATRACE_CALL();
3851
Igor Murashkine6800ce2013-03-04 17:25:57 -08003852 {
3853 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003854 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003855 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003856 if (mAppOpsManager != nullptr) {
3857 // Notify app ops that the camera is not available
3858 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003859 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07003860 toString16(mClientPackageName), mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08003861
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003862 // Just check for camera acccess here on open - delay startOp until
3863 // camera frames start streaming in startCameraStreamingOps
3864 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003865 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003866 status_t res = handleAppOpMode(mode);
3867 if (res != OK) {
3868 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003869 }
Svetoslav28e8ef72015-05-11 19:21:31 -07003870 }
3871
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003872 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003873
3874 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003875 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003876
Austin Borgerdddb7552023-03-30 17:53:01 -07003877 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08003878
Shuzhen Wang695044d2020-03-06 09:02:23 -08003879 // Notify listeners of camera open/close status
3880 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
3881
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003882 return OK;
3883}
3884
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003885status_t CameraService::BasicClient::startCameraStreamingOps() {
3886 ATRACE_CALL();
3887
3888 if (!mOpsActive) {
3889 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3890 return INVALID_OPERATION;
3891 }
3892 if (mOpsStreaming) {
3893 ALOGV("%s: Streaming already active!", __FUNCTION__);
3894 return OK;
3895 }
3896
3897 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003898 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003899
3900 if (mAppOpsManager != nullptr) {
3901 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003902 toString16(mClientPackageName), /*startIfModeDefault*/ false,
3903 toString16(mClientFeatureId),
3904 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003905 status_t res = handleAppOpMode(mode);
3906 if (res != OK) {
3907 return res;
3908 }
3909 }
3910
3911 mOpsStreaming = true;
3912
3913 return OK;
3914}
3915
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003916status_t CameraService::BasicClient::noteAppOp() {
3917 ATRACE_CALL();
3918
3919 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07003920 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003921
3922 // noteAppOp is only used for when camera mute is not supported, in order
3923 // to trigger the sensor privacy "Unblock" dialog
3924 if (mAppOpsManager != nullptr) {
3925 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003926 toString16(mClientPackageName), toString16(mClientFeatureId),
3927 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02003928 status_t res = handleAppOpMode(mode);
3929 if (res != OK) {
3930 return res;
3931 }
3932 }
3933
3934 return OK;
3935}
3936
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003937status_t CameraService::BasicClient::finishCameraStreamingOps() {
3938 ATRACE_CALL();
3939
3940 if (!mOpsActive) {
3941 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
3942 return INVALID_OPERATION;
3943 }
3944 if (!mOpsStreaming) {
3945 ALOGV("%s: Streaming not active!", __FUNCTION__);
3946 return OK;
3947 }
3948
3949 if (mAppOpsManager != nullptr) {
3950 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07003951 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003952 mOpsStreaming = false;
3953 }
3954
3955 return OK;
3956}
3957
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003958status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003959 ATRACE_CALL();
3960
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003961 if (mOpsStreaming) {
3962 // Make sure we've notified everyone about camera stopping
3963 finishCameraStreamingOps();
3964 }
3965
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003966 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003967 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003968 mOpsActive = false;
3969
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003970 // This function is called when a client disconnects. This should
3971 // release the camera, but actually only if it was in a proper
3972 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003973 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01003974 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003975
Ruben Brunkcc776712015-02-17 20:18:47 -08003976 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003977 sCameraService->updateStatus(StatusInternal::PRESENT,
3978 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003979 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07003980 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003981 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
3982 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003983 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003984 mOpsCallback.clear();
3985
Austin Borgerdddb7552023-03-30 17:53:01 -07003986 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08003987
Shuzhen Wang695044d2020-03-06 09:02:23 -08003988 // Notify listeners of camera open/close status
3989 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
3990
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003991 return OK;
3992}
3993
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003994void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003995 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003996 if (mAppOpsManager == nullptr) {
3997 return;
3998 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003999 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004000 if (op != AppOpsManager::OP_CAMERA) {
4001 ALOGW("Unexpected app ops notification received: %d", op);
4002 return;
4003 }
4004
4005 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004006 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004007 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004008 ALOGV("checkOp returns: %d, %s ", res,
4009 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4010 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4011 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4012 "UNKNOWN");
4013
Shuzhen Wang64900852021-02-05 09:03:29 -08004014 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004015 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4016 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004017 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004018 } else if (res == AppOpsManager::MODE_IGNORED) {
4019 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Evan Severson09ab4002021-02-10 14:15:19 -08004020 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004021 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Shuzhen Wang64900852021-02-05 09:03:29 -08004022 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
Austin Borgered99f642023-06-01 16:51:35 -07004023 mCameraIdStr.c_str(), mClientPackageName.c_str(),
Shuzhen Wang64900852021-02-05 09:03:29 -08004024 mUidIsTrusted, isUidActive);
4025 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
4026 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
4027 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004028 if (!mUidIsTrusted) {
4029 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4030 setCameraMute(true);
4031 } else if (!isUidActive
4032 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4033 block();
4034 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004035 }
Evan Severson09ab4002021-02-10 14:15:19 -08004036 } else if (res == AppOpsManager::MODE_ALLOWED) {
4037 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004038 }
4039}
4040
Svet Ganova453d0d2018-01-11 15:37:58 -08004041void CameraService::BasicClient::block() {
4042 ATRACE_CALL();
4043
4044 // Reset the client PID to allow server-initiated disconnect,
4045 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004046 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004047 CaptureResultExtras resultExtras; // a dummy result (invalid)
4048 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4049 disconnect();
4050}
4051
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052// ----------------------------------------------------------------------------
4053
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004054void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004055 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004056 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004057 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4058 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4059 api1ErrorCode = CAMERA_ERROR_DISABLED;
4060 }
4061 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004062 } else {
4063 ALOGE("mRemoteCallback is NULL!!");
4064 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004065}
4066
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004067// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004068binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004069 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004070 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004071}
4072
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004073bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4074 return level == API_1;
4075}
4076
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004077CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4078 mClient(client) {
4079}
4080
4081void CameraService::Client::OpsCallback::opChanged(int32_t op,
4082 const String16& packageName) {
4083 sp<BasicClient> client = mClient.promote();
4084 if (client != NULL) {
4085 client->opChanged(op, packageName);
4086 }
4087}
4088
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004090// UidPolicy
4091// ----------------------------------------------------------------------------
4092
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004093void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004094 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004095 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004096
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004097 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004098 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004099 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004100 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004101 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4102 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004103 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004104 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004105 if (res == OK) {
4106 mRegistered = true;
4107 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004108 } else {
4109 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004110 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004111}
4112
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004113void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004114 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004115 return;
4116 }
4117
4118 registerWithActivityManager();
4119}
4120
4121void CameraService::UidPolicy::registerSelf() {
4122 // Use check service to see if the activity service is available
4123 // If not available then register for notifications, instead of blocking
4124 // till the service is ready
4125 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004126 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004127 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004128 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004129 } else {
4130 registerWithActivityManager();
4131 }
4132}
4133
Svet Ganova453d0d2018-01-11 15:37:58 -08004134void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004135 Mutex::Autolock _l(mUidLock);
4136
Steven Moreland2f348142019-07-02 15:59:07 -07004137 mAm.unregisterUidObserver(this);
4138 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004139 mRegistered = false;
4140 mActiveUids.clear();
4141 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004142}
4143
4144void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4145 onUidIdle(uid, disabled);
4146}
4147
4148void CameraService::UidPolicy::onUidActive(uid_t uid) {
4149 Mutex::Autolock _l(mUidLock);
4150 mActiveUids.insert(uid);
4151}
4152
4153void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4154 bool deleted = false;
4155 {
4156 Mutex::Autolock _l(mUidLock);
4157 if (mActiveUids.erase(uid) > 0) {
4158 deleted = true;
4159 }
4160 }
4161 if (deleted) {
4162 sp<CameraService> service = mService.promote();
4163 if (service != nullptr) {
4164 service->blockClientsForUid(uid);
4165 }
4166 }
4167}
4168
Emilian Peev53722fa2019-02-22 17:47:20 -08004169void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004170 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004171 bool procStateChange = false;
4172 {
4173 Mutex::Autolock _l(mUidLock);
4174 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4175 mMonitoredUids[uid].procState != procState) {
4176 mMonitoredUids[uid].procState = procState;
4177 procStateChange = true;
4178 }
4179 }
4180
4181 if (procStateChange) {
4182 sp<CameraService> service = mService.promote();
4183 if (service != nullptr) {
4184 service->notifyMonitoredUids();
4185 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004186 }
4187}
4188
Austin Borgerdddb7552023-03-30 17:53:01 -07004189/**
4190 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4191 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4192 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4193 * monitoredUids. If it is revised above some other monitoredUid, signal
4194 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4195 * foreground apps in split screen - state changes will capture all other cases.
4196 */
4197void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4198 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004199 {
4200 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004201 auto it = mMonitoredUids.find(uid);
4202
4203 if (it != mMonitoredUids.end()) {
4204 if (it->second.hasCamera) {
4205 for (auto &monitoredUid : mMonitoredUids) {
4206 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004207 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004208 notifyUidSet.emplace(monitoredUid.first);
4209 }
4210 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004211 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004212 notifyUidSet.emplace(uid);
4213 } else {
4214 for (auto &monitoredUid : mMonitoredUids) {
4215 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004216 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004217 notifyUidSet.emplace(uid);
4218 }
4219 }
4220 }
4221 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004222 }
4223 }
4224
Austin Borgerdddb7552023-03-30 17:53:01 -07004225 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004226 sp<CameraService> service = mService.promote();
4227 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004228 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004229 }
4230 }
4231}
4232
Austin Borgerdddb7552023-03-30 17:53:01 -07004233/**
4234 * Register a uid for monitoring, and note whether it owns a camera.
4235 */
4236void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004237 Mutex::Autolock _l(mUidLock);
4238 auto it = mMonitoredUids.find(uid);
4239 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004240 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004241 } else {
Austin Borger65577682022-02-17 00:25:43 +00004242 MonitoredUid monitoredUid;
4243 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004244 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004245 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004246 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004247 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004248 if (res != OK) {
4249 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4250 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004251 }
4252
4253 if (openCamera) {
4254 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004255 }
4256}
4257
Austin Borgerdddb7552023-03-30 17:53:01 -07004258/**
4259 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4260 */
4261void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004262 Mutex::Autolock _l(mUidLock);
4263 auto it = mMonitoredUids.find(uid);
4264 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004265 it->second.refCount--;
4266 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004267 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004268 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004269 if (res != OK) {
4270 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4271 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004272 } else if (closeCamera) {
4273 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004274 }
4275 } else {
4276 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4277 }
4278}
4279
Austin Borgered99f642023-06-01 16:51:35 -07004280bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004281 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004282 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004283}
4284
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004285static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4286static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004287
Austin Borgered99f642023-06-01 16:51:35 -07004288bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004289 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004290 // If activity manager is unreachable, assume everything is active
4291 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004292 return true;
4293 }
4294 auto it = mOverrideUids.find(uid);
4295 if (it != mOverrideUids.end()) {
4296 return it->second;
4297 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004298 bool active = mActiveUids.find(uid) != mActiveUids.end();
4299 if (!active) {
4300 // We want active UIDs to always access camera with their first attempt since
4301 // there is no guarantee the app is robustly written and would retry getting
4302 // the camera on failure. The inverse case is not a problem as we would take
4303 // camera away soon once we get the callback that the uid is no longer active.
4304 ActivityManager am;
4305 // Okay to access with a lock held as UID changes are dispatched without
4306 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004307 int64_t startTimeMillis = 0;
4308 do {
4309 // TODO: Fix this b/109950150!
4310 // Okay this is a hack. There is a race between the UID turning active and
4311 // activity being resumed. The proper fix is very risky, so we temporary add
4312 // some polling which should happen pretty rarely anyway as the race is hard
4313 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004314 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004315 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004316 if (active) {
4317 break;
4318 }
4319 if (startTimeMillis <= 0) {
4320 startTimeMillis = uptimeMillis();
4321 }
4322 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004323 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004324 if (remainingTimeMillis <= 0) {
4325 break;
4326 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004327 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4328
4329 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004330 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004331 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004332 } while (true);
4333
Svet Ganov7b4ab782018-03-25 12:48:10 -07004334 if (active) {
4335 // Now that we found out the UID is actually active, cache that
4336 mActiveUids.insert(uid);
4337 }
4338 }
4339 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004340}
4341
Varun Shahb42f1eb2019-04-16 14:45:13 -07004342int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4343 Mutex::Autolock _l(mUidLock);
4344 return getProcStateLocked(uid);
4345}
4346
4347int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4348 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4349 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004350 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004351 }
4352 return procState;
4353}
4354
Austin Borgered99f642023-06-01 16:51:35 -07004355void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4356 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004357 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004358}
4359
Austin Borgered99f642023-06-01 16:51:35 -07004360void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004361 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004362}
4363
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004364void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4365 Mutex::Autolock _l(mUidLock);
4366 ALOGV("UidPolicy: ActivityManager has died");
4367 mRegistered = false;
4368 mActiveUids.clear();
4369}
4370
Austin Borgered99f642023-06-01 16:51:35 -07004371void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004372 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004373 bool wasActive = false;
4374 bool isActive = false;
4375 {
4376 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004377 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004378 mOverrideUids.erase(uid);
4379 if (insert) {
4380 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4381 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004382 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004383 }
4384 if (wasActive != isActive && !isActive) {
4385 sp<CameraService> service = mService.promote();
4386 if (service != nullptr) {
4387 service->blockClientsForUid(uid);
4388 }
4389 }
4390}
4391
4392// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004393// SensorPrivacyPolicy
4394// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004395
4396void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4397{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004398 Mutex::Autolock _l(mSensorPrivacyLock);
4399 if (mRegistered) {
4400 return;
4401 }
Evan Severson09ab4002021-02-10 14:15:19 -08004402 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004403 mSpm.addSensorPrivacyListener(this);
4404 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4405 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004406 if (res == OK) {
4407 mRegistered = true;
4408 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4409 }
4410}
4411
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004412void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4413 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004414 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004415 return;
4416 }
4417
4418 registerWithSensorPrivacyManager();
4419}
4420
4421void CameraService::SensorPrivacyPolicy::registerSelf() {
4422 // Use checkservice to see if the sensor_privacy service is available
4423 // If service is not available then register for notification
4424 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004425 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004426 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004427 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004428 } else {
4429 registerWithSensorPrivacyManager();
4430 }
4431}
4432
Michael Grooverd1d435a2018-12-18 17:39:42 -08004433void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4434 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004435 mSpm.removeSensorPrivacyListener(this);
4436 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004437 mRegistered = false;
4438 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4439}
4440
4441bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004442 if (!mRegistered) {
4443 registerWithSensorPrivacyManager();
4444 }
4445
Michael Grooverd1d435a2018-12-18 17:39:42 -08004446 Mutex::Autolock _l(mSensorPrivacyLock);
4447 return mSensorPrivacyEnabled;
4448}
4449
Evan Seversond0b69922022-01-27 10:47:34 -08004450bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004451 if (!hasCameraPrivacyFeature()) {
4452 return false;
4453 }
Evan Seversond0b69922022-01-27 10:47:34 -08004454 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004455}
4456
Evan Seversond0b69922022-01-27 10:47:34 -08004457binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
4458 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004459 {
4460 Mutex::Autolock _l(mSensorPrivacyLock);
Kwangkyu Parke3af2992022-11-05 02:46:52 +09004461 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004462 }
4463 // if sensor privacy is enabled then block all clients from accessing the camera
Evan Severson09ab4002021-02-10 14:15:19 -08004464 if (enabled) {
4465 sp<CameraService> service = mService.promote();
4466 if (service != nullptr) {
4467 service->blockAllClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004468 }
4469 }
4470 return binder::Status::ok();
4471}
4472
4473void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4474 Mutex::Autolock _l(mSensorPrivacyLock);
4475 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4476 mRegistered = false;
4477}
4478
Evan Severson09ab4002021-02-10 14:15:19 -08004479bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004480 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4481 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4482 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4483 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4484 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004485}
4486
Michael Grooverd1d435a2018-12-18 17:39:42 -08004487// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004488// CameraState
4489// ----------------------------------------------------------------------------
4490
Austin Borgered99f642023-06-01 16:51:35 -07004491CameraService::CameraState::CameraState(const std::string& id, int cost,
4492 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004493 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004494 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004495 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004496
4497CameraService::CameraState::~CameraState() {}
4498
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004499CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004500 Mutex::Autolock lock(mStatusLock);
4501 return mStatus;
4502}
4503
Austin Borgered99f642023-06-01 16:51:35 -07004504std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004505 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004506 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004507 return res;
4508}
4509
Ruben Brunkcc776712015-02-17 20:18:47 -08004510CameraParameters CameraService::CameraState::getShimParams() const {
4511 return mShimParams;
4512}
4513
4514void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4515 mShimParams = params;
4516}
4517
4518int CameraService::CameraState::getCost() const {
4519 return mCost;
4520}
4521
Austin Borgered99f642023-06-01 16:51:35 -07004522std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004523 return mConflicting;
4524}
4525
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004526SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4527 return mSystemCameraKind;
4528}
4529
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004530bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4531 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4532 != mPhysicalCameras.end();
4533}
4534
Austin Borgered99f642023-06-01 16:51:35 -07004535bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004536 Mutex::Autolock lock(mStatusLock);
4537 auto result = mUnavailablePhysicalIds.insert(physicalId);
4538 return result.second;
4539}
4540
Austin Borgered99f642023-06-01 16:51:35 -07004541bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004542 Mutex::Autolock lock(mStatusLock);
4543 auto count = mUnavailablePhysicalIds.erase(physicalId);
4544 return count > 0;
4545}
4546
Austin Borgered99f642023-06-01 16:51:35 -07004547void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004548 Mutex::Autolock lock(mStatusLock);
4549 mClientPackage = clientPackage;
4550}
4551
Austin Borgered99f642023-06-01 16:51:35 -07004552std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004553 Mutex::Autolock lock(mStatusLock);
4554 return mClientPackage;
4555}
4556
Ruben Brunkcc776712015-02-17 20:18:47 -08004557// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004558// ClientEventListener
4559// ----------------------------------------------------------------------------
4560
4561void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004562 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004563 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004564 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004565 if (basicClient.get() != nullptr) {
4566 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004567 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004568 static_cast<int>(basicClient->getClientUid()));
4569 }
4570}
4571
4572void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004573 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004574 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004575 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004576 if (basicClient.get() != nullptr) {
4577 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004578 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004579 static_cast<int>(basicClient->getClientUid()));
4580 }
4581}
4582
4583
4584// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004585// CameraClientManager
4586// ----------------------------------------------------------------------------
4587
Ruben Brunk99e69712015-05-26 17:25:07 -07004588CameraService::CameraClientManager::CameraClientManager() {
4589 setListener(std::make_shared<ClientEventListener>());
4590}
4591
Ruben Brunkcc776712015-02-17 20:18:47 -08004592CameraService::CameraClientManager::~CameraClientManager() {}
4593
4594sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004595 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004596 auto descriptor = get(id);
4597 if (descriptor == nullptr) {
4598 return sp<BasicClient>{nullptr};
4599 }
4600 return descriptor->getValue();
4601}
4602
Austin Borgered99f642023-06-01 16:51:35 -07004603std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004604 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004605 std::ostringstream ret;
4606 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004607 bool hasAny = false;
4608 for (auto& i : all) {
4609 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004610 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004611 int32_t cost = i->getCost();
4612 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004613 int32_t score = i->getPriority().getScore();
4614 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004615 auto conflicting = i->getConflicting();
4616 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07004617 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004618 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004619 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004620 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07004621 uid_t clientUid = clientSp->getClientUid();
4622 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004623 }
Austin Borgered99f642023-06-01 16:51:35 -07004624 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4625 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004626
Ruben Brunk6267b532015-04-30 17:44:07 -07004627 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004628 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07004629 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004630 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07004631 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004632 }
4633
Austin Borgered99f642023-06-01 16:51:35 -07004634 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08004635 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07004636 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004637 }
Austin Borgered99f642023-06-01 16:51:35 -07004638 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08004639 }
Austin Borgered99f642023-06-01 16:51:35 -07004640 if (hasAny) ret << "\n";
4641 ret << "]\n";
4642 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004643}
4644
4645CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07004646 const std::string& key, const sp<BasicClient>& value, int32_t cost,
4647 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004648 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004649
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004650 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07004651 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004652
Austin Borgered99f642023-06-01 16:51:35 -07004653 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004654 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4655 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004656}
4657
4658CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004659 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004660 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004661 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004662 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004663 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4664 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004665}
4666
4667// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004668// InjectionStatusListener
4669// ----------------------------------------------------------------------------
4670
4671void CameraService::InjectionStatusListener::addListener(
4672 const sp<ICameraInjectionCallback>& callback) {
4673 Mutex::Autolock lock(mListenerLock);
4674 if (mCameraInjectionCallback) return;
4675 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
4676 if (res == OK) {
4677 mCameraInjectionCallback = callback;
4678 }
4679}
4680
4681void CameraService::InjectionStatusListener::removeListener() {
4682 Mutex::Autolock lock(mListenerLock);
4683 if (mCameraInjectionCallback == nullptr) {
4684 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4685 return;
4686 }
4687 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
4688 mCameraInjectionCallback = nullptr;
4689}
4690
4691void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07004692 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08004693 if (mCameraInjectionCallback == nullptr) {
4694 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
4695 return;
4696 }
Cliff Wud3a05312021-04-26 23:07:31 +08004697
4698 switch (err) {
4699 case -ENODEV:
4700 mCameraInjectionCallback->onInjectionError(
4701 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4702 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07004703 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004704 break;
4705 case -EBUSY:
4706 mCameraInjectionCallback->onInjectionError(
4707 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4708 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07004709 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004710 break;
4711 case DEAD_OBJECT:
4712 mCameraInjectionCallback->onInjectionError(
4713 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4714 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07004715 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004716 break;
4717 case INVALID_OPERATION:
4718 mCameraInjectionCallback->onInjectionError(
4719 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
4720 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07004721 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004722 break;
4723 case UNKNOWN_TRANSACTION:
4724 mCameraInjectionCallback->onInjectionError(
4725 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
4726 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07004727 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004728 break;
4729 default:
4730 mCameraInjectionCallback->onInjectionError(
4731 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
4732 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07004733 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08004734 }
Cliff Wud8cae102021-03-11 01:37:42 +08004735}
4736
4737void CameraService::InjectionStatusListener::binderDied(
4738 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08004739 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
4740 auto parent = mParent.promote();
4741 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08004742 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4743 if (clientDescriptor != nullptr) {
4744 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4745 baseClientPtr->stopInjection();
4746 }
Cliff Wu3b268182021-07-06 15:44:43 +08004747 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004748 }
4749}
4750
4751// ----------------------------------------------------------------------------
4752// CameraInjectionSession
4753// ----------------------------------------------------------------------------
4754
4755binder::Status CameraService::CameraInjectionSession::stopInjection() {
4756 Mutex::Autolock lock(mInjectionSessionLock);
4757 auto parent = mParent.promote();
4758 if (parent == nullptr) {
4759 ALOGE("CameraInjectionSession: Parent is gone");
4760 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
4761 "Camera service encountered error");
4762 }
Cliff Wud3a05312021-04-26 23:07:31 +08004763
4764 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08004765 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
4766 if (clientDescriptor != nullptr) {
4767 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
4768 res = baseClientPtr->stopInjection();
4769 if (res != OK) {
4770 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
4771 " ret != NO_ERROR: %d", res);
4772 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
4773 "Camera session encountered error");
4774 }
4775 }
Cliff Wu3b268182021-07-06 15:44:43 +08004776 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08004777 return binder::Status::ok();
4778}
4779
4780// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07004781
4782static const int kDumpLockRetries = 50;
4783static const int kDumpLockSleep = 60000;
4784
4785static bool tryLock(Mutex& mutex)
4786{
4787 bool locked = false;
4788 for (int i = 0; i < kDumpLockRetries; ++i) {
4789 if (mutex.tryLock() == NO_ERROR) {
4790 locked = true;
4791 break;
4792 }
4793 usleep(kDumpLockSleep);
4794 }
4795 return locked;
4796}
4797
Rucha Katakwardf223072021-06-15 10:21:00 -07004798void CameraService::cacheDump() {
4799 if (mMemFd != -1) {
4800 const Vector<String16> args;
4801 ATRACE_CALL();
4802 // Acquiring service lock here will avoid the deadlock since
4803 // cacheDump will not be called during the second disconnect.
4804 Mutex::Autolock lock(mServiceLock);
4805
4806 Mutex::Autolock l(mCameraStatesLock);
4807 // Start collecting the info for open sessions and store it in temp file.
4808 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004809 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07004810 auto clientDescriptor = mActiveClientManager.get(cameraId);
4811 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004812 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004813 // Log the current open session info before device is disconnected.
4814 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
4815 }
4816 }
4817 }
4818}
4819
Mathias Agopian65ab4712010-07-14 17:59:35 -07004820status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004821 ATRACE_CALL();
4822
Austin Borgered99f642023-06-01 16:51:35 -07004823 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004824 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004825 CameraThreadState::getCallingPid(),
4826 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004827 return NO_ERROR;
4828 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004829 bool locked = tryLock(mServiceLock);
4830 // failed to lock - CameraService is probably deadlocked
4831 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004832 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004833 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004834
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004835 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004836 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07004837
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004838 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004839 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08004840
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004841 if (locked) mServiceLock.unlock();
4842 return NO_ERROR;
4843 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004844 dprintf(fd, "\n== Service global info: ==\n\n");
4845 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004846 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07004847 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
4848 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004849 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
4850 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
4851 }
Austin Borgered99f642023-06-01 16:51:35 -07004852 std::string activeClientString = mActiveClientManager.toString();
4853 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
4854 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08004855 if (mStreamUseCaseOverrides.size() > 0) {
4856 dprintf(fd, "Active stream use case overrides:");
4857 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
4858 dprintf(fd, " %" PRId64, useCaseOverride);
4859 }
4860 dprintf(fd, "\n");
4861 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004862
4863 dumpEventLog(fd);
4864
4865 bool stateLocked = tryLock(mCameraStatesLock);
4866 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004867 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004868 }
4869
Emilian Peevbd8c5032018-02-14 23:05:40 +00004870 int argSize = args.size();
4871 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07004872 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00004873 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07004874 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00004875 }
4876 break;
4877 }
4878 }
4879
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004880 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07004881 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004882
Austin Borgered99f642023-06-01 16:51:35 -07004883 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004884
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004885 CameraParameters p = state.second->getShimParams();
4886 if (!p.isEmpty()) {
4887 dprintf(fd, " Camera1 API shim is using parameters:\n ");
4888 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004889 }
4890
4891 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004892 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004893 // log the current open session info
4894 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08004895 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07004896 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004897 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004898
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004899 }
4900
4901 if (stateLocked) mCameraStatesLock.unlock();
4902
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004903 if (locked) mServiceLock.unlock();
4904
Emilian Peevf53f66e2017-04-11 14:29:43 +01004905 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004906
4907 dprintf(fd, "\n== Vendor tags: ==\n\n");
4908
4909 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
4910 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00004911 sp<VendorTagDescriptorCache> cache =
4912 VendorTagDescriptorCache::getGlobalVendorTagCache();
4913 if (cache == NULL) {
4914 dprintf(fd, "No vendor tags.\n");
4915 } else {
4916 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
4917 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004918 } else {
4919 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
4920 }
4921
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004922 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004923 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004924 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004925
4926 // Process dump arguments, if any
4927 int n = args.size();
4928 String16 verboseOption("-v");
4929 String16 unreachableOption("--unreachable");
4930 for (int i = 0; i < n; i++) {
4931 if (args[i] == verboseOption) {
4932 // change logging level
4933 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07004934 std::string levelStr = toStdString(args[i+1]);
4935 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004936 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004937 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004938 } else if (args[i] == unreachableOption) {
4939 // Dump memory analysis
4940 // TODO - should limit be an argument parameter?
4941 UnreachableMemoryInfo info;
4942 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
4943 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004944 dprintf(fd, "\n== Unable to dump unreachable memory. "
4945 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004946 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004947 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08004948 std::string s = info.ToString(/*log_contents*/ true);
4949 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07004950 }
4951 }
4952 }
Rucha Katakwardf223072021-06-15 10:21:00 -07004953
4954 bool serviceLocked = tryLock(mServiceLock);
4955
4956 // Dump info from previous open sessions.
4957 // Reposition the offset to beginning of the file before reading
4958
4959 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
4960 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
4961 ssize_t size_read;
4962 char buf[4096];
4963 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
4964 // Read data from file to a small buffer and write it to fd.
4965 write(fd, buf, size_read);
4966 if (size_read == -1) {
4967 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4968 break;
4969 }
4970 }
4971 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
4972 } else {
4973 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
4974 }
4975
4976 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004977 return NO_ERROR;
4978}
4979
Rucha Katakwardf223072021-06-15 10:21:00 -07004980void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07004981 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004982 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07004983 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07004984 getFormattedCurrentTime().c_str(),
4985 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004986 dprintf(fd, " Client priority score: %d state: %d\n",
4987 clientDescriptor->getPriority().getScore(),
4988 clientDescriptor->getPriority().getState());
4989 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
4990
4991 auto client = clientDescriptor->getValue();
4992 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07004993 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07004994
4995 client->dumpClient(fd, args);
4996}
4997
Austin Borgered99f642023-06-01 16:51:35 -07004998void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07004999 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005000 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005001}
5002
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005003void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005004 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005005
5006 Mutex::Autolock l(mLogLock);
5007 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005008 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005009 }
5010
5011 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005012 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005013 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005014 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005015 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005016 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005017}
5018
Austin Borgered99f642023-06-01 16:51:35 -07005019void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005020 Mutex::Autolock lock(mLogLock);
5021 if (!isClientWatchedLocked(client)) { return; }
5022
5023 std::vector<std::string> dumpVector;
5024 client->dumpWatchedEventsToVector(dumpVector);
5025
5026 if (dumpVector.empty()) { return; }
5027
Austin Borgered99f642023-06-01 16:51:35 -07005028 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005029
Austin Borgered99f642023-06-01 16:51:35 -07005030 std::string currentTime = getFormattedCurrentTime();
5031 dumpString << "Cached @ ";
5032 dumpString << currentTime;
5033 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005034
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005035 size_t i = dumpVector.size();
5036
5037 // Store the string in reverse order (latest last)
5038 while (i > 0) {
5039 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005040 dumpString << cameraId;
5041 dumpString << ":";
5042 dumpString << client->getPackageName();
5043 dumpString << " ";
5044 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005045 }
5046
Austin Borgered99f642023-06-01 16:51:35 -07005047 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005048}
5049
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005050void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005051 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005052 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5053 if (mTorchClientMap[i] == who) {
5054 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005055 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005056 status_t res = mFlashlight->setTorchMode(cameraId, false);
5057 if (res) {
5058 ALOGE("%s: torch client died but couldn't turn off torch: "
5059 "%s (%d)", __FUNCTION__, strerror(-res), res);
5060 return;
5061 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005062 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005063 break;
5064 }
5065 }
5066}
5067
Ruben Brunkcc776712015-02-17 20:18:47 -08005068/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005069
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005070 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005071 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5072 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005073 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005074 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005075 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005076
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005077 // check torch client
5078 handleTorchClientBinderDied(who);
5079
5080 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005081 if(!evictClientIdByRemote(who)) {
5082 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005083 return;
5084 }
5085
Ruben Brunkcc776712015-02-17 20:18:47 -08005086 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5087 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005088}
5089
Austin Borgered99f642023-06-01 16:51:35 -07005090void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005091 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005092}
5093
Austin Borgered99f642023-06-01 16:51:35 -07005094void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005095 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005096 // Do not lock mServiceLock here or can get into a deadlock from
5097 // connect() -> disconnect -> updateStatus
5098
5099 auto state = getCameraState(cameraId);
5100
5101 if (state == nullptr) {
5102 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005103 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005104 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005105 }
5106
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005107 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5108 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5109 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005110 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005111 return;
5112 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005113
5114 // Collect the logical cameras without holding mStatusLock in updateStatus
5115 // as that can lead to a deadlock(b/162192331).
5116 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005117 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005118 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005119 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005120 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005121 (const std::string& cameraId, StatusInternal status) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005122 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005123 // Update torch status if it has a flash unit.
5124 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005125 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005126 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5127 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005128 TorchModeStatus newTorchStatus =
5129 status == StatusInternal::PRESENT ?
5130 TorchModeStatus::AVAILABLE_OFF :
5131 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005132 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005133 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005134 }
5135 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005136 }
5137
5138 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005139 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005140 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005141
Ruben Brunkcc776712015-02-17 20:18:47 -08005142 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005143 bool isVendorListener = listener->isVendorListener();
5144 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5145 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07005146 isVendorListener) {
5147 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005148 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005149 continue;
5150 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005151 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005152 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005153 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005154 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005155 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5156 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005157 // Also trigger the callbacks for cameras that were remapped to the current
5158 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005159 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005160 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5161 for (auto& remappedCameraId : remappedCameraIds) {
5162 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005163 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005164 listener->handleBinderStatus(ret,
5165 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5166 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5167 ret.exceptionCode());
5168 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005169 }
5170 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005171}
5172
Austin Borgered99f642023-06-01 16:51:35 -07005173void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5174 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005175 auto state = getCameraState(cameraId);
5176 if (state == nullptr) {
5177 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005178 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005179 return;
5180 }
5181 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005182 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005183 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005184 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005185 }
5186
Shuzhen Wang695044d2020-03-06 09:02:23 -08005187 Mutex::Autolock lock(mStatusListenerLock);
5188
5189 for (const auto& it : mListenerList) {
5190 if (!it->isOpenCloseCallbackAllowed()) {
5191 continue;
5192 }
5193
5194 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005195 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005196 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005197 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005198 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005199 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005200
5201 it->handleBinderStatus(ret,
5202 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5203 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005204 }
5205}
5206
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005207template<class Func>
5208void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005209 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005210 std::initializer_list<StatusInternal> rejectSourceStates,
5211 Func onStatusUpdatedLocked) {
5212 Mutex::Autolock lock(mStatusLock);
5213 StatusInternal oldStatus = mStatus;
5214 mStatus = status;
5215
5216 if (oldStatus == status) {
5217 return;
5218 }
5219
5220 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005221 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005222
5223 if (oldStatus == StatusInternal::NOT_PRESENT &&
5224 (status != StatusInternal::PRESENT &&
5225 status != StatusInternal::ENUMERATING)) {
5226
5227 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5228 __FUNCTION__);
5229 mStatus = oldStatus;
5230 return;
5231 }
5232
5233 /**
5234 * Sometimes we want to conditionally do a transition.
5235 * For example if a client disconnects, we want to go to PRESENT
5236 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5237 */
5238 for (auto& rejectStatus : rejectSourceStates) {
5239 if (oldStatus == rejectStatus) {
5240 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005241 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005242 mStatus = oldStatus;
5243 return;
5244 }
5245 }
5246
5247 onStatusUpdatedLocked(cameraId, status);
5248}
5249
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005250status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005251 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005252 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005253 if (!status) {
5254 return BAD_VALUE;
5255 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005256 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5257 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005258 // invalid camera ID or the camera doesn't have a flash unit
5259 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005260 }
5261
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005262 *status = mTorchStatusMap.valueAt(index);
5263 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005264}
5265
Austin Borgered99f642023-06-01 16:51:35 -07005266status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005267 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005268 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5269 if (index == NAME_NOT_FOUND) {
5270 return BAD_VALUE;
5271 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005272 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005273
5274 return OK;
5275}
5276
Austin Borgered99f642023-06-01 16:51:35 -07005277std::list<std::string> CameraService::getLogicalCameras(
5278 const std::string& physicalCameraId) {
5279 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005280 Mutex::Autolock lock(mCameraStatesLock);
5281 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005282 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5283 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005284 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005285 }
5286 return retList;
5287}
5288
5289void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005290 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005291 SystemCameraKind deviceKind) {
5292 // mStatusListenerLock is expected to be locked
5293 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005294 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005295 // Note: we check only the deviceKind of the physical camera id
5296 // since, logical camera ids and their physical camera ids are
5297 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005298 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5299 listener->getListenerPid(), listener->getListenerUid())) {
5300 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005301 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005302 continue;
5303 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005304 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005305 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005306 listener->handleBinderStatus(ret,
5307 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5308 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5309 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005310 }
5311 }
5312}
5313
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005314
Svet Ganova453d0d2018-01-11 15:37:58 -08005315void CameraService::blockClientsForUid(uid_t uid) {
5316 const auto clients = mActiveClientManager.getAll();
5317 for (auto& current : clients) {
5318 if (current != nullptr) {
5319 const auto basicClient = current->getValue();
5320 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5321 basicClient->block();
5322 }
5323 }
5324 }
5325}
5326
Michael Grooverd1d435a2018-12-18 17:39:42 -08005327void CameraService::blockAllClients() {
5328 const auto clients = mActiveClientManager.getAll();
5329 for (auto& current : clients) {
5330 if (current != nullptr) {
5331 const auto basicClient = current->getValue();
5332 if (basicClient.get() != nullptr) {
5333 basicClient->block();
5334 }
5335 }
5336 }
5337}
5338
Svet Ganova453d0d2018-01-11 15:37:58 -08005339// NOTE: This is a remote API - make sure all args are validated
5340status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005341 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005342 return PERMISSION_DENIED;
5343 }
5344 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5345 return BAD_VALUE;
5346 }
Austin Borgered99f642023-06-01 16:51:35 -07005347 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005348 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005349 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005350 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005351 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005352 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005353 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005354 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005355 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005356 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005357 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005358 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005359 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005360 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005361 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005362 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005363 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005364 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005365 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005366 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005367 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005368 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005369 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005370 handleClearStreamUseCaseOverrides();
5371 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005372 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005373 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005374 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005375 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005376 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005377 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005378 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005379 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005380 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005381 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005382 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005383 }
5384 printHelp(err);
5385 return BAD_VALUE;
5386}
5387
malikakash82ed4352023-07-21 22:44:34 +00005388status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5389 uid_t uid = IPCThreadState::self()->getCallingUid();
5390 if (uid != AID_ROOT) {
5391 dprintf(err, "Must be adb root\n");
5392 return PERMISSION_DENIED;
5393 }
5394 if (args.size() != 4) {
5395 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5396 return BAD_VALUE;
5397 }
Austin Borgered99f642023-06-01 16:51:35 -07005398 std::string packageName = toStdString(args[1]);
5399 std::string cameraIdToReplace = toStdString(args[2]);
5400 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005401 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5402 return OK;
5403}
5404
Svet Ganova453d0d2018-01-11 15:37:58 -08005405status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005406 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005407
Svet Ganova453d0d2018-01-11 15:37:58 -08005408 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005409 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005410 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005411 } else if ((args[2] != toString16("idle"))) {
5412 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005413 return BAD_VALUE;
5414 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005415
5416 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005417 if (args.size() >= 5 && args[3] == toString16("--user")) {
5418 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005419 }
5420
5421 uid_t uid;
5422 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5423 return BAD_VALUE;
5424 }
5425
5426 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005427 return NO_ERROR;
5428}
5429
5430status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005431 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005432
5433 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005434 if (args.size() >= 4 && args[2] == toString16("--user")) {
5435 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005436 }
5437
5438 uid_t uid;
5439 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005440 return BAD_VALUE;
5441 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005442
5443 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005444 return NO_ERROR;
5445}
5446
5447status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005448 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005449
5450 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005451 if (args.size() >= 4 && args[2] == toString16("--user")) {
5452 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005453 }
5454
5455 uid_t uid;
5456 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005457 return BAD_VALUE;
5458 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005459
5460 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005461 return dprintf(out, "active\n");
5462 } else {
5463 return dprintf(out, "idle\n");
5464 }
5465}
5466
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005467status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005468 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005469 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5470 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5471 Mutex::Autolock lock(mServiceLock);
5472
5473 mOverrideRotateAndCropMode = rotateValue;
5474
5475 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5476
5477 const auto clients = mActiveClientManager.getAll();
5478 for (auto& current : clients) {
5479 if (current != nullptr) {
5480 const auto basicClient = current->getValue();
5481 if (basicClient.get() != nullptr) {
5482 basicClient->setRotateAndCropOverride(rotateValue);
5483 }
5484 }
5485 }
5486
5487 return OK;
5488}
5489
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005490status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5491 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005492 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005493 if ((*end != '\0') ||
5494 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5495 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5496 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5497 return BAD_VALUE;
5498 }
5499
5500 Mutex::Autolock lock(mServiceLock);
5501 mOverrideAutoframingMode = autoframingValue;
5502
5503 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5504
5505 const auto clients = mActiveClientManager.getAll();
5506 for (auto& current : clients) {
5507 if (current != nullptr) {
5508 const auto basicClient = current->getValue();
5509 if (basicClient.get() != nullptr) {
5510 basicClient->setAutoframingOverride(autoframingValue);
5511 }
5512 }
5513 }
5514
5515 return OK;
5516}
5517
Ravneetaeb20dc2022-03-30 05:33:03 +00005518status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005519 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005520
5521 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5522
5523 Mutex::Autolock lock(mServiceLock);
5524
5525 mCameraServiceWatchdogEnabled = enableWatchdog;
5526
5527 const auto clients = mActiveClientManager.getAll();
5528 for (auto& current : clients) {
5529 if (current != nullptr) {
5530 const auto basicClient = current->getValue();
5531 if (basicClient.get() != nullptr) {
5532 basicClient->setCameraServiceWatchdog(enableWatchdog);
5533 }
5534 }
5535 }
5536
5537 return OK;
5538}
5539
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005540status_t CameraService::handleGetRotateAndCrop(int out) {
5541 Mutex::Autolock lock(mServiceLock);
5542
5543 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5544}
5545
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005546status_t CameraService::handleGetAutoframing(int out) {
5547 Mutex::Autolock lock(mServiceLock);
5548
5549 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5550}
5551
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005552status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5553 char *endPtr;
5554 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005555 std::string maskString = toStdString(args[1]);
5556 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005557
5558 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005559 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005560 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5561
5562 Mutex::Autolock lock(mServiceLock);
5563
5564 mImageDumpMask = maskValue;
5565
5566 return OK;
5567}
5568
5569status_t CameraService::handleGetImageDumpMask(int out) {
5570 Mutex::Autolock lock(mServiceLock);
5571
5572 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5573}
5574
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005575status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005576 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005577 if (errno != 0) return BAD_VALUE;
5578
5579 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5580 Mutex::Autolock lock(mServiceLock);
5581
5582 mOverrideCameraMuteMode = (muteValue == 1);
5583
5584 const auto clients = mActiveClientManager.getAll();
5585 for (auto& current : clients) {
5586 if (current != nullptr) {
5587 const auto basicClient = current->getValue();
5588 if (basicClient.get() != nullptr) {
5589 if (basicClient->supportsCameraMute()) {
5590 basicClient->setCameraMute(mOverrideCameraMuteMode);
5591 }
5592 }
5593 }
5594 }
5595
5596 return OK;
5597}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005598
Shuzhen Wang16610a62022-12-15 22:38:07 -08005599status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5600 std::vector<int64_t> useCasesOverride;
5601 for (size_t i = 1; i < args.size(); i++) {
5602 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005603 std::string arg = toStdString(args[i]);
5604 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005605 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005606 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005607 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07005608 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005609 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07005610 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005611 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07005612 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005613 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07005614 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005615 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07005616 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005617 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5618 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005619 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005620 return BAD_VALUE;
5621 }
5622 useCasesOverride.push_back(useCase);
5623 }
5624
5625 Mutex::Autolock lock(mServiceLock);
5626 mStreamUseCaseOverrides = std::move(useCasesOverride);
5627
5628 return OK;
5629}
5630
5631void CameraService::handleClearStreamUseCaseOverrides() {
5632 Mutex::Autolock lock(mServiceLock);
5633 mStreamUseCaseOverrides.clear();
5634}
5635
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005636status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
5637 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005638 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005639 if ((*end != '\0') ||
5640 (zoomOverrideValue != -1 &&
5641 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
5642 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
5643 return BAD_VALUE;
5644 }
5645
5646 Mutex::Autolock lock(mServiceLock);
5647 mZoomOverrideValue = zoomOverrideValue;
5648
5649 const auto clients = mActiveClientManager.getAll();
5650 for (auto& current : clients) {
5651 if (current != nullptr) {
5652 const auto basicClient = current->getValue();
5653 if (basicClient.get() != nullptr) {
5654 if (basicClient->supportsZoomOverride()) {
5655 basicClient->setZoomOverride(mZoomOverrideValue);
5656 }
5657 }
5658 }
5659 }
5660
5661 return OK;
5662}
5663
Avichal Rakesh84147132021-11-11 17:47:11 -08005664status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07005665 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005666 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005667 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005668 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005669 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005670 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005671 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005672 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005673 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005674 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005675 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005676 dprintf(outFd, "Camera service watch commands:\n"
5677 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
5678 " starts watching the provided tags for clients with provided package\n"
5679 " recognizes tag shorthands like '3a'\n"
5680 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005681 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005682 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005683 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005684 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08005685 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005686 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005687 return BAD_VALUE;
5688}
5689
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005690status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
5691 Mutex::Autolock lock(mLogLock);
5692 size_t tagsIdx; // index of '-m'
5693 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07005694 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005695 if (tagsIdx < args.size() - 1) {
5696 tags = args[tagsIdx + 1];
5697 } else {
5698 dprintf(outFd, "No tags provided.\n");
5699 return BAD_VALUE;
5700 }
5701
5702 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07005703 // watch all clients if no clients are provided
5704 String16 clients = toString16(kWatchAllClientsFlag);
5705 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005706 clientsIdx++);
5707 if (clientsIdx < args.size() - 1) {
5708 clients = args[clientsIdx + 1];
5709 }
Austin Borgered99f642023-06-01 16:51:35 -07005710 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005711
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005712 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07005713 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005714
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005715 bool serviceLock = tryLock(mServiceLock);
5716 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005717 auto cameraClients = mActiveClientManager.getAll();
5718 for (const auto &clientDescriptor: cameraClients) {
5719 if (clientDescriptor == nullptr) { continue; }
5720 sp<BasicClient> client = clientDescriptor->getValue();
5721 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005722
5723 if (isClientWatchedLocked(client.get())) {
5724 client->startWatchingTags(mMonitorTags, outFd);
5725 numWatchedClients++;
5726 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005727 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005728 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
5729
5730 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005731 return OK;
5732}
5733
5734status_t CameraService::stopWatchingTags(int outFd) {
5735 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005736 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005737 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005738
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005739 mWatchedClientPackages.clear();
5740 mWatchedClientsDumpCache.clear();
5741
5742 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005743 auto cameraClients = mActiveClientManager.getAll();
5744 for (const auto &clientDescriptor : cameraClients) {
5745 if (clientDescriptor == nullptr) { continue; }
5746 sp<BasicClient> client = clientDescriptor->getValue();
5747 if (client.get() == nullptr) { continue; }
5748 client->stopWatchingTags(outFd);
5749 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005750 dprintf(outFd, "Stopped watching all clients.\n");
5751 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005752 return OK;
5753}
5754
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005755status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
5756 Mutex::Autolock lock(mLogLock);
5757 size_t clearedSize = mWatchedClientsDumpCache.size();
5758 mWatchedClientsDumpCache.clear();
5759 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
5760 return OK;
5761}
5762
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005763status_t CameraService::printWatchedTags(int outFd) {
5764 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07005765 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005766
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005767 bool printedSomething = false; // tracks if any monitoring information was printed
5768 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005769
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005770 bool serviceLock = tryLock(mServiceLock);
5771 // get all watched clients that are currently connected
5772 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
5773 if (clientDescriptor == nullptr) { continue; }
5774
5775 sp<BasicClient> client = clientDescriptor->getValue();
5776 if (client.get() == nullptr) { continue; }
5777 if (!isClientWatchedLocked(client.get())) { continue; }
5778
5779 std::vector<std::string> dumpVector;
5780 client->dumpWatchedEventsToVector(dumpVector);
5781
5782 size_t printIdx = dumpVector.size();
5783 if (printIdx == 0) {
5784 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005785 }
5786
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005787 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07005788 const std::string &cameraId = clientDescriptor->getKey();
5789 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005790 while(printIdx > 0) {
5791 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07005792 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005793 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08005794 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005795 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005796 printedSomething = true;
5797
5798 connectedMonitoredClients.emplace(client->getPackageName());
5799 }
5800 if (serviceLock) { mServiceLock.unlock(); }
5801
5802 // Print entries in mWatchedClientsDumpCache for clients that are not connected
5803 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07005804 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005805 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
5806 continue;
5807 }
5808
Austin Borgered99f642023-06-01 16:51:35 -07005809 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005810 dprintf(outFd, "%s\n", kv.second.c_str());
5811 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005812 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005813
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005814 if (!printedSomething) {
5815 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005816 }
5817
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005818 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005819}
5820
Avichal Rakesh84147132021-11-11 17:47:11 -08005821// Print all events in vector `events' that came after lastPrintedEvent
5822void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005823 const std::string &cameraId,
5824 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08005825 const std::vector<std::string> &events,
5826 const std::string &lastPrintedEvent) {
5827 if (events.empty()) { return; }
5828
5829 // index of lastPrintedEvent in events.
5830 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
5831 size_t lastPrintedIdx;
5832 for (lastPrintedIdx = 0;
5833 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
5834 lastPrintedIdx++);
5835
5836 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
5837
Avichal Rakesh84147132021-11-11 17:47:11 -08005838 // print events in chronological order (latest event last)
5839 size_t idxToPrint = lastPrintedIdx;
5840 do {
5841 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07005842 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
5843 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08005844 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08005845}
5846
5847// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
5848// command should be interrupted if the user presses the return key, or if user loses any way to
5849// signal interrupt.
5850// If timeoutMs == 0, this function will always return false
5851bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
5852 struct timeval startTime;
5853 int startTimeError = gettimeofday(&startTime, nullptr);
5854 if (startTimeError) {
5855 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5856 return true;
5857 }
5858
5859 const nfds_t numFds = 1;
5860 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
5861
5862 struct timeval currTime;
5863 char buffer[2];
5864 while(true) {
5865 int currTimeError = gettimeofday(&currTime, nullptr);
5866 if (currTimeError) {
5867 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
5868 return true;
5869 }
5870
5871 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
5872 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
5873 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
5874
5875 if (remainingTimeMs <= 0) {
5876 // No user interrupt within timeoutMs, don't interrupt watch command
5877 return false;
5878 }
5879
5880 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
5881 if (numFdsUpdated < 0) {
5882 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5883 return true;
5884 }
5885
5886 if (numFdsUpdated == 0) {
5887 // No user input within timeoutMs, don't interrupt watch command
5888 return false;
5889 }
5890
5891 if (!(pollFd.revents & POLLIN)) {
5892 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
5893 return true;
5894 }
5895
5896 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
5897 if (sizeRead < 0) {
5898 dprintf(outFd, "Error reading user input. Exiting.\n");
5899 return true;
5900 }
5901
5902 if (sizeRead == 0) {
5903 // Reached end of input fd (can happen if input is piped)
5904 // User has no way to signal an interrupt, so interrupt here
5905 return true;
5906 }
5907
5908 if (buffer[0] == '\n') {
5909 // User pressed return, interrupt watch command.
5910 return true;
5911 }
5912 }
5913}
5914
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005915status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
5916 int inFd, int outFd) {
5917 // Figure out refresh interval, if present in args
5918 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005919 if (args.size() > 2) {
5920 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07005921 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005922 intervalIdx++);
5923
5924 size_t intervalValIdx = intervalIdx + 1;
5925 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07005926 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005927 if (errno) { return BAD_VALUE; }
5928 }
5929 }
5930
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005931 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
5932 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005933
Avichal Rakesh84147132021-11-11 17:47:11 -08005934 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07005935 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005936
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005937 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08005938 bool serviceLock = tryLock(mServiceLock);
5939 auto cameraClients = mActiveClientManager.getAll();
5940 if (serviceLock) { mServiceLock.unlock(); }
5941
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005942 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005943 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005944 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005945
5946 sp<BasicClient> client = clientDescriptor->getValue();
5947 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005948 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005949
Austin Borgered99f642023-06-01 16:51:35 -07005950 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08005951 // This also initializes the map entries with an empty string
5952 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
5953
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005954 std::vector<std::string> latestEvents;
5955 client->dumpWatchedEventsToVector(latestEvents);
5956
5957 if (!latestEvents.empty()) {
5958 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07005959 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08005960 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005961 latestEvents,
5962 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08005963 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005964 }
5965 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005966 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005967 break;
5968 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005969 }
5970 return OK;
5971}
5972
Austin Borgered99f642023-06-01 16:51:35 -07005973void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005974 mWatchedClientPackages.clear();
5975
Austin Borgered99f642023-06-01 16:51:35 -07005976 std::istringstream iss(clients);
5977 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005978
Austin Borgered99f642023-06-01 16:51:35 -07005979 while (std::getline(iss, nextClient, ',')) {
5980 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005981 // Don't need to track any other package if 'all' is present
5982 mWatchedClientPackages.clear();
5983 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
5984 break;
5985 }
5986
5987 // track package names
5988 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005989 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005990}
5991
Svet Ganova453d0d2018-01-11 15:37:58 -08005992status_t CameraService::printHelp(int out) {
5993 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07005994 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
5995 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
5996 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005997 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
5998 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
5999 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006000 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6001 " Valid values 0=false, 1=true, 2=auto\n"
6002 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006003 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6004 " Valid values 0=OFF, 1=ON for JPEG\n"
6005 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006006 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006007 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6008 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6009 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6010 " on. In case the number of usecases is smaller than the number of streams, the\n"
6011 " last use case is assigned to all the remaining streams. In case of multiple\n"
6012 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6013 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6014 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6015 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006016 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6017 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
malikakash82ed4352023-07-21 22:44:34 +00006018 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006019 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006020 " help print this message\n");
6021}
6022
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006023bool CameraService::isClientWatched(const BasicClient *client) {
6024 Mutex::Autolock lock(mLogLock);
6025 return isClientWatchedLocked(client);
6026}
6027
6028bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6029 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6030 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6031}
6032
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006033int32_t CameraService::updateAudioRestriction() {
6034 Mutex::Autolock lock(mServiceLock);
6035 return updateAudioRestrictionLocked();
6036}
6037
6038int32_t CameraService::updateAudioRestrictionLocked() {
6039 int32_t mode = 0;
6040 // iterate through all active client
6041 for (const auto& i : mActiveClientManager.getAll()) {
6042 const auto clientSp = i->getValue();
6043 mode |= clientSp->getAudioRestriction();
6044 }
6045
6046 bool modeChanged = (mAudioRestriction != mode);
6047 mAudioRestriction = mode;
6048 if (modeChanged) {
6049 mAppOps.setCameraAudioRestriction(mode);
6050 }
6051 return mode;
6052}
6053
Austin Borgered99f642023-06-01 16:51:35 -07006054status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006055 sp<BasicClient> clientSp) {
6056 std::unique_ptr<AutoConditionLock> lock =
6057 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6058 status_t res = NO_ERROR;
6059 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006060 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006061 mInjectionStatusListener->notifyInjectionError(
6062 externalCamId, UNKNOWN_TRANSACTION);
6063 clientSp->notifyError(
6064 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6065 CaptureResultExtras());
6066
6067 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6068 // other clients from connecting in mServiceLockWrapper if held
6069 mServiceLock.unlock();
6070
6071 // Clear caller identity temporarily so client disconnect PID checks work correctly
6072 int64_t token = CameraThreadState::clearCallingIdentity();
6073 clientSp->disconnect();
6074 CameraThreadState::restoreCallingIdentity(token);
6075
6076 // Reacquire mServiceLock
6077 mServiceLock.lock();
6078 }
6079
6080 return res;
6081}
6082
Cliff Wud3a05312021-04-26 23:07:31 +08006083void CameraService::clearInjectionParameters() {
6084 {
6085 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006086 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006087 mInjectionInternalCamId = "";
6088 }
6089 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006090 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006091}
6092
Mathias Agopian65ab4712010-07-14 17:59:35 -07006093}; // namespace android