blob: 78c14b2b572182257b213826a2c11fd176e60208 [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>
Svet Ganova453d0d2018-01-11 15:37:58 -080041#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080042#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/MemoryBase.h>
45#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080046#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080048#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070049#include <com_android_internal_camera_flags.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"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070086#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080088namespace {
89 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080090 const char* kActivityServiceName = "activity";
91 const char* kSensorPrivacyServiceName = "sensor_privacy";
92 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070093 const char* kProcessInfoServiceName = "processinfo";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080094}; // namespace anonymous
95
Mathias Agopian65ab4712010-07-14 17:59:35 -070096namespace android {
97
Austin Borgerea931242021-12-13 23:10:41 +000098using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -070099using namespace camera3::SessionConfigurationUtils;
100
101using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700102using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700103using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800104using hardware::ICamera;
105using hardware::ICameraClient;
106using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800107using hardware::camera2::ICameraInjectionCallback;
108using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800109using hardware::camera2::utils::CameraIdAndSessionConfiguration;
110using hardware::camera2::utils::ConcurrentCameraIdCombination;
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700111namespace flags = com::android::internal::camera::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800112
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113// ----------------------------------------------------------------------------
114// Logging support -- this is for debugging only
115// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700116volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117
Steve Blockb8a80522011-12-20 16:23:08 +0000118#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
119#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120
121static void setLogLevel(int level) {
122 android_atomic_write(level, &gLogLevel);
123}
124
Henri Chataingbcb99452023-11-01 17:40:30 +0000125int32_t format_as(CameraService::StatusInternal s) {
126 return fmt::underlying(s);
127}
128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130
Austin Borger249e6592024-03-10 22:28:11 -0700131// Permission strings (references to AttributionAndPermissionUtils for brevity)
132static const std::string &sDumpPermission =
133 AttributionAndPermissionUtils::sDumpPermission;
134static const std::string &sManageCameraPermission =
135 AttributionAndPermissionUtils::sManageCameraPermission;
136static const std::string &sCameraSendSystemEventsPermission =
137 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
138static const std::string &sCameraInjectExternalCameraPermission =
139 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
140
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000141// Constant integer for FGS Logging, used to denote the API type for logger
142static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700143const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800144static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
145static constexpr int32_t kSystemNativeClientState =
146 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700147static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700148
Austin Borgered99f642023-06-01 16:51:35 -0700149const std::string CameraService::kOfflineDevice("offline-");
150const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700151
Rucha Katakward9ea6452021-05-06 11:57:16 -0700152// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700153static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700154
Austin Borger74fca042022-05-23 12:41:21 -0700155CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700156 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
157 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
158 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
159 std::make_shared<AttributionAndPermissionUtils>()\
160 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700161 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
162 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800163 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800164 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700165 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700166 mSoundRef(0), mInitialized(false),
167 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000168 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700169 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800170 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700171 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
172 if (mMemFd == -1) {
173 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175}
176
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800177// The word 'System' here does not refer to clients only on the system
178// partition. They just need to have a android system uid.
179static bool doesClientHaveSystemUid() {
180 return (CameraThreadState::getCallingUid() < AID_APP_START);
181}
182
Charles Chena7b613c2023-01-24 21:57:33 +0000183// Enable processes with isolated AID to request the binder
184void CameraService::instantiate() {
185 CameraService::publish(true);
186}
187
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800188void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700189 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800190 return;
191 }
192
193 ALOGV("appops service registered. setting camera audio restriction");
194 mAppOps.setCameraAudioRestriction(mAudioRestriction);
195}
196
Iliyan Malchev8951a972011-04-14 16:55:59 -0700197void CameraService::onFirstRef()
198{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700199
Ruben Brunkcc776712015-02-17 20:18:47 -0800200 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800201
Iliyan Malchev8951a972011-04-14 16:55:59 -0700202 BnCameraService::onFirstRef();
203
Ruben Brunk99e69712015-05-26 17:25:07 -0700204 // Update battery life tracking if service is restarting
205 BatteryNotifier& notifier(BatteryNotifier::getInstance());
206 notifier.noteResetCamera();
207 notifier.noteResetFlashlight();
208
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800209 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800210
Emilian Peevf53f66e2017-04-11 14:29:43 +0100211 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800212 if (res == OK) {
213 mInitialized = true;
214 }
215
Svet Ganova453d0d2018-01-11 15:37:58 -0800216 mUidPolicy = new UidPolicy(this);
217 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700218 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800219 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800220 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800221
222 // appops function setCamerAudioRestriction uses getService which
223 // is blocking till the appops service is ready. To enable early
224 // boot availability for cameraservice, use checkService which is
225 // non blocking and register for notifications
226 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700227 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800228 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700229 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800230 } else {
231 mAppOps.setCameraAudioRestriction(mAudioRestriction);
232 }
233
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700234 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
235 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000236 // Deprecated, so it will fail to register on newer devices
237 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700238 __FUNCTION__);
239 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700240
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700241 if (!AidlCameraService::registerService(this)) {
242 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
243 }
244
Shuzhen Wang24b44152019-09-20 10:38:11 -0700245 // This needs to be last call in this function, so that it's as close to
246 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700247 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700248 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800249}
250
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800251status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800252 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100253
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800254 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000255 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800256 {
257 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800258
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800259 if (nullptr == mCameraProviderManager.get()) {
260 mCameraProviderManager = new CameraProviderManager();
261 res = mCameraProviderManager->initialize(this);
262 if (res != OK) {
263 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
264 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700265 logServiceError("Unable to initialize camera provider manager",
266 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100268 }
269 }
270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271
272 // Setup vendor tags before we call get_camera_info the first time
273 // because HAL might need to setup static vendor keys in get_camera_info
274 // TODO: maybe put this into CameraProviderManager::initialize()?
275 mCameraProviderManager->setUpVendorTags();
276
277 if (nullptr == mFlashlight.get()) {
278 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700279 }
280
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800281 res = mFlashlight->findFlashUnits();
282 if (res != OK) {
283 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
284 }
285
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000286 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800287 }
288
289
290 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700291 if (getCameraState(cameraId) == nullptr) {
292 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800293 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000294 if (unavailPhysicalIds.count(cameraId) > 0) {
295 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700296 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 }
298 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800299 }
300
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700301 // Derive primary rear/front cameras, and filter their charactierstics.
302 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700303 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700304 // Assume internal cameras are advertised from the same
305 // provider. If multiple providers are registered at different time,
306 // and each provider contains multiple internal color cameras, the current
307 // logic may filter the characteristics of more than one front/rear color
308 // cameras.
309 Mutex::Autolock l(mServiceLock);
310 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700311 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700312
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800313 return OK;
314}
315
Austin Borgered99f642023-06-01 16:51:35 -0700316void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700317 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800318 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800319 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700320 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
321 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000322 ALOGV("%s: Skipping torch callback for system-only camera device %s",
323 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700324 continue;
325 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700326 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700327 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700328 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
329 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000330 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
331 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700332 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000333 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
334 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700335 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000336 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
337 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
338 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800339 }
340}
341
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800343 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800344 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800345 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800346 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347}
348
Emilian Peevaee727d2017-05-04 16:35:48 +0100349void CameraService::onNewProviderRegistered() {
350 enumerateProviders();
351}
352
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700353void CameraService::filterAPI1SystemCameraLocked(
354 const std::vector<std::string> &normalDeviceIds) {
355 mNormalDeviceIdsWithoutSystemCamera.clear();
356 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700357 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700358 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700359 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
360 continue;
361 }
362 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700363 // All system camera ids will necessarily come after public camera
364 // device ids as per the HAL interface contract.
365 break;
366 }
367 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
368 }
369 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
370 mNormalDeviceIdsWithoutSystemCamera.size());
371}
372
Austin Borgered99f642023-06-01 16:51:35 -0700373status_t CameraService::getSystemCameraKind(const std::string& cameraId,
374 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700375 auto state = getCameraState(cameraId);
376 if (state != nullptr) {
377 *kind = state->getSystemCameraKind();
378 return OK;
379 }
380 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700381 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382}
383
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800384void CameraService::updateCameraNumAndIds() {
385 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700386 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
387 // Excludes hidden secure cameras
388 mNumberOfCameras =
389 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
390 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800391 mNormalDeviceIds =
392 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800394}
395
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700396void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700397 // To claim to be S Performance primary cameras, the cameras must be
398 // backward compatible. So performance class primary camera Ids must be API1
399 // compatible.
400 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
401 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
402 int facing = -1;
403 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800404 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700405 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800406 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700407 if (facing == -1) {
408 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
409 return;
410 }
411
412 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
413 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700414 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
415 if (res == OK) {
416 mPerfClassPrimaryCameraIds.insert(cameraId);
417 } else {
418 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
419 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
420 break;
421 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422
423 if (facing == hardware::CAMERA_FACING_BACK) {
424 firstRearCameraSeen = true;
425 }
426 if (facing == hardware::CAMERA_FACING_FRONT) {
427 firstFrontCameraSeen = true;
428 }
429 }
430
431 if (firstRearCameraSeen && firstFrontCameraSeen) {
432 break;
433 }
434 }
435}
436
Austin Borgered99f642023-06-01 16:51:35 -0700437void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700438 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100439 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
440 if (res != OK) {
441 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
442 return;
443 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000444 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700445 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
446 if (res != OK) {
447 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
448 return;
449 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000450 std::vector<std::string> physicalCameraIds;
451 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700452 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100453 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700454 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100455 }
456
457 {
458 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700459 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000460 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100461 }
462
Austin Borgered99f642023-06-01 16:51:35 -0700463 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100464 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700465 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800466
Austin Borgered99f642023-06-01 16:51:35 -0700467 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100468 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800469
470 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700471 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100472}
473
Austin Borgered99f642023-06-01 16:51:35 -0700474void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800475 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700476 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100477 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700478 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100479 }
480
481 {
482 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700483 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100484 }
485}
486
Austin Borgered99f642023-06-01 16:51:35 -0700487void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800488 CameraDeviceStatus newHalStatus) {
489 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700490 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700491
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800492 StatusInternal newStatus = mapToInternal(newHalStatus);
493
Austin Borgered99f642023-06-01 16:51:35 -0700494 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800495
496 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700497 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700499 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100500
501 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700502 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100503
Austin Borgered99f642023-06-01 16:51:35 -0700504 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700505 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700506 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700507 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700508 return;
509 }
510
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800511 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800512
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800514 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700515 return;
516 }
517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000519 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
520 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800521
522 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
523 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700524 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800525
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800526 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700527 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800528 // Don't do this in updateStatus to avoid deadlock over mServiceLock
529 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700530
Ruben Brunkcc776712015-02-17 20:18:47 -0800531 // Remove cached shim parameters
532 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700533
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800534 // Remove online as well as offline client from the list of active clients,
535 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700536 clientToDisconnectOnline = removeClientLocked(cameraId);
537 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700538 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800539
Austin Borgered99f642023-06-01 16:51:35 -0700540 disconnectClient(cameraId, clientToDisconnectOnline);
541 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700542
Austin Borgered99f642023-06-01 16:51:35 -0700543 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800544 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000546 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
547 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700548 }
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700550 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800551}
Igor Murashkincba2c162013-03-20 15:56:31 -0700552
Austin Borgered99f642023-06-01 16:51:35 -0700553void CameraService::onDeviceStatusChanged(const std::string& id,
554 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800555 CameraDeviceStatus newHalStatus) {
556 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700557 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800558
559 StatusInternal newStatus = mapToInternal(newHalStatus);
560
561 std::shared_ptr<CameraState> state = getCameraState(id);
562
563 if (state == nullptr) {
564 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700565 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800566 return;
567 }
568
569 StatusInternal logicalCameraStatus = state->getStatus();
570 if (logicalCameraStatus != StatusInternal::PRESENT &&
571 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
572 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700573 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800574 return;
575 }
576
577 bool updated = false;
578 if (newStatus == StatusInternal::PRESENT) {
579 updated = state->removeUnavailablePhysicalId(physicalId);
580 } else {
581 updated = state->addUnavailablePhysicalId(physicalId);
582 }
583
584 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700585 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800586 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000587 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800588 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000589 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800590 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700591 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
592 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
593 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700594 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700595 return;
596 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800597 Mutex::Autolock lock(mStatusListenerLock);
598 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700599 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
600 listener->getListenerPid(), listener->getListenerUid())) {
601 ALOGV("Skipping discovery callback for system-only camera device %s",
602 id.c_str());
603 continue;
604 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700605 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700606 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700607 listener->handleBinderStatus(ret,
608 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
609 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
610 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800611 }
612 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700613}
614
Austin Borgered99f642023-06-01 16:51:35 -0700615void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800616 if (clientToDisconnect.get() != nullptr) {
617 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700618 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800619 // Notify the client of disconnection
620 clientToDisconnect->notifyError(
621 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
622 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800623 clientToDisconnect->disconnect();
624 }
625}
626
Austin Borgered99f642023-06-01 16:51:35 -0700627void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800628 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700629 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
630 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
631 if (res != OK) {
632 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700633 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700634 return;
635 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800636 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700637 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800638}
639
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700640
Austin Borgered99f642023-06-01 16:51:35 -0700641void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700642 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
643 Mutex::Autolock al(mTorchStatusMutex);
644 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
645}
646
Austin Borgered99f642023-06-01 16:51:35 -0700647void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800648 int32_t newStrengthLevel) {
649 Mutex::Autolock lock(mStatusListenerLock);
650 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700651 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700652 i->handleBinderStatus(ret,
653 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
654 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800655 }
656}
657
Austin Borgered99f642023-06-01 16:51:35 -0700658void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700659 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800660 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700661 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800662
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800663 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800664 status_t res = getTorchStatusLocked(cameraId, &status);
665 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700666 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700667 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800668 return;
669 }
670 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800671 return;
672 }
673
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800674 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800675 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800676 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
677 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678 return;
679 }
680
Ruben Brunkcc776712015-02-17 20:18:47 -0800681 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700682 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700683 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700684 auto iter = mTorchUidMap.find(cameraId);
685 if (iter != mTorchUidMap.end()) {
686 int oldUid = iter->second.second;
687 int newUid = iter->second.first;
688 BatteryNotifier& notifier(BatteryNotifier::getInstance());
689 if (oldUid != newUid) {
690 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800691 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700692 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700693 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800694 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700695 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700696 }
697 iter->second.second = newUid;
698 } else {
699 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800700 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700701 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700702 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700703 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700704 }
705 }
706 }
707 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700708 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800709}
710
Austin Borger249e6592024-03-10 22:28:11 -0700711bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700712 // Returns false if this is not an automotive device type.
713 if (!isAutomotiveDevice())
714 return false;
715
716 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700717 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700718 return false;
719
720 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
721 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
722 // This isn't a known camera ID, so it's not a system camera.
723 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
724 return false;
725 }
726
727 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
728 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
729 return false;
730 }
731
732 CameraMetadata cameraInfo;
733 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700734 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700735 if (res != OK){
736 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
737 cam_id.c_str());
738 return false;
739 }
740
741 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
742 if (auto_location.count != 1)
743 return false;
744
745 uint8_t location = auto_location.data.u8[0];
746 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
747 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
748 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
749 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
750 return false;
751 }
752
753 return true;
754}
755
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800756Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700757 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100758 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700759 bool hasSystemCameraPermissions =
Austin Borger1c1bee02023-06-01 16:51:35 -0700760 hasPermissionsForSystemCamera(std::string(), CameraThreadState::getCallingPid(),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700761 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700762 switch (type) {
763 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700764 if (hasSystemCameraPermissions) {
765 *numCameras = static_cast<int>(mNormalDeviceIds.size());
766 } else {
767 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
768 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800769 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700770 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700771 if (hasSystemCameraPermissions) {
772 *numCameras = mNumberOfCameras;
773 } else {
774 *numCameras = mNumberOfCamerasWithoutSystemCamera;
775 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700777 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800778 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700779 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800780 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
781 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700782 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784}
785
malikakash73125c62023-07-21 22:44:34 +0000786Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700787 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000788 const int pid = CameraThreadState::getCallingPid();
789 const int uid = CameraThreadState::getCallingUid();
790 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
791 __FUNCTION__, pid, uid);
792 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
793 "Permission Denial: no permission to configure camera id mapping");
794 }
795 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000796 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000797 if (!parseStatus.isOk()) {
798 return parseStatus;
799 }
800 remapCameraIds(cameraIdRemappingMap);
801 return Status::ok();
802}
803
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700804Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
805 /* out */
806 hardware::camera2::impl::CameraMetadataNative* request) {
807 ATRACE_CALL();
808
809 if (!flags::feature_combination_query()) {
810 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
811 "Camera subsystem doesn't support this method!");
812 }
813 if (!mInitialized) {
814 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
815 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
816 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
817 }
818
819 const std::string cameraId = resolveCameraId(unresolvedCameraId,
820 CameraThreadState::getCallingUid());
821
822 binder::Status res;
823 if (request == nullptr) {
824 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
825 "Camera %s: Error creating default request", cameraId.c_str());
826 return res;
827 }
828 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
829 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
830 cameraId, templateId, &tempId);
831 if (!res.isOk()) {
832 ALOGE("%s: Camera %s: failed to map request Template %d",
833 __FUNCTION__, cameraId.c_str(), templateId);
834 return res;
835 }
836
837 if (shouldRejectSystemCameraConnection(cameraId)) {
838 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
839 "request for system only device %s: ", cameraId.c_str());
840 }
841
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700842 CameraMetadata metadata;
843 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
844 if (err == OK) {
845 request->swap(metadata);
846 } else if (err == BAD_VALUE) {
847 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
848 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
849 cameraId.c_str(), templateId, strerror(-err), err);
850 } else {
851 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
852 "Camera %s: Error creating default request for template %d: %s (%d)",
853 cameraId.c_str(), templateId, strerror(-err), err);
854 }
855 return res;
856}
857
858Status CameraService::isSessionConfigurationWithParametersSupported(
859 const std::string& unresolvedCameraId,
860 const SessionConfiguration& sessionConfiguration,
861 /*out*/
862 bool* supported) {
863 ATRACE_CALL();
864
865 if (!flags::feature_combination_query()) {
866 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
867 "Camera subsystem doesn't support this method!");
868 }
869 if (!mInitialized) {
870 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
871 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
872 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
873 }
874
875 const std::string cameraId = resolveCameraId(unresolvedCameraId,
876 CameraThreadState::getCallingUid());
877 if (supported == nullptr) {
878 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
879 unresolvedCameraId.c_str());
880 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
881 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
882 }
883
884 if (shouldRejectSystemCameraConnection(cameraId)) {
885 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
886 "session configuration with parameters support for system only device %s: ",
887 cameraId.c_str());
888 }
889
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700890 *supported = false;
891 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
892 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
893 supported);
894 binder::Status res;
895 switch (ret) {
896 case OK:
897 // Expected, do nothing.
898 break;
899 case INVALID_OPERATION: {
900 std::string msg = fmt::sprintf(
901 "Camera %s: Session configuration query not supported!",
902 cameraId.c_str());
903 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
904 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
905 }
906
907 break;
908 default: {
909 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
910 strerror(-ret), ret);
911 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
912 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
913 msg.c_str());
914 }
915 }
916
917 return res;
918}
919
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800920Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
921 int targetSdkVersion, bool overrideToPortrait,
922 const SessionConfiguration& sessionConfiguration,
923 /*out*/ CameraMetadata* outMetadata) {
924 ATRACE_CALL();
925
926 if (!mInitialized) {
927 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
928 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
929 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
930 }
931
932 const std::string cameraId =
933 resolveCameraId(unresolvedCameraId, CameraThreadState::getCallingUid());
934
935 if (outMetadata == nullptr) {
936 std::string msg =
937 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
938 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
939 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
940 }
941
942 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
943 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
944
945 status_t ret = mCameraProviderManager->getSessionCharacteristics(
946 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
947
948 // TODO(b/303645857): Remove fingerprintable metadata if the caller process does not have
949 // camera access permission.
950
951 Status res = Status::ok();
952 switch (ret) {
953 case OK:
954 // Expected, no handling needed.
955 break;
956 case INVALID_OPERATION: {
957 std::string msg = fmt::sprintf(
958 "Camera %s: Session characteristics query not supported!",
959 cameraId.c_str());
960 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
961 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
962 }
963 break;
964 default: {
965 std::string msg = fmt::sprintf("Camera %s: Error: %s (%d)", cameraId.c_str(),
966 strerror(-ret), ret);
967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
968 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
969 }
970 }
971
972 return res;
973}
974
malikakash82ed4352023-07-21 22:44:34 +0000975Status CameraService::parseCameraIdRemapping(
976 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +0000977 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700978 std::string packageName;
979 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +0000980 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +0000981 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +0000982 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +0000983 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
984 "CameraIdRemapping: Package name cannot be empty");
985 }
malikakash214f6e62023-08-10 23:50:56 +0000986 if (packageIdRemapping.cameraIdsToReplace.size()
987 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +0000988 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
989 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +0000990 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +0000991 }
malikakash214f6e62023-08-10 23:50:56 +0000992 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700993 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
994 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +0000995 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +0000996 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
997 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700998 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000999 }
1000 if (cameraIdToReplace == updatedCameraId) {
1001 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1002 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1003 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001004 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001005 }
1006 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001007 }
1008 }
1009 return Status::ok();
1010}
1011
1012void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1013 // Acquire mServiceLock and prevent other clients from connecting
1014 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1015 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1016
malikakashedb38962023-09-06 00:03:35 +00001017 // Collect all existing clients for camera Ids that are being
1018 // remapped in the new cameraIdRemapping, but only if they were being used by a
1019 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001020 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001021 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001022 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1023 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001024 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001025 id0.c_str(), id1.c_str());
1026 auto clientDescriptor = mActiveClientManager.get(id0);
1027 if (clientDescriptor != nullptr) {
1028 sp<BasicClient> clientSp = clientDescriptor->getValue();
1029 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001030 // This camera is being used by a targeted packageName and
1031 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001032 clientsToDisconnect.push_back(clientSp);
1033 cameraIdsToUpdate.push_back(id0);
1034 }
1035 }
1036 }
1037 }
1038
malikakashedb38962023-09-06 00:03:35 +00001039 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001040 // Notify the clients about the disconnection.
1041 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001042 CaptureResultExtras{});
1043 }
malikakash82ed4352023-07-21 22:44:34 +00001044
1045 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1046 // blocking other clients from connecting in mServiceLockWrapper if held.
1047 mServiceLock.unlock();
1048
malikakashedb38962023-09-06 00:03:35 +00001049 // Clear calling identity for disconnect() PID checks.
1050 int64_t token = CameraThreadState::clearCallingIdentity();
1051
malikakash82ed4352023-07-21 22:44:34 +00001052 // Disconnect clients.
1053 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001054 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1055 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001056 clientSp->disconnect();
1057 }
1058
malikakashedb38962023-09-06 00:03:35 +00001059 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1060 clientsToDisconnect.clear();
1061
1062 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001063 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001064
1065 {
1066 Mutex::Autolock lock(mCameraIdRemappingLock);
1067 // Update mCameraIdRemapping.
1068 mCameraIdRemapping.clear();
1069 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1070 }
malikakash82ed4352023-07-21 22:44:34 +00001071}
1072
malikakash22af94c2023-12-04 18:13:14 +00001073Status CameraService::injectSessionParams(
1074 const std::string& cameraId,
1075 const CameraMetadata& sessionParams) {
1076 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
1077 const int pid = CameraThreadState::getCallingPid();
1078 const int uid = CameraThreadState::getCallingUid();
1079 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1080 __FUNCTION__, pid, uid);
1081 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1082 "Permission Denial: no permission to inject session params");
1083 }
1084
1085 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1086 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1087
1088 auto clientDescriptor = mActiveClientManager.get(cameraId);
1089 if (clientDescriptor == nullptr) {
1090 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1091 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1092 "No active client for camera id %s", cameraId.c_str());
1093 }
1094
1095 sp<BasicClient> clientSp = clientDescriptor->getValue();
1096 status_t res = clientSp->injectSessionParams(sessionParams);
1097
1098 if (res != OK) {
1099 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1100 "Error injecting session params into camera \"%s\": %s (%d)",
1101 cameraId.c_str(), strerror(-res), res);
1102 }
1103 return Status::ok();
1104}
1105
Austin Borgered99f642023-06-01 16:51:35 -07001106std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1107 const std::string& inputCameraId, int clientUid) {
1108 std::string packageName = getPackageNameFromUid(clientUid);
1109 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001110 Mutex::Autolock lock(mCameraIdRemappingLock);
1111 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1112 packageMapIter != mCameraIdRemapping.end()) {
1113 for (auto& [id0, id1]: packageMapIter->second) {
1114 if (id1 == inputCameraId) {
1115 cameraIds.push_back(id0);
1116 }
1117 }
1118 }
1119 return cameraIds;
1120}
1121
Austin Borgered99f642023-06-01 16:51:35 -07001122std::string CameraService::resolveCameraId(
1123 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001124 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001125 const std::string& packageName) {
1126 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001127 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001128 packageNameVal = getPackageNameFromUid(clientUid);
1129 }
malikakash65d20692023-09-07 01:06:33 +00001130 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001131 // We shouldn't remap cameras for processes with system/vendor UIDs.
1132 return inputCameraId;
1133 }
malikakash82ed4352023-07-21 22:44:34 +00001134 Mutex::Autolock lock(mCameraIdRemappingLock);
1135 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1136 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001137 auto packageMap = packageMapIter->second;
1138 if (auto replacementIdIter = packageMap.find(inputCameraId);
1139 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001140 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001141 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001142 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001143 replacementIdIter->second.c_str());
1144 return replacementIdIter->second;
1145 }
1146 }
1147 return inputCameraId;
1148}
1149
Austin Borger18b30a72022-10-27 12:20:29 -07001150Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001151 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001152 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001153 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001154 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
1155 std::string cameraIdStr = resolveCameraId(
1156 unresolvedCameraId, CameraThreadState::getCallingUid());
1157
Austin Borgered99f642023-06-01 16:51:35 -07001158 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001159 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1160 "characteristics for system only device %s: ", cameraIdStr.c_str());
1161 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001162
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001163 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001164 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001165 return STATUS_ERROR(ERROR_DISCONNECTED,
1166 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001167 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001168 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001169 CameraThreadState::getCallingPid(), CameraThreadState::getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001170 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1171 if (hasSystemCameraPermissions) {
1172 cameraIdBound = mNumberOfCameras;
1173 }
1174 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1176 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 }
1178
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001179 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001180 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001181 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001182 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001183 if (err != OK) {
1184 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1185 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1186 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001187 logServiceError(std::string("Error retrieving camera info from device ")
1188 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001189 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001190
Ruben Brunkcc776712015-02-17 20:18:47 -08001191 return ret;
1192}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001193
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001194std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001195 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
1196 auto callingPid = CameraThreadState::getCallingPid();
1197 auto callingUid = CameraThreadState::getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001198 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1199 callingPid, callingUid, /* checkCameraPermissions= */ false);
1200 if (systemCameraPermissions || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001201 deviceIds = &mNormalDeviceIds;
1202 }
1203 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001204 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001205 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001206 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001207 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001208
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001209 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001210}
1211
Austin Borgered99f642023-06-01 16:51:35 -07001212std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001213 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001214 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001215}
1216
Austin Borgered99f642023-06-01 16:51:35 -07001217Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001218 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001219 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001220
malikakashedb38962023-09-06 00:03:35 +00001221 const std::string cameraId = resolveCameraId(unresolvedCameraId,
1222 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -07001223
Zhijun He2b59be82013-09-25 10:14:30 -07001224 if (!cameraInfo) {
1225 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001226 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001227 }
1228
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001229 if (!mInitialized) {
1230 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001231 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001232 return STATUS_ERROR(ERROR_DISCONNECTED,
1233 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001234 }
1235
Austin Borgered99f642023-06-01 16:51:35 -07001236 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001237 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001238 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001239 }
1240
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001241 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001242
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001243 bool overrideForPerfClass =
1244 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001245 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001246 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001247 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001248 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001249 if (res == NAME_NOT_FOUND) {
1250 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001251 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001252 strerror(-res), res);
1253 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001254 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1255 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001256 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001257 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001258 strerror(-res), res);
1259 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001260 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001261 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001262 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1263 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001264 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001265 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001266 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001267 int callingPid = CameraThreadState::getCallingPid();
1268 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001269 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001270 // If it's not calling from cameraserver, check the permission only if
1271 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1272 // it would've already been checked in shouldRejectSystemCameraConnection.
Austin Borger249e6592024-03-10 22:28:11 -07001273 bool checkPermissionForCamera = hasPermissionsForCamera(cameraId, callingPid, callingUid);
Emilian Peeve20c6372018-08-14 18:45:53 +01001274 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001275 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001276 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001277 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001278 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001279 &tagsRemoved);
1280 if (res != OK) {
1281 cameraInfo->clear();
1282 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1283 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001284 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001285 }
1286 }
1287
1288 if (!tagsRemoved.empty()) {
1289 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1290 tagsRemoved.data(), tagsRemoved.size());
1291 if (res != OK) {
1292 cameraInfo->clear();
1293 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001294 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001295 strerror(-res), res);
1296 }
1297 }
1298
Zhijun He2b59be82013-09-25 10:14:30 -07001299 return ret;
1300}
1301
malikakashedb38962023-09-06 00:03:35 +00001302Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001303 int32_t* torchStrength) {
1304 ATRACE_CALL();
1305 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001306
malikakashedb38962023-09-06 00:03:35 +00001307 const std::string cameraId = resolveCameraId(
malikakash65d20692023-09-07 01:06:33 +00001308 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001309 if (!mInitialized) {
1310 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1311 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1312 }
1313
1314 if(torchStrength == NULL) {
1315 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1316 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1317 }
1318
Austin Borgered99f642023-06-01 16:51:35 -07001319 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001320 if (res != OK) {
1321 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001322 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001323 strerror(-res), res);
1324 }
1325 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1326 return Status::ok();
1327}
1328
Austin Borgered99f642023-06-01 16:51:35 -07001329std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001330 time_t now = time(nullptr);
1331 char formattedTime[64];
1332 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001333 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001334}
1335
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001336Status CameraService::getCameraVendorTagDescriptor(
1337 /*out*/
1338 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001339 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001340 if (!mInitialized) {
1341 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001342 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001343 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001344 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1345 if (globalDescriptor != nullptr) {
1346 *desc = *(globalDescriptor.get());
1347 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001348 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001349}
1350
Emilian Peev71c73a22017-03-21 16:35:51 +00001351Status CameraService::getCameraVendorTagCache(
1352 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1353 ATRACE_CALL();
1354 if (!mInitialized) {
1355 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1356 return STATUS_ERROR(ERROR_DISCONNECTED,
1357 "Camera subsystem not available");
1358 }
1359 sp<VendorTagDescriptorCache> globalCache =
1360 VendorTagDescriptorCache::getGlobalVendorTagCache();
1361 if (globalCache != nullptr) {
1362 *cache = *(globalCache.get());
1363 }
1364 return Status::ok();
1365}
1366
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001367void CameraService::clearCachedVariables() {
1368 BasicClient::BasicClient::sCameraService = nullptr;
1369}
1370
Austin Borgered99f642023-06-01 16:51:35 -07001371std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001372 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001373 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001374
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001375 int deviceVersion = 0;
1376
Emilian Peevf53f66e2017-04-11 14:29:43 +01001377 status_t res;
1378 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001379 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001380 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001381 if (res != OK || transport == IPCTransport::INVALID) {
1382 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001383 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001384 return std::make_pair(-1, IPCTransport::INVALID) ;
1385 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001386 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001387
Emilian Peevf53f66e2017-04-11 14:29:43 +01001388 hardware::CameraInfo info;
1389 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001390 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001391 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001392 if (res != OK) {
1393 return std::make_pair(-1, IPCTransport::INVALID);
1394 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001395 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001396 if (orientation) {
1397 *orientation = info.orientation;
1398 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001399 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001400
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001401 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001402}
1403
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001404Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001405 switch(err) {
1406 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001407 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001408 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001409 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1410 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001411 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412 return STATUS_ERROR(ERROR_DISCONNECTED,
1413 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001414 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001415 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1416 "Camera HAL encountered error %d: %s",
1417 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001418 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001419}
1420
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001421Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001422 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1423 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001424 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001425 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001426 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001427 bool forceSlowJpegMode, const std::string& originalCameraId,
1428 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001429 // For HIDL devices
1430 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1431 // Create CameraClient based on device version reported by the HAL.
1432 int deviceVersion = deviceVersionAndTransport.first;
1433 switch(deviceVersion) {
1434 case CAMERA_DEVICE_API_VERSION_1_0:
1435 ALOGE("Camera using old HAL version: %d", deviceVersion);
1436 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1437 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001438 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001439 break;
1440 case CAMERA_DEVICE_API_VERSION_3_0:
1441 case CAMERA_DEVICE_API_VERSION_3_1:
1442 case CAMERA_DEVICE_API_VERSION_3_2:
1443 case CAMERA_DEVICE_API_VERSION_3_3:
1444 case CAMERA_DEVICE_API_VERSION_3_4:
1445 case CAMERA_DEVICE_API_VERSION_3_5:
1446 case CAMERA_DEVICE_API_VERSION_3_6:
1447 case CAMERA_DEVICE_API_VERSION_3_7:
1448 break;
1449 default:
1450 // Should not be reachable
1451 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1452 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1453 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001454 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001455 }
1456 }
1457 if (effectiveApiLevel == API_1) { // Camera1 API route
1458 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001459 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001460 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001461 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001462 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1463 forceSlowJpegMode);
1464 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1465 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001466 } else { // Camera2 API route
1467 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1468 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001469 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001470 cameraService->mCameraServiceProxyWrapper,
1471 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001472 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001473 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001474 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001475 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001476 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001477}
1478
Austin Borgered99f642023-06-01 16:51:35 -07001479std::string CameraService::toString(std::set<userid_t> intSet) {
1480 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001481 bool first = true;
1482 for (userid_t i : intSet) {
1483 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001484 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001485 first = false;
1486 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001487 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001488 }
1489 }
Austin Borgered99f642023-06-01 16:51:35 -07001490 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001491}
1492
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001493int32_t CameraService::mapToInterface(TorchModeStatus status) {
1494 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1495 switch (status) {
1496 case TorchModeStatus::NOT_AVAILABLE:
1497 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1498 break;
1499 case TorchModeStatus::AVAILABLE_OFF:
1500 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1501 break;
1502 case TorchModeStatus::AVAILABLE_ON:
1503 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1504 break;
1505 default:
1506 ALOGW("Unknown new flash status: %d", status);
1507 }
1508 return serviceStatus;
1509}
1510
1511CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1512 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1513 switch (status) {
1514 case CameraDeviceStatus::NOT_PRESENT:
1515 serviceStatus = StatusInternal::NOT_PRESENT;
1516 break;
1517 case CameraDeviceStatus::PRESENT:
1518 serviceStatus = StatusInternal::PRESENT;
1519 break;
1520 case CameraDeviceStatus::ENUMERATING:
1521 serviceStatus = StatusInternal::ENUMERATING;
1522 break;
1523 default:
1524 ALOGW("Unknown new HAL device status: %d", status);
1525 }
1526 return serviceStatus;
1527}
1528
1529int32_t CameraService::mapToInterface(StatusInternal status) {
1530 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1531 switch (status) {
1532 case StatusInternal::NOT_PRESENT:
1533 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1534 break;
1535 case StatusInternal::PRESENT:
1536 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1537 break;
1538 case StatusInternal::ENUMERATING:
1539 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1540 break;
1541 case StatusInternal::NOT_AVAILABLE:
1542 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1543 break;
1544 case StatusInternal::UNKNOWN:
1545 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1546 break;
1547 default:
1548 ALOGW("Unknown new internal device status: %d", status);
1549 }
1550 return serviceStatus;
1551}
1552
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001553Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001554 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001555
Austin Borgered99f642023-06-01 16:51:35 -07001556 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001558 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001559 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001560 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1561 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001562 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001563 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001564 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001565 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001566 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001567 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001568 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001569}
1570
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001571Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001572 /*out*/
1573 CameraParameters* parameters) {
1574
1575 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1576
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001578
1579 if (parameters == NULL) {
1580 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001582 }
1583
malikakashedb38962023-09-06 00:03:35 +00001584 std::string unresolvedCameraId = std::to_string(cameraId);
1585 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1586 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001587
1588 // Check if we already have parameters
1589 {
1590 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001591 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001592 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001593 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001594 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001595 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001596 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001597 }
1598 CameraParameters p = cameraState->getShimParams();
1599 if (!p.isEmpty()) {
1600 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001601 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001602 }
1603 }
1604
Jayant Chowdhary12361932018-08-27 14:46:13 -07001605 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001606 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001607 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001609 // Error already logged by callee
1610 return ret;
1611 }
1612
1613 // Check for parameters again
1614 {
1615 // Scope for service lock
1616 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001617 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001618 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001619 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001621 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001622 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001623 CameraParameters p = cameraState->getShimParams();
1624 if (!p.isEmpty()) {
1625 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001627 }
1628 }
1629
Ruben Brunkcc776712015-02-17 20:18:47 -08001630 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1631 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001633}
1634
Austin Borgered99f642023-06-01 16:51:35 -07001635Status CameraService::validateConnectLocked(const std::string& cameraId,
1636 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001637 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001638
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001639#ifdef __BRILLO__
1640 UNUSED(clientName8);
1641 UNUSED(clientUid);
1642 UNUSED(clientPid);
1643 UNUSED(originalClientPid);
1644#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001645 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1646 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001647 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001648 return allowed;
1649 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001650#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001651
Jayant Chowdhary12361932018-08-27 14:46:13 -07001652 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001653
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001654 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1656 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001657 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001658 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001659 }
1660
Ruben Brunkcc776712015-02-17 20:18:47 -08001661 if (getCameraState(cameraId) == nullptr) {
1662 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001663 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001664 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001665 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 }
1667
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001668 status_t err = checkIfDeviceIsUsable(cameraId);
1669 if (err != NO_ERROR) {
1670 switch(err) {
1671 case -ENODEV:
1672 case -EBUSY:
1673 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001674 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001675 default:
1676 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001677 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001678 }
1679 }
1680 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001681}
1682
Austin Borgered99f642023-06-01 16:51:35 -07001683Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1684 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001685 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001686 int callingPid = CameraThreadState::getCallingPid();
1687 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001689 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001691 clientUid = callingUid;
1692 } else if (!isTrustedCallingUid(callingUid)) {
1693 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1694 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001695 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1696 "Untrusted caller (calling PID %d, UID %d) trying to "
1697 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001698 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001699 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 }
1701
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001702 // Check if we can trust clientPid
1703 if (clientPid == USE_CALLING_PID) {
1704 clientPid = callingPid;
1705 } else if (!isTrustedCallingUid(callingUid)) {
1706 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1707 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001708 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1709 "Untrusted caller (calling PID %d, UID %d) trying to "
1710 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001711 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001712 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001713 }
1714
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001715 if (shouldRejectSystemCameraConnection(cameraId)) {
1716 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1717 cameraId.c_str());
1718 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001719 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001720 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001721 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1722 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001723 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001724 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001725 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001726
1727 }
1728
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001729 // If it's not calling from cameraserver, check the permission if the
1730 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1731 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001732 bool checkPermissionForCamera =
1733 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001734 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001735 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001736 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001737 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1738 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001739 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001740 }
1741
Svet Ganova453d0d2018-01-11 15:37:58 -08001742 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001743 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001744 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001745 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1746 clientPid, clientUid);
1747 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001748 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1749 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001750 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001751 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001752 }
1753
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001754 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1755 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1756 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1757 if ((!isAutomotivePrivilegedClient(callingUid) ||
1758 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1759 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001760 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1761 return STATUS_ERROR_FMT(ERROR_DISABLED,
1762 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001763 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001764 }
1765
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001766 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1767 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001768 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001769 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770
Ruben Brunk6267b532015-04-30 17:44:07 -07001771 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001772
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001773 // For non-system clients : Only allow clients who are being used by the current foreground
1774 // device user, unless calling from our own process.
1775 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001776 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001777 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1778 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001779 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001780 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1781 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001782 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001783 }
1784
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001785 if (flags::camera_hsum_permission()) {
1786 // If the System User tries to access the camera when the device is running in
1787 // headless system user mode, ensure that client has the required permission
1788 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001789 if (isHeadlessSystemUserMode()
1790 && (clientUserId == USER_SYSTEM)
1791 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001792 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1793 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1794 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1795 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001796 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001797 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001798 }
1799
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001800 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001801}
1802
Austin Borgered99f642023-06-01 16:51:35 -07001803status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001804 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001805 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001806 if (cameraState == nullptr) {
1807 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001808 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001809 return -ENODEV;
1810 }
1811
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001812 StatusInternal currentStatus = cameraState->getStatus();
1813 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001814 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001815 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001816 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001817 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001818 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001819 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001820 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001821 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001822
Ruben Brunkcc776712015-02-17 20:18:47 -08001823 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001824}
1825
Ruben Brunkcc776712015-02-17 20:18:47 -08001826void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001827 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001828
Ruben Brunkcc776712015-02-17 20:18:47 -08001829 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001830 auto clientDescriptor =
1831 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001832 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001833 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1834
1835 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001836 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001837
1838 if (evicted.size() > 0) {
1839 // This should never happen - clients should already have been removed in disconnect
1840 for (auto& i : evicted) {
1841 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001842 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001843 }
1844
1845 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1846 __FUNCTION__);
1847 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001848
1849 // And register a death notification for the client callback. Do
1850 // this last to avoid Binder policy where a nested Binder
1851 // transaction might be pre-empted to service the client death
1852 // notification if the client process dies before linkToDeath is
1853 // invoked.
1854 sp<IBinder> remoteCallback = client->getRemote();
1855 if (remoteCallback != nullptr) {
1856 remoteCallback->linkToDeath(this);
1857 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001858}
1859
Austin Borgered99f642023-06-01 16:51:35 -07001860status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1861 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1862 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001863 /*out*/
1864 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001865 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001866 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001867 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001868 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001869 DescriptorPtr clientDescriptor;
1870 {
1871 if (effectiveApiLevel == API_1) {
1872 // If we are using API1, any existing client for this camera ID with the same remote
1873 // should be returned rather than evicted to allow MediaRecorder to work properly.
1874
1875 auto current = mActiveClientManager.get(cameraId);
1876 if (current != nullptr) {
1877 auto clientSp = current->getValue();
1878 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001879 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001880 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001881 " API level, evicting prior client...");
1882 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001883 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001884 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001885 *client = clientSp;
1886 return NO_ERROR;
1887 }
1888 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001889 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001890 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001891
Ruben Brunkcc776712015-02-17 20:18:47 -08001892 // Get state for the given cameraId
1893 auto state = getCameraState(cameraId);
1894 if (state == nullptr) {
1895 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001896 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001897 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001898 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001899 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001900
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001901 sp<IServiceManager> sm = defaultServiceManager();
1902 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
1903 if (!binder && isAutomotivePrivilegedClient(CameraThreadState::getCallingUid())) {
1904 // If processinfo service is not available and the client is automotive privileged
1905 // client used for safety critical uses cases such as rear-view and surround-view which
1906 // needs to be available before android boot completes, then use the hardcoded values
1907 // for the process state and priority score. As this scenario is before android system
1908 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1909 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1910 // visible on the top.
1911 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1912 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1913 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1914 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1915 } else {
1916 // Get current active client PIDs
1917 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1918 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001919
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001920 std::vector<int> priorityScores(ownerPids.size());
1921 std::vector<int> states(ownerPids.size());
1922
1923 // Get priority scores of all active PIDs
1924 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1925 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1926 if (err != OK) {
1927 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1928 return err;
1929 }
1930
1931 // Update all active clients' priorities
1932 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1933 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1934 pidToPriorityMap.emplace(ownerPids[i],
1935 resource_policy::ClientPriority(priorityScores[i], states[i],
1936 /* isVendorClient won't get copied over*/ false,
1937 /* oomScoreOffset won't get copied over*/ 0));
1938 }
1939 mActiveClientManager.updatePriorities(pidToPriorityMap);
1940
1941 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1942 int32_t actualState = states[states.size() - 1];
1943
1944 // Make descriptor for incoming client. We store the oomScoreOffset
1945 // since we might need it later on new handleEvictionsLocked and
1946 // ProcessInfoService would not take that into account.
1947 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1948 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1949 state->getConflicting(), actualScore, clientPid, actualState,
1950 oomScoreOffset, systemNativeClient);
1951 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001952
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001953 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1954
Ruben Brunkcc776712015-02-17 20:18:47 -08001955 // Find clients that would be evicted
1956 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1957
1958 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1959 // background, so we cannot do evictions
1960 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1961 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1962 " priority).", clientPid);
1963
1964 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001965 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001966 auto incompatibleClients =
1967 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1968
Austin Borgered99f642023-06-01 16:51:35 -07001969 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1970 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1971 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001972 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001973
1974 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001975 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001976 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001977 i->getKey().c_str(),
1978 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001979 i->getOwnerId(), i->getPriority().getScore(),
1980 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001981 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07001982 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
1983 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001984 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001985 }
1986
1987 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001988 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001989 mEventLog.add(msg);
1990
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001991 auto current = mActiveClientManager.get(cameraId);
1992 if (current != nullptr) {
1993 return -EBUSY; // CAMERA_IN_USE
1994 } else {
1995 return -EUSERS; // MAX_CAMERAS_IN_USE
1996 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001997 }
1998
1999 for (auto& i : evicted) {
2000 sp<BasicClient> clientSp = i->getValue();
2001 if (clientSp.get() == nullptr) {
2002 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2003
2004 // TODO: Remove this
2005 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2006 __FUNCTION__);
2007 mActiveClientManager.remove(i);
2008 continue;
2009 }
2010
2011 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002012 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002013 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002014
Ruben Brunkcc776712015-02-17 20:18:47 -08002015 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002016 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002017 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2018 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002019 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002020 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002021 i->getPriority().getState(), cameraId.c_str(),
2022 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002023 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002024
2025 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002026 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002027 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002028 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002029 }
2030
Ruben Brunkcc776712015-02-17 20:18:47 -08002031 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2032 // other clients from connecting in mServiceLockWrapper if held
2033 mServiceLock.unlock();
2034
2035 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002036 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002037
2038 // Destroy evicted clients
2039 for (auto& i : evictedClients) {
2040 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002041 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002042 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002043
Jayant Chowdhary12361932018-08-27 14:46:13 -07002044 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002045
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002046 for (const auto& i : evictedClients) {
2047 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002048 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002049 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2050 if (ret == TIMED_OUT) {
2051 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002052 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2053 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002054 return -EBUSY;
2055 }
2056 if (ret != NO_ERROR) {
2057 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002058 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2059 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002060 return ret;
2061 }
2062 }
2063
2064 evictedClients.clear();
2065
Ruben Brunkcc776712015-02-17 20:18:47 -08002066 // Once clients have been disconnected, relock
2067 mServiceLock.lock();
2068
2069 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2070 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2071 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002072 }
2073
Ruben Brunkcc776712015-02-17 20:18:47 -08002074 *partial = clientDescriptor;
2075 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002076}
2077
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002078Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002079 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002080 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002081 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002082 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002083 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002084 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002085 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002086 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002087 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002088 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002089
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002090 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002091 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002092
malikakashedb38962023-09-06 00:03:35 +00002093 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
2094 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
2095 CameraThreadState::getCallingUid());
2096
Ruben Brunkcc776712015-02-17 20:18:47 -08002097 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002098 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2099 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002100 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002101 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002102
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002103 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002104 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
2105 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002107 }
2108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002109 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002110
2111 const sp<IServiceManager> sm(defaultServiceManager());
2112 const auto& mActivityManager = getActivityManager();
2113 if (mActivityManager) {
2114 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2115 CameraThreadState::getCallingUid(),
2116 CameraThreadState::getCallingPid());
2117 }
2118
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002119 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002120}
2121
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002122bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2123 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002124 // If the client is not a vendor client, don't add listener if
2125 // a) the camera is a publicly hidden secure camera OR
2126 // b) the camera is a system only camera and the client doesn't
2127 // have android.permission.SYSTEM_CAMERA permissions.
2128 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2129 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002130 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002131 return true;
2132 }
2133 return false;
2134}
2135
Austin Borgered99f642023-06-01 16:51:35 -07002136bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002137 // Rules for rejection:
2138 // 1) If cameraserver tries to access this camera device, accept the
2139 // connection.
2140 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002141 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002142 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2143 // and the serving thread is a non hwbinder thread, the client must have
2144 // android.permission.SYSTEM_CAMERA permissions to connect.
2145
2146 int cPid = CameraThreadState::getCallingPid();
2147 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002148 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002149 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2150 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002151 // This isn't a known camera ID, so it's not a system camera
2152 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2153 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002154 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002155
2156 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002157 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002158 return false;
2159 }
2160 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002161 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002162 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2163 return true;
2164 }
2165 // (3) Here we only check for permissions if it is a system only camera device. This is since
2166 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2167 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2168 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002169 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002170 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002171 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2172 cameraId.c_str());
2173 return true;
2174 }
2175
2176 return false;
2177}
2178
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002179Status CameraService::connectDevice(
2180 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002181 const std::string& unresolvedCameraId,
2182 const std::string& clientPackageName,
2183 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002184 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002185 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08002186 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002187 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002188
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002189 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002190 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002191 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002192 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002193 int callingPid = CameraThreadState::getCallingPid();
Austin Borger249e6592024-03-10 22:28:11 -07002194 int callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002195 bool systemNativeClient = false;
2196 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002197 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002198 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002199 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002200 }
Austin Borger249e6592024-03-10 22:28:11 -07002201
malikakashedb38962023-09-06 00:03:35 +00002202 const std::string cameraId = resolveCameraId(
2203 unresolvedCameraId,
Austin Borger249e6592024-03-10 22:28:11 -07002204 callingUid,
malikakashedb38962023-09-06 00:03:35 +00002205 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002206
2207 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002208 std::string msg =
2209 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2210 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2211 cameraId.c_str());
2212 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2213 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002214 }
2215
Austin Borger9bfa0a72022-08-03 17:50:40 -07002216 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002217 if (clientUid == USE_CALLING_UID) {
2218 clientUserId = multiuser_get_user_id(callingUid);
2219 }
2220
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002221 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2222 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002223 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2224 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002225 std::string msg = "Camera disabled by device policy";
2226 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2227 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002228 }
2229
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002230 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002231 if (oomScoreOffset > 0
2232 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002233 callingUid)
2234 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002235 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002236 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002237 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2238 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2239 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002240 }
2241
Austin Borgered99f642023-06-01 16:51:35 -07002242 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2243 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002244 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002245 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002246 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002247
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002248 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002249 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002250 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002251 }
2252
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002254 Mutex::Autolock lock(mServiceLock);
2255
2256 // Clear the previous cached logs and reposition the
2257 // file offset to beginning of the file to log new data.
2258 // If either truncate or lseek fails, close the previous file and create a new one.
2259 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2260 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2261 // Close the previous memfd.
2262 close(mMemFd);
2263 // If failure to wipe the data, then create a new file and
2264 // assign the new value to mMemFd.
2265 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2266 if (mMemFd == -1) {
2267 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2268 }
2269 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002270 const sp<IServiceManager> sm(defaultServiceManager());
2271 const auto& mActivityManager = getActivityManager();
2272 if (mActivityManager) {
2273 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002274 callingUid,
2275 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002276 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002277 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002278}
2279
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002280bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2281 int callingPid, int callingUid) {
2282 if (!isAutomotiveDevice()) {
2283 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2284 }
2285
2286 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2287 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2288 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2289 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2290 "using camera %s", callingUid, cam_id.c_str());
2291 return false;
2292 }
2293
2294 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2295 return true;
2296 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2297 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002298 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2299 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002300 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2301 return false;
2302 } else {
2303 return true;
2304 }
2305 }
2306 return false;
2307}
2308
Austin Borgered99f642023-06-01 16:51:35 -07002309std::string CameraService::getPackageNameFromUid(int clientUid) {
2310 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002311
2312 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002313 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002314 if (binder == 0) {
2315 ALOGE("Cannot get permission service");
2316 // Return empty package name and the further interaction
2317 // with camera will likely fail
2318 return packageName;
2319 }
2320
2321 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2322 Vector<String16> packages;
2323
2324 permCtrl->getPackagesForUid(clientUid, packages);
2325
2326 if (packages.isEmpty()) {
2327 ALOGE("No packages for calling UID %d", clientUid);
2328 // Return empty package name and the further interaction
2329 // with camera will likely fail
2330 return packageName;
2331 }
2332
2333 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002334 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002335
2336 return packageName;
2337}
2338
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002339template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002340Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2341 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2342 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002343 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002344 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002345 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002346 binder::Status ret = binder::Status::ok();
2347
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002348 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002349 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002350 int packageUid = (clientUid == USE_CALLING_UID) ?
2351 CameraThreadState::getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002352 if (clientPackageNameMaybe.size() <= 0) {
2353 // NDK calls don't come with package names, but we need one for various cases.
2354 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2355 // do exist. For all authentication cases, all packages under the same UID get the
2356 // same permissions, so picking any associated package name is sufficient. For some
2357 // other cases, this may give inaccurate names for clients in logs.
2358 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002359 clientPackageName = getPackageNameFromUid(packageUid);
2360 } else {
2361 clientPackageName = clientPackageNameMaybe;
2362 }
2363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002364 int originalClientPid = 0;
2365
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002366 int packagePid = (clientPid == USE_CALLING_PID) ?
2367 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002368 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002369 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002370 static_cast<int>(effectiveApiLevel));
2371
Shuzhen Wang316781a2020-08-18 18:11:01 -07002372 nsecs_t openTimeNs = systemTime();
2373
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002374 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002375 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002376 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002377
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002378 {
2379 // Acquire mServiceLock and prevent other clients from connecting
2380 std::unique_ptr<AutoConditionLock> lock =
2381 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2382
2383 if (lock == nullptr) {
2384 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2385 , clientPid);
2386 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2387 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002388 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002389 }
2390
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002391 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002392 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002393 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2394 return ret;
2395 }
2396
2397 // Check the shim parameters after acquiring lock, if they have already been updated and
2398 // we were doing a shim update, return immediately
2399 if (shimUpdateOnly) {
2400 auto cameraState = getCameraState(cameraId);
2401 if (cameraState != nullptr) {
2402 if (!cameraState->getShimParams().isEmpty()) return ret;
2403 }
2404 }
2405
2406 status_t err;
2407
2408 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002409 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002410 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002411 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2412 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002413 switch (err) {
2414 case -ENODEV:
2415 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2416 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002417 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002418 case -EBUSY:
2419 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2420 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002421 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002422 case -EUSERS:
2423 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2424 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002425 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002426 default:
2427 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2428 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002429 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002430 }
2431 }
2432
2433 if (clientTmp.get() != nullptr) {
2434 // Handle special case for API1 MediaRecorder where the existing client is returned
2435 device = static_cast<CLIENT*>(clientTmp.get());
2436 return ret;
2437 }
2438
2439 // give flashlight a chance to close devices if necessary.
2440 mFlashlight->prepareDeviceOpen(cameraId);
2441
Austin Borger18b30a72022-10-27 12:20:29 -07002442 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002443 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002444 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2445 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002446 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002447 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002448 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002449 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002450 }
2451
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002452 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002453 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002454 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002455 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002456 clientFeatureId, cameraId, api1CameraId, facing,
2457 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002458 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002459 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002460 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002461 return ret;
2462 }
2463 client = static_cast<CLIENT*>(tmp.get());
2464
2465 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2466 __FUNCTION__);
2467
Austin Borgered99f642023-06-01 16:51:35 -07002468 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002469 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002470 if (err != OK) {
2471 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002472 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002473 mServiceLock.unlock();
2474 client->disconnect();
2475 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002476 switch(err) {
2477 case BAD_VALUE:
2478 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002479 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002480 case -EBUSY:
2481 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002482 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002483 case -EUSERS:
2484 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2485 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002486 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002487 case PERMISSION_DENIED:
2488 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002489 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002490 case -EACCES:
2491 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002492 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002493 case -ENODEV:
2494 default:
2495 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002496 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002497 strerror(-err), err);
2498 }
2499 }
2500
2501 // Update shim paremeters for legacy clients
2502 if (effectiveApiLevel == API_1) {
2503 // Assume we have always received a Client subclass for API1
2504 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2505 String8 rawParams = shimClient->getParameters();
2506 CameraParameters params(rawParams);
2507
2508 auto cameraState = getCameraState(cameraId);
2509 if (cameraState != nullptr) {
2510 cameraState->setShimParams(params);
2511 } else {
2512 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002513 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002514 }
2515 }
2516
Ravneetaeb20dc2022-03-30 05:33:03 +00002517 // Enable/disable camera service watchdog
2518 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2519
Emilian Peev6d45db82024-01-18 20:11:54 +00002520 CameraMetadata chars;
2521 bool rotateAndCropSupported = true;
2522 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2523 &chars, overrideToPortrait);
2524 if (err == OK) {
2525 auto availableRotateCropEntry = chars.find(
2526 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2527 if (availableRotateCropEntry.count <= 1) {
2528 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002529 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002530 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002531 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2532 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002533 }
2534
Emilian Peev6d45db82024-01-18 20:11:54 +00002535 if (rotateAndCropSupported) {
2536 // Set rotate-and-crop override behavior
2537 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2538 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2539 } else if (overrideToPortrait && portraitRotation != 0) {
2540 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2541 switch (portraitRotation) {
2542 case 90:
2543 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2544 break;
2545 case 180:
2546 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2547 break;
2548 case 270:
2549 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2550 break;
2551 default:
2552 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2553 break;
2554 }
2555 client->setRotateAndCropOverride(rotateAndCropMode);
2556 } else {
2557 client->setRotateAndCropOverride(
2558 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2559 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2560 }
2561 }
2562
2563 bool autoframingSupported = true;
2564 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2565 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2566 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2567 autoframingSupported = false;
2568 }
2569
2570 if (autoframingSupported) {
2571 // Set autoframing override behaviour
2572 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2573 client->setAutoframingOverride(mOverrideAutoframingMode);
2574 } else {
2575 client->setAutoframingOverride(
2576 mCameraServiceProxyWrapper->getAutoframingOverride(
2577 clientPackageName));
2578 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002579 }
2580
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002581 bool isCameraPrivacyEnabled;
2582 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002583 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002584 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2585 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2586 } else {
2587 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002588 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002589 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002590
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002591 if (client->supportsCameraMute()) {
2592 client->setCameraMute(
2593 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2594 } else if (isCameraPrivacyEnabled) {
2595 // no camera mute supported, but privacy is on! => disconnect
2596 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2597 client->getPackageName().c_str(), cameraId.c_str());
2598 // Do not hold mServiceLock while disconnecting clients, but
2599 // retain the condition blocking other clients from connecting
2600 // in mServiceLockWrapper if held.
2601 mServiceLock.unlock();
2602 // Clear caller identity temporarily so client disconnect PID
2603 // checks work correctly
2604 int64_t token = CameraThreadState::clearCallingIdentity();
2605 // Note AppOp to trigger the "Unblock" dialog
2606 client->noteAppOp();
2607 client->disconnect();
2608 CameraThreadState::restoreCallingIdentity(token);
2609 // Reacquire mServiceLock
2610 mServiceLock.lock();
2611
2612 return STATUS_ERROR_FMT(ERROR_DISABLED,
2613 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002614 }
2615
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002616 if (shimUpdateOnly) {
2617 // If only updating legacy shim parameters, immediately disconnect client
2618 mServiceLock.unlock();
2619 client->disconnect();
2620 mServiceLock.lock();
2621 } else {
2622 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002623 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002624 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002625
2626 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002627 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002628 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002629 } // lock is destroyed, allow further connect calls
2630
2631 // Important: release the mutex here so the client can call back into the service from its
2632 // destructor (can be at the end of the call)
2633 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002634
2635 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002636 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002637 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002638
Cliff Wud3a05312021-04-26 23:07:31 +08002639 {
2640 Mutex::Autolock lock(mInjectionParametersLock);
2641 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2642 mInjectionInitPending = false;
2643 status_t res = NO_ERROR;
2644 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2645 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002646 sp<BasicClient> clientSp = clientDescriptor->getValue();
2647 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2648 if(res != OK) {
2649 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2650 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002651 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002652 }
2653 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002654 if (res != OK) {
2655 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2656 }
2657 } else {
2658 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002659 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002660 res = NO_INIT;
2661 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2662 }
2663 }
2664 }
2665
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002666 return ret;
2667}
2668
Austin Borgered99f642023-06-01 16:51:35 -07002669status_t CameraService::addOfflineClient(const std::string &cameraId,
2670 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002671 if (offlineClient.get() == nullptr) {
2672 return BAD_VALUE;
2673 }
2674
2675 {
2676 // Acquire mServiceLock and prevent other clients from connecting
2677 std::unique_ptr<AutoConditionLock> lock =
2678 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2679
2680 if (lock == nullptr) {
2681 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2682 , __FUNCTION__, offlineClient->getClientPid());
2683 return TIMED_OUT;
2684 }
2685
2686 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2687 if (onlineClientDesc.get() == nullptr) {
2688 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2689 cameraId.c_str());
2690 return BAD_VALUE;
2691 }
2692
2693 // Offline clients do not evict or conflict with other online devices. Resource sharing
2694 // conflicts are handled by the camera provider which will either succeed or fail before
2695 // reaching this method.
2696 const auto& onlinePriority = onlineClientDesc->getPriority();
2697 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2698 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002699 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002700 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002701 // native clients don't have offline processing support.
2702 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002703 if (offlineClientDesc == nullptr) {
2704 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2705 return BAD_VALUE;
2706 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002707
2708 // Allow only one offline device per camera
2709 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2710 if (!incompatibleClients.empty()) {
2711 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2712 return BAD_VALUE;
2713 }
2714
Austin Borgered99f642023-06-01 16:51:35 -07002715 std::string monitorTags = isClientWatched(offlineClient.get())
2716 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002717 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002718 if (err != OK) {
2719 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2720 return err;
2721 }
2722
2723 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2724 if (evicted.size() > 0) {
2725 for (auto& i : evicted) {
2726 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002727 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002728 }
2729
2730 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2731 "properly", __FUNCTION__);
2732
2733 return BAD_VALUE;
2734 }
2735
2736 logConnectedOffline(offlineClientDesc->getKey(),
2737 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002738 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002739
2740 sp<IBinder> remoteCallback = offlineClient->getRemote();
2741 if (remoteCallback != nullptr) {
2742 remoteCallback->linkToDeath(this);
2743 }
2744 } // lock is destroyed, allow further connect calls
2745
2746 return OK;
2747}
2748
Austin Borgered99f642023-06-01 16:51:35 -07002749Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger1c1bee02023-06-01 16:51:35 -07002750 int32_t torchStrength, const sp<IBinder>& clientBinder) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002751 Mutex::Autolock lock(mServiceLock);
2752
2753 ATRACE_CALL();
2754 if (clientBinder == nullptr) {
2755 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2756 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2757 "Torch client binder in null.");
2758 }
2759
Rucha Katakwar38284522021-11-10 11:25:21 -08002760 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002761 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002762 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002763 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002764 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002765 }
2766
2767 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002768 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002769 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002770 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002771 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002772 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002773 }
2774
2775 StatusInternal cameraStatus = state->getStatus();
2776 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2777 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002778 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002779 (int)cameraStatus);
2780 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002781 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002782 }
2783
2784 {
2785 Mutex::Autolock al(mTorchStatusMutex);
2786 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002787 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002788 if (err != OK) {
2789 if (err == NAME_NOT_FOUND) {
2790 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002791 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002792 }
2793 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002794 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002795 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2796 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002797 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002798 }
2799
2800 if (status == TorchModeStatus::NOT_AVAILABLE) {
2801 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2802 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002803 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002804 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2805 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002806 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002807 } else {
2808 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002809 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002810 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2811 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002812 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002813 }
2814 }
2815 }
2816
2817 {
2818 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002819 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002820 }
2821 // Check if the current torch strength level is same as the new one.
2822 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002823 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002824
Austin Borgered99f642023-06-01 16:51:35 -07002825 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002826
2827 if (err != OK) {
2828 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002829 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002830 switch (err) {
2831 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002832 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2833 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002834 errorCode = ERROR_ILLEGAL_ARGUMENT;
2835 break;
2836 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002837 msg = fmt::sprintf("Camera \"%s\" is in use",
2838 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002839 errorCode = ERROR_CAMERA_IN_USE;
2840 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002841 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002842 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002843 "valid range.", torchStrength);
2844 errorCode = ERROR_ILLEGAL_ARGUMENT;
2845 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002846 default:
Austin Borgered99f642023-06-01 16:51:35 -07002847 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002848 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002849 }
Austin Borgered99f642023-06-01 16:51:35 -07002850 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2851 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002852 }
2853
2854 {
2855 // update the link to client's death
2856 // Store the last client that turns on each camera's torch mode.
2857 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002858 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002859 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002860 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002861 } else {
2862 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2863 mTorchClientMap.replaceValueAt(index, clientBinder);
2864 }
2865 clientBinder->linkToDeath(this);
2866 }
2867
2868 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002869 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002870 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002871 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002872 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002873 }
2874 return Status::ok();
2875}
2876
malikakash73125c62023-07-21 22:44:34 +00002877Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002878 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002879 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002880
2881 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002882 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002883 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002884 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2885 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002886 }
2887
Jayant Chowdhary12361932018-08-27 14:46:13 -07002888 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002889 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002890
Austin Borgered99f642023-06-01 16:51:35 -07002891 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002892 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002893 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002894 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002895 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002896 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002897 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002898 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002899 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002900 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002901 }
2902
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002903 StatusInternal cameraStatus = state->getStatus();
2904 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002905 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002906 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2907 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002908 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002909 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002910 }
2911
2912 {
2913 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002914 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002915 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002916 if (err != OK) {
2917 if (err == NAME_NOT_FOUND) {
2918 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002919 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002920 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002921 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002922 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002923 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002924 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002925 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002926 }
2927
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002928 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002929 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002930 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002931 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002932 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2933 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002934 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002935 } else {
2936 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002937 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002938 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2939 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002940 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002941 }
2942 }
2943 }
2944
Ruben Brunk99e69712015-05-26 17:25:07 -07002945 {
2946 // Update UID map - this is used in the torch status changed callbacks, so must be done
2947 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002948 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002949 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002950 }
2951
Austin Borgered99f642023-06-01 16:51:35 -07002952 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002953
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002954 if (err != OK) {
2955 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002956 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002957 switch (err) {
2958 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002959 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2960 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002961 errorCode = ERROR_ILLEGAL_ARGUMENT;
2962 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002963 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002964 msg = fmt::sprintf("Camera \"%s\" is in use",
2965 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002966 errorCode = ERROR_CAMERA_IN_USE;
2967 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002968 default:
Austin Borgered99f642023-06-01 16:51:35 -07002969 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002970 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002971 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972 errorCode = ERROR_INVALID_OPERATION;
2973 }
Austin Borgered99f642023-06-01 16:51:35 -07002974 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2975 logServiceError(msg, errorCode);
2976 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002977 }
2978
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002979 {
2980 // update the link to client's death
2981 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002982 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002983 if (enabled) {
2984 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002985 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002986 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002987 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002988 mTorchClientMap.replaceValueAt(index, clientBinder);
2989 }
2990 clientBinder->linkToDeath(this);
2991 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07002992 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002993 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002994 }
2995
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07002996 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07002997 std::string torchState = enabled ? "on" : "off";
2998 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
2999 torchState.c_str(), clientPid);
3000 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003001 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003002}
3003
Austin Borgered99f642023-06-01 16:51:35 -07003004void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3005 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3006 mTorchUidMap[cameraId].first = uid;
3007 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003008 } else {
3009 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003010 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003011 }
3012}
3013
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003014Status CameraService::notifySystemEvent(int32_t eventId,
3015 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003016 const int pid = CameraThreadState::getCallingPid();
3017 const int selfPid = getpid();
3018
3019 // Permission checks
3020 if (pid != selfPid) {
3021 // Ensure we're being called by system_server, or similar process with
3022 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003023 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003024 const int uid = CameraThreadState::getCallingUid();
3025 ALOGE("Permission Denial: cannot send updates to camera service about system"
3026 " events from pid=%d, uid=%d", pid, uid);
3027 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003028 "No permission to send updates to camera service about system events"
3029 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003030 }
3031 }
3032
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003033 ATRACE_CALL();
3034
Ruben Brunk36597b22015-03-20 22:15:57 -07003035 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003036 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003037 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003038 // from a system server crash
3039 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003040 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003041 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003042 break;
3043 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003044 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3045 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003046 if (args.size() != 1) {
3047 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3048 "USB Device Event requires 1 argument");
3049 }
3050
Valentin Iftime29e2e152021-08-13 15:17:33 +02003051 // Notify CameraProviderManager for lazy HALs
3052 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3053 std::to_string(args[0]));
3054 break;
3055 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003056 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003057 default: {
3058 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3059 eventId);
3060 break;
3061 }
3062 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003063 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003064}
3065
Emilian Peev53722fa2019-02-22 17:47:20 -08003066void CameraService::notifyMonitoredUids() {
3067 Mutex::Autolock lock(mStatusListenerLock);
3068
3069 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003070 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003071 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3072 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003073 }
3074}
3075
Austin Borgerdddb7552023-03-30 17:53:01 -07003076void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3077 Mutex::Autolock lock(mStatusListenerLock);
3078
3079 for (const auto& it : mListenerList) {
3080 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3081 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3082 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3083 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3084 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3085 }
3086 }
3087}
3088
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003089Status CameraService::notifyDeviceStateChange(int64_t newState) {
3090 const int pid = CameraThreadState::getCallingPid();
3091 const int selfPid = getpid();
3092
3093 // Permission checks
3094 if (pid != selfPid) {
3095 // Ensure we're being called by system_server, or similar process with
3096 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003097 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003098 const int uid = CameraThreadState::getCallingUid();
3099 ALOGE("Permission Denial: cannot send updates to camera service about device"
3100 " state changes from pid=%d, uid=%d", pid, uid);
3101 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3102 "No permission to send updates to camera service about device state"
3103 " changes from pid=%d, uid=%d", pid, uid);
3104 }
3105 }
3106
3107 ATRACE_CALL();
3108
Austin Borger18b30a72022-10-27 12:20:29 -07003109 {
3110 Mutex::Autolock lock(mServiceLock);
3111 mDeviceState = newState;
3112 }
3113
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003114 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003115
3116 return Status::ok();
3117}
3118
Emilian Peev8b64f282021-03-25 16:49:57 -07003119Status CameraService::notifyDisplayConfigurationChange() {
3120 ATRACE_CALL();
3121 const int callingPid = CameraThreadState::getCallingPid();
3122 const int selfPid = getpid();
3123
3124 // Permission checks
3125 if (callingPid != selfPid) {
3126 // Ensure we're being called by system_server, or similar process with
3127 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003128 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07003129 const int uid = CameraThreadState::getCallingUid();
3130 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3131 " changes from pid=%d, uid=%d", callingPid, uid);
3132 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3133 "No permission to send updates to camera service about orientation"
3134 " changes from pid=%d, uid=%d", callingPid, uid);
3135 }
3136 }
3137
3138 Mutex::Autolock lock(mServiceLock);
3139
3140 // Don't do anything if rotate-and-crop override via cmd is active
3141 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3142
3143 const auto clients = mActiveClientManager.getAll();
3144 for (auto& current : clients) {
3145 if (current != nullptr) {
3146 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003147 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3148 basicClient->setRotateAndCropOverride(
3149 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3150 basicClient->getPackageName(),
3151 basicClient->getCameraFacing(),
3152 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003153 }
3154 }
3155 }
3156
3157 return Status::ok();
3158}
3159
3160Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003161 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3162 ATRACE_CALL();
3163 if (!concurrentCameraIds) {
3164 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3165 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3166 }
3167
3168 if (!mInitialized) {
3169 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003170 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003171 return STATUS_ERROR(ERROR_DISCONNECTED,
3172 "Camera subsystem is not available");
3173 }
3174 // First call into the provider and get the set of concurrent camera
3175 // combinations
3176 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003177 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003178 for (auto &combination : concurrentCameraCombinations) {
3179 std::vector<std::string> validCombination;
3180 for (auto &cameraId : combination) {
3181 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003182 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003183 if (state == nullptr) {
3184 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3185 continue;
3186 }
3187 StatusInternal status = state->getStatus();
3188 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3189 continue;
3190 }
Austin Borgered99f642023-06-01 16:51:35 -07003191 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003192 continue;
3193 }
3194 validCombination.push_back(cameraId);
3195 }
3196 if (validCombination.size() != 0) {
3197 concurrentCameraIds->push_back(std::move(validCombination));
3198 }
3199 }
3200 return Status::ok();
3201}
3202
3203Status CameraService::isConcurrentSessionConfigurationSupported(
3204 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003205 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003206 if (!isSupported) {
3207 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3208 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3209 }
3210
3211 if (!mInitialized) {
3212 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3213 return STATUS_ERROR(ERROR_DISCONNECTED,
3214 "Camera subsystem is not available");
3215 }
3216
3217 // Check for camera permissions
Austin Borger249e6592024-03-10 22:28:11 -07003218 int callingPid = CameraThreadState::getCallingPid();
3219 int callingUid = CameraThreadState::getCallingUid();
3220 bool hasCameraPermission = ((callingPid == getpid()) ||
3221 hasPermissionsForCamera(callingPid, callingUid));
3222 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003223 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3224 "android.permission.CAMERA needed to call"
3225 "isConcurrentSessionConfigurationSupported");
3226 }
3227
3228 status_t res =
3229 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003230 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3231 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003232 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003233 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003234 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003235 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3236 "support %s (%d)", strerror(-res), res);
3237 }
3238 return Status::ok();
3239}
3240
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003241Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3242 /*out*/
3243 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003244 return addListenerHelper(listener, cameraStatuses);
3245}
3246
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003247binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3248 std::vector<hardware::CameraStatus>* cameraStatuses) {
3249 return addListenerHelper(listener, cameraStatuses, false, true);
3250}
3251
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003252Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3253 /*out*/
3254 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003255 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003256
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003257 ATRACE_CALL();
3258
Igor Murashkinbfc99152013-02-27 12:55:20 -08003259 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003260
Ruben Brunk3450ba72015-06-16 11:00:37 -07003261 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003262 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003263 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003264 }
3265
Charles Chenf075f082024-03-04 23:32:55 +00003266 auto clientPid = CameraThreadState::getCallingPid();
Austin Borger249e6592024-03-10 22:28:11 -07003267 auto clientUid = CameraThreadState::getCallingUid();
3268 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003269
Igor Murashkinbfc99152013-02-27 12:55:20 -08003270 Mutex::Autolock lock(mServiceLock);
3271
Ruben Brunkcc776712015-02-17 20:18:47 -08003272 {
3273 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003274 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003275 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003276 ALOGW("%s: Tried to add listener %p which was already subscribed",
3277 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003278 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003279 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003280 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003281
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003282 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003283 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3284 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003285 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003286 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003287 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003288 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003289 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3290 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3291 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003292 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003293 // The listener still needs to be added to the list of listeners, regardless of what
3294 // permissions the listener process has / whether it is a vendor listener. Since it might be
3295 // eligible to listen to other camera ids.
3296 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003297 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003298 }
3299
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003300 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003301 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003302 Mutex::Autolock lock(mCameraStatesLock);
3303 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003304 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003305 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003306 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003307 }
3308 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003309 // Remove the camera statuses that should be hidden from the client, we do
3310 // this after collecting the states in order to avoid holding
3311 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3312 // the same time.
3313 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3314 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3315 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3316 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3317 ALOGE("%s: Invalid camera id %s, skipping status update",
3318 __FUNCTION__, s.cameraId.c_str());
3319 return true;
3320 }
3321 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3322 clientUid);}), cameraStatuses->end());
3323
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003324 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003325 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003326 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003327 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003328 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003329
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003330 /*
3331 * Immediately signal current torch status to this listener only
3332 * This may be a subset of all the devices, so don't include it in the response directly
3333 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003334 {
3335 Mutex::Autolock al(mTorchStatusMutex);
3336 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003337 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003338 // The camera id is visible to the client. Fine to send torch
3339 // callback.
3340 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3341 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3342 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003343 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003344 }
3345
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003346 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003347}
Ruben Brunkcc776712015-02-17 20:18:47 -08003348
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003349Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003350 ATRACE_CALL();
3351
Igor Murashkinbfc99152013-02-27 12:55:20 -08003352 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3353
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003354 if (listener == 0) {
3355 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003356 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003357 }
3358
Igor Murashkinbfc99152013-02-27 12:55:20 -08003359 Mutex::Autolock lock(mServiceLock);
3360
Ruben Brunkcc776712015-02-17 20:18:47 -08003361 {
3362 Mutex::Autolock lock(mStatusListenerLock);
3363 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003364 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003365 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003366 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003367 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003368 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003369 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003370 }
3371 }
3372
3373 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3374 __FUNCTION__, listener.get());
3375
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003376 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003377}
3378
Austin Borgered99f642023-06-01 16:51:35 -07003379Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003380
3381 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003382 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3383
3384 if (parameters == NULL) {
3385 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003386 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003387 }
3388
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003389 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003390
3391 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003392 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003393 // Error logged by caller
3394 return ret;
3395 }
3396
3397 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003398
Austin Borgered99f642023-06-01 16:51:35 -07003399 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003400
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003401 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003402}
3403
Austin Borgered99f642023-06-01 16:51:35 -07003404Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003405 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003406 ATRACE_CALL();
3407
malikakashedb38962023-09-06 00:03:35 +00003408 const std::string cameraId = resolveCameraId(
3409 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003410
Austin Borgered99f642023-06-01 16:51:35 -07003411 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003412
3413 switch (apiVersion) {
3414 case API_VERSION_1:
3415 case API_VERSION_2:
3416 break;
3417 default:
Austin Borgered99f642023-06-01 16:51:35 -07003418 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3419 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3420 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003421 }
3422
Austin Borger18b30a72022-10-27 12:20:29 -07003423 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003424 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003425 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003426 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3427 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3428 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003429 }
3430 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3431 int deviceVersion = deviceVersionAndTransport.first;
3432 switch (deviceVersion) {
3433 case CAMERA_DEVICE_API_VERSION_1_0:
3434 case CAMERA_DEVICE_API_VERSION_3_0:
3435 case CAMERA_DEVICE_API_VERSION_3_1:
3436 if (apiVersion == API_VERSION_2) {
3437 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003438 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003439 *isSupported = false;
3440 } else { // if (apiVersion == API_VERSION_1) {
3441 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003442 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003443 *isSupported = true;
3444 }
3445 break;
3446 case CAMERA_DEVICE_API_VERSION_3_2:
3447 case CAMERA_DEVICE_API_VERSION_3_3:
3448 case CAMERA_DEVICE_API_VERSION_3_4:
3449 case CAMERA_DEVICE_API_VERSION_3_5:
3450 case CAMERA_DEVICE_API_VERSION_3_6:
3451 case CAMERA_DEVICE_API_VERSION_3_7:
3452 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003453 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003454 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003455 break;
3456 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003457 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3458 deviceVersion, cameraId.c_str());
3459 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3460 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003461 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003462 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003463 } else {
3464 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003465 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003466 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003467}
3468
Austin Borgered99f642023-06-01 16:51:35 -07003469Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003470 /*out*/ bool *isSupported) {
3471 ATRACE_CALL();
3472
malikakashedb38962023-09-06 00:03:35 +00003473 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3474 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003475
Austin Borgered99f642023-06-01 16:51:35 -07003476 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3477 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003478
3479 return Status::ok();
3480}
3481
Cliff Wud8cae102021-03-11 01:37:42 +08003482Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003483 const std::string& packageName, const std::string& internalCamId,
3484 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003485 const sp<ICameraInjectionCallback>& callback,
3486 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003487 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003488 ATRACE_CALL();
3489
Austin Borgered99f642023-06-01 16:51:35 -07003490 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003491 const int pid = CameraThreadState::getCallingPid();
3492 const int uid = CameraThreadState::getCallingUid();
3493 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3494 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3495 "Permission Denial: no permission to inject camera");
3496 }
3497
3498 ALOGV(
3499 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3500 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003501 __FUNCTION__, packageName.c_str(),
3502 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003503
Cliff Wud3a05312021-04-26 23:07:31 +08003504 {
3505 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003506 mInjectionInternalCamId = internalCamId;
3507 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003508 mInjectionStatusListener->addListener(callback);
3509 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003510 status_t res = NO_ERROR;
3511 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3512 // If the client already exists, we can directly connect to the camera device through the
3513 // client's injectCamera(), otherwise we need to wait until the client is established
3514 // (execute connectHelper()) before injecting the camera to the camera device.
3515 if (clientDescriptor != nullptr) {
3516 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003517 sp<BasicClient> clientSp = clientDescriptor->getValue();
3518 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3519 if(res != OK) {
3520 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3521 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003522 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003523 }
3524 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003525 if(res != OK) {
3526 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3527 }
3528 } else {
3529 mInjectionInitPending = true;
3530 }
3531 }
Cliff Wud8cae102021-03-11 01:37:42 +08003532
Cliff Wud3a05312021-04-26 23:07:31 +08003533 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003534}
3535
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003536Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003537 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003538 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3539 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3540 return Status::ok();
3541}
3542
Ruben Brunkcc776712015-02-17 20:18:47 -08003543void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003544 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003545 for (auto& i : mActiveClientManager.getAll()) {
3546 auto clientSp = i->getValue();
3547 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003548 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003549 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003550 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003551 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003552 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003553}
3554
Ruben Brunkcc776712015-02-17 20:18:47 -08003555bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003556 bool ret = false;
3557 {
3558 // Acquire mServiceLock and prevent other clients from connecting
3559 std::unique_ptr<AutoConditionLock> lock =
3560 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003561
Igor Murashkin634a5152013-02-20 17:15:11 -08003562
Ruben Brunkcc776712015-02-17 20:18:47 -08003563 std::vector<sp<BasicClient>> evicted;
3564 for (auto& i : mActiveClientManager.getAll()) {
3565 auto clientSp = i->getValue();
3566 if (clientSp.get() == nullptr) {
3567 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3568 mActiveClientManager.remove(i);
3569 continue;
3570 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003571 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003572 mActiveClientManager.remove(i);
3573 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003574
Ruben Brunkcc776712015-02-17 20:18:47 -08003575 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003576 clientSp->notifyError(
3577 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003578 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003579 }
3580 }
3581
Ruben Brunkcc776712015-02-17 20:18:47 -08003582 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3583 // other clients from connecting in mServiceLockWrapper if held
3584 mServiceLock.unlock();
3585
Ruben Brunk36597b22015-03-20 22:15:57 -07003586 // Do not clear caller identity, remote caller should be client proccess
3587
Ruben Brunkcc776712015-02-17 20:18:47 -08003588 for (auto& i : evicted) {
3589 if (i.get() != nullptr) {
3590 i->disconnect();
3591 ret = true;
3592 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003593 }
3594
Ruben Brunkcc776712015-02-17 20:18:47 -08003595 // Reacquire mServiceLock
3596 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003597
Ruben Brunkcc776712015-02-17 20:18:47 -08003598 } // lock is destroyed, allow further connect calls
3599
3600 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003601}
3602
Ruben Brunkcc776712015-02-17 20:18:47 -08003603std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003604 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003605 std::shared_ptr<CameraState> state;
3606 {
3607 Mutex::Autolock lock(mCameraStatesLock);
3608 auto iter = mCameraStates.find(cameraId);
3609 if (iter != mCameraStates.end()) {
3610 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003611 }
3612 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003613 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003614}
3615
Austin Borgered99f642023-06-01 16:51:35 -07003616sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003617 // Remove from active clients list
3618 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3619 if (clientDescriptorPtr == nullptr) {
3620 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003621 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003622 return sp<BasicClient>{nullptr};
3623 }
3624
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003625 sp<BasicClient> client = clientDescriptorPtr->getValue();
3626 if (client.get() != nullptr) {
3627 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3628 }
3629 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003630}
3631
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003632void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003633 // Acquire mServiceLock and prevent other clients from connecting
3634 std::unique_ptr<AutoConditionLock> lock =
3635 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3636
Ruben Brunk6267b532015-04-30 17:44:07 -07003637 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003638 for (size_t i = 0; i < newUserIds.size(); i++) {
3639 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003640 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003641 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003642 return;
3643 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003644 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003645 }
3646
Ruben Brunka8ca9152015-04-07 14:23:40 -07003647
Ruben Brunk6267b532015-04-30 17:44:07 -07003648 if (newAllowedUsers == mAllowedUsers) {
3649 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3650 return;
3651 }
3652
3653 logUserSwitch(mAllowedUsers, newAllowedUsers);
3654
3655 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003656
3657 // Current user has switched, evict all current clients.
3658 std::vector<sp<BasicClient>> evicted;
3659 for (auto& i : mActiveClientManager.getAll()) {
3660 auto clientSp = i->getValue();
3661
3662 if (clientSp.get() == nullptr) {
3663 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3664 continue;
3665 }
3666
Ruben Brunk6267b532015-04-30 17:44:07 -07003667 // Don't evict clients that are still allowed.
3668 uid_t clientUid = clientSp->getClientUid();
3669 userid_t clientUserId = multiuser_get_user_id(clientUid);
3670 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3671 continue;
3672 }
3673
Ruben Brunk36597b22015-03-20 22:15:57 -07003674 evicted.push_back(clientSp);
3675
Ruben Brunk36597b22015-03-20 22:15:57 -07003676 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003677 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003678
Ruben Brunk36597b22015-03-20 22:15:57 -07003679 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003680 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003681 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003682 " to user switch.", i->getKey().c_str(),
3683 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003684 i->getOwnerId(), i->getPriority().getScore(),
3685 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003686
3687 }
3688
3689 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3690 // blocking other clients from connecting in mServiceLockWrapper if held.
3691 mServiceLock.unlock();
3692
3693 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003694 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003695
3696 for (auto& i : evicted) {
3697 i->disconnect();
3698 }
3699
Jayant Chowdhary12361932018-08-27 14:46:13 -07003700 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003701
3702 // Reacquire mServiceLock
3703 mServiceLock.lock();
3704}
Ruben Brunkcc776712015-02-17 20:18:47 -08003705
Austin Borgered99f642023-06-01 16:51:35 -07003706void CameraService::logEvent(const std::string &event) {
3707 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003708 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003709 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003710 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003711 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003712 mEventLog.add(msg);
3713 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3714 // Error event not added to the dumpsys log before
3715 mEventLog.add(msg);
3716 sServiceErrorEventSet.insert(msg);
3717 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003718}
3719
Austin Borgered99f642023-06-01 16:51:35 -07003720void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3721 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003722 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003723 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3724 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003725}
3726
Austin Borgered99f642023-06-01 16:51:35 -07003727void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3728 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003729 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003730 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3731 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003732}
3733
Austin Borgered99f642023-06-01 16:51:35 -07003734void CameraService::logConnected(const std::string &cameraId, int clientPid,
3735 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003736 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003737 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3738 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003739}
3740
Austin Borgered99f642023-06-01 16:51:35 -07003741void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3742 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003743 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003744 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3745 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003746}
3747
Austin Borgered99f642023-06-01 16:51:35 -07003748void CameraService::logRejected(const std::string &cameraId, int clientPid,
3749 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003750 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003751 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3752 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003753}
3754
Austin Borgered99f642023-06-01 16:51:35 -07003755void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3756 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003757 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003758 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3759 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003760}
3761
Ruben Brunk6267b532015-04-30 17:44:07 -07003762void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3763 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003764 std::string newUsers = toString(newUserIds);
3765 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003766 if (oldUsers.size() == 0) {
3767 oldUsers = "<None>";
3768 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003769 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003770 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3771 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003772}
3773
Austin Borgered99f642023-06-01 16:51:35 -07003774void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003775 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003776 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003777}
3778
Austin Borgered99f642023-06-01 16:51:35 -07003779void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003780 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003781 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003782}
3783
Austin Borgered99f642023-06-01 16:51:35 -07003784void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003785 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003786 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003787}
3788
Austin Borgered99f642023-06-01 16:51:35 -07003789void CameraService::logServiceError(const std::string &msg, int errorCode) {
3790 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3791 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003792}
3793
Ruben Brunk36597b22015-03-20 22:15:57 -07003794status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3795 uint32_t flags) {
3796
Mathias Agopian65ab4712010-07-14 17:59:35 -07003797 // Permission checks
3798 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003799 case SHELL_COMMAND_TRANSACTION: {
3800 int in = data.readFileDescriptor();
3801 int out = data.readFileDescriptor();
3802 int err = data.readFileDescriptor();
3803 int argc = data.readInt32();
3804 Vector<String16> args;
3805 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3806 args.add(data.readString16());
3807 }
3808 sp<IBinder> unusedCallback;
3809 sp<IResultReceiver> resultReceiver;
3810 status_t status;
3811 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3812 return status;
3813 }
3814 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3815 return status;
3816 }
3817 status = shellCommand(in, out, err, args);
3818 if (resultReceiver != nullptr) {
3819 resultReceiver->send(status);
3820 }
3821 return NO_ERROR;
3822 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003823 }
3824
3825 return BnCameraService::onTransact(code, data, reply, flags);
3826}
3827
Mathias Agopian65ab4712010-07-14 17:59:35 -07003828// We share the media players for shutter and recording sound for all clients.
3829// A reference count is kept to determine when we will actually release the
3830// media players.
3831
Jaekyun Seokef498052018-03-23 13:09:44 +09003832sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3833 sp<MediaPlayer> mp = new MediaPlayer();
3834 status_t error;
3835 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003836 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003837 error = mp->prepare();
3838 }
3839 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003840 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003841 mp->disconnect();
3842 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003843 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003844 }
3845 return mp;
3846}
3847
username5755fea2018-12-27 09:48:08 +08003848void CameraService::increaseSoundRef() {
3849 Mutex::Autolock lock(mSoundLock);
3850 mSoundRef++;
3851}
3852
3853void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003854 ATRACE_CALL();
3855
username5755fea2018-12-27 09:48:08 +08003856 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3857 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3858 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3859 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3860 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3861 }
3862 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3863 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3864 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3865 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003866 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003867 }
3868 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3869 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3870 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3871 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3872 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874}
3875
username5755fea2018-12-27 09:48:08 +08003876void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003877 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003878 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003879 if (--mSoundRef) return;
3880
3881 for (int i = 0; i < NUM_SOUNDS; i++) {
3882 if (mSoundPlayer[i] != 0) {
3883 mSoundPlayer[i]->disconnect();
3884 mSoundPlayer[i].clear();
3885 }
3886 }
3887}
3888
3889void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003890 ATRACE_CALL();
3891
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003893 if (kind < 0 || kind >= NUM_SOUNDS) {
3894 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3895 return;
3896 }
3897
Mathias Agopian65ab4712010-07-14 17:59:35 -07003898 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003899 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003900 sp<MediaPlayer> player = mSoundPlayer[kind];
3901 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003902 player->seekTo(0);
3903 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003904 }
3905}
3906
3907// ----------------------------------------------------------------------------
3908
3909CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003910 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07003911 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07003912 const std::string& clientPackageName, bool systemNativeClient,
3913 const std::optional<std::string>& clientFeatureId,
3914 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003915 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003916 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003917 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003918 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003919 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07003920 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003921 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003922 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003923 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003924 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003925 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003926{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003927 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003928 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003930 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003931
username5755fea2018-12-27 09:48:08 +08003932 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003933
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003934 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003935}
3936
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937// tear down the client
3938CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003939 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003940 mDestructionStarted = true;
3941
username5755fea2018-12-27 09:48:08 +08003942 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003943 // unconditionally disconnect. function is idempotent
3944 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945}
3946
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003947sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3948
Igor Murashkin634a5152013-02-20 17:15:11 -08003949CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003950 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07003951 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07003952 const std::string& clientPackageName, bool nativeClient,
3953 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003954 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003955 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07003956 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003957 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003958 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003959 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3960 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003961 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003962 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003963 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003964 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003965 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003966 mRemoteBinder(remoteCallback),
3967 mOpsActive(false),
3968 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003969{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003970 if (sCameraService == nullptr) {
3971 sCameraService = cameraService;
3972 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003973
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003974 // There are 2 scenarios in which a client won't have AppOps operations
3975 // (both scenarios : native clients)
3976 // 1) It's an system native client*, the package name will be empty
3977 // and it will return from this function in the previous if condition
3978 // (This is the same as the previously existing behavior).
3979 // 2) It is a system native client, but its package name has been
3980 // modified for debugging, however it still must not use AppOps since
3981 // the package name is not a real one.
3982 //
3983 // * system native client - native client with UID < AID_APP_START. It
3984 // doesn't exclude clients not on the system partition.
3985 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003986 mAppOpsManager = std::make_unique<AppOpsManager>();
3987 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003988
Charles Chenf075f082024-03-04 23:32:55 +00003989 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003990}
3991
3992CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003993 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08003994 mDestructionStarted = true;
3995}
3996
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003997binder::Status CameraService::BasicClient::disconnect() {
3998 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003999 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004000 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004001 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004002 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004003
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004004 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004005 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004006 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004007 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004008
4009 sp<IBinder> remote = getRemote();
4010 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004011 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004012 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004013
4014 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004015 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004016 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004017 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004018 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004019
Igor Murashkincba2c162013-03-20 15:56:31 -07004020 // client shouldn't be able to call into us anymore
4021 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004022
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004023 const auto& mActivityManager = getActivityManager();
4024 if (mActivityManager) {
4025 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
4026 CameraThreadState::getCallingUid(),
4027 CameraThreadState::getCallingPid());
4028 }
4029
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004030 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004031}
4032
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004033status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4034 // No dumping of clients directly over Binder,
4035 // must go through CameraService::dump
4036 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004037 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004038 return OK;
4039}
4040
Austin Borgered99f642023-06-01 16:51:35 -07004041status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004042 // Can't watch tags directly, must go through CameraService::startWatchingTags
4043 return OK;
4044}
4045
4046status_t CameraService::BasicClient::stopWatchingTags(int) {
4047 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4048 return OK;
4049}
4050
4051status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4052 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4053 return OK;
4054}
4055
Austin Borgered99f642023-06-01 16:51:35 -07004056std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004057 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004058}
4059
Emilian Peev8b64f282021-03-25 16:49:57 -07004060int CameraService::BasicClient::getCameraFacing() const {
4061 return mCameraFacing;
4062}
4063
4064int CameraService::BasicClient::getCameraOrientation() const {
4065 return mOrientation;
4066}
Ruben Brunkcc776712015-02-17 20:18:47 -08004067
4068int CameraService::BasicClient::getClientPid() const {
4069 return mClientPid;
4070}
4071
Ruben Brunk6267b532015-04-30 17:44:07 -07004072uid_t CameraService::BasicClient::getClientUid() const {
4073 return mClientUid;
4074}
4075
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004076bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4077 // Defaults to API2.
4078 return level == API_2;
4079}
4080
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004081status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004082 {
4083 Mutex::Autolock l(mAudioRestrictionLock);
4084 mAudioRestriction = mode;
4085 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004086 sCameraService->updateAudioRestriction();
4087 return OK;
4088}
4089
4090int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004091 return sCameraService->updateAudioRestriction();
4092}
4093
4094int32_t CameraService::BasicClient::getAudioRestriction() const {
4095 Mutex::Autolock l(mAudioRestrictionLock);
4096 return mAudioRestriction;
4097}
4098
4099bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4100 switch (mode) {
4101 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4102 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4103 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4104 return true;
4105 default:
4106 return false;
4107 }
4108}
4109
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004110status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4111 if (mode == AppOpsManager::MODE_ERRORED) {
4112 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004113 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004114 return PERMISSION_DENIED;
4115 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4116 // If the calling Uid is trusted (a native service), the AppOpsManager could
4117 // return MODE_IGNORED. Do not treat such case as error.
4118 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4119 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004120
4121 bool isCameraPrivacyEnabled;
4122 if (flags::camera_privacy_allowlist()) {
4123 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4124 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4125 } else {
4126 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004127 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004128 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004129 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4130 // We prefer to successfully open the camera and perform camera muting
4131 // or blocking in connectHelper as handleAppOpMode can be called before the
4132 // connection has been fully established and at that time camera muting
4133 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004134 if (!isUidActive || !isCameraPrivacyEnabled) {
4135 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004136 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004137 // Return the same error as for device policy manager rejection
4138 return -EACCES;
4139 }
4140 }
4141 return OK;
4142}
4143
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004144status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004145 ATRACE_CALL();
4146
Igor Murashkine6800ce2013-03-04 17:25:57 -08004147 {
4148 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004149 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004150 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004151 if (mAppOpsManager != nullptr) {
4152 // Notify app ops that the camera is not available
4153 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004154
4155 if (flags::watch_foreground_changes()) {
4156 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4157 toString16(mClientPackageName),
4158 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4159 } else {
4160 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004161 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004162 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004163
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004164 // Just check for camera acccess here on open - delay startOp until
4165 // camera frames start streaming in startCameraStreamingOps
4166 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004167 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004168 status_t res = handleAppOpMode(mode);
4169 if (res != OK) {
4170 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004171 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004172 }
4173
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004174 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004175
4176 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004177 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004178
Austin Borgerdddb7552023-03-30 17:53:01 -07004179 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004180
Shuzhen Wang695044d2020-03-06 09:02:23 -08004181 // Notify listeners of camera open/close status
4182 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4183
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004184 return OK;
4185}
4186
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004187status_t CameraService::BasicClient::startCameraStreamingOps() {
4188 ATRACE_CALL();
4189
4190 if (!mOpsActive) {
4191 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4192 return INVALID_OPERATION;
4193 }
4194 if (mOpsStreaming) {
4195 ALOGV("%s: Streaming already active!", __FUNCTION__);
4196 return OK;
4197 }
4198
4199 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004200 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004201
4202 if (mAppOpsManager != nullptr) {
4203 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004204 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4205 toString16(mClientFeatureId),
4206 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004207 status_t res = handleAppOpMode(mode);
4208 if (res != OK) {
4209 return res;
4210 }
4211 }
4212
4213 mOpsStreaming = true;
4214
4215 return OK;
4216}
4217
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004218status_t CameraService::BasicClient::noteAppOp() {
4219 ATRACE_CALL();
4220
4221 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004222 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004223
4224 // noteAppOp is only used for when camera mute is not supported, in order
4225 // to trigger the sensor privacy "Unblock" dialog
4226 if (mAppOpsManager != nullptr) {
4227 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004228 toString16(mClientPackageName), toString16(mClientFeatureId),
4229 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004230 status_t res = handleAppOpMode(mode);
4231 if (res != OK) {
4232 return res;
4233 }
4234 }
4235
4236 return OK;
4237}
4238
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004239status_t CameraService::BasicClient::finishCameraStreamingOps() {
4240 ATRACE_CALL();
4241
4242 if (!mOpsActive) {
4243 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4244 return INVALID_OPERATION;
4245 }
4246 if (!mOpsStreaming) {
4247 ALOGV("%s: Streaming not active!", __FUNCTION__);
4248 return OK;
4249 }
4250
4251 if (mAppOpsManager != nullptr) {
4252 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004253 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004254 mOpsStreaming = false;
4255 }
4256
4257 return OK;
4258}
4259
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004260status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004261 ATRACE_CALL();
4262
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004263 if (mOpsStreaming) {
4264 // Make sure we've notified everyone about camera stopping
4265 finishCameraStreamingOps();
4266 }
4267
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004268 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004269 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004270 mOpsActive = false;
4271
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004272 // This function is called when a client disconnects. This should
4273 // release the camera, but actually only if it was in a proper
4274 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004275 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004276 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004277
Ruben Brunkcc776712015-02-17 20:18:47 -08004278 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004279 sCameraService->updateStatus(StatusInternal::PRESENT,
4280 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004281 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004282 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004283 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4284 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004285 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004286 mOpsCallback.clear();
4287
Austin Borgerdddb7552023-03-30 17:53:01 -07004288 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004289
Shuzhen Wang695044d2020-03-06 09:02:23 -08004290 // Notify listeners of camera open/close status
4291 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4292
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004293 return OK;
4294}
4295
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004296void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004297 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004298 if (mAppOpsManager == nullptr) {
4299 return;
4300 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004301 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004302 if (op != AppOpsManager::OP_CAMERA) {
4303 ALOGW("Unexpected app ops notification received: %d", op);
4304 return;
4305 }
4306
4307 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004308 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004309 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004310 ALOGV("checkOp returns: %d, %s ", res,
4311 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4312 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4313 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4314 "UNKNOWN");
4315
Shuzhen Wang64900852021-02-05 09:03:29 -08004316 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004317 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4318 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004319 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004320 } else if (res == AppOpsManager::MODE_IGNORED) {
4321 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004322
Austin Borgerca1e0062023-06-28 11:32:55 -07004323 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4324 // If not visible, but still active, then we want to block instead of muting the camera.
4325 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4326 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4327
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004328 bool isCameraPrivacyEnabled;
4329 if (flags::camera_privacy_allowlist()) {
4330 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4331 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4332 } else {
4333 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004334 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004335 }
4336
4337 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004338 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4339 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4340 isCameraPrivacyEnabled);
4341 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4342 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4343 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004344 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004345 if (flags::watch_foreground_changes()) {
4346 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4347 setCameraMute(true);
4348 } else {
4349 block();
4350 }
4351 } else {
4352 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4353 setCameraMute(true);
4354 } else if (!isUidActive
4355 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4356 block();
4357 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004358 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004359 }
Evan Severson09ab4002021-02-10 14:15:19 -08004360 } else if (res == AppOpsManager::MODE_ALLOWED) {
4361 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004362 }
4363}
4364
Svet Ganova453d0d2018-01-11 15:37:58 -08004365void CameraService::BasicClient::block() {
4366 ATRACE_CALL();
4367
4368 // Reset the client PID to allow server-initiated disconnect,
4369 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004370 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004371 CaptureResultExtras resultExtras; // a dummy result (invalid)
4372 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4373 disconnect();
4374}
4375
Mathias Agopian65ab4712010-07-14 17:59:35 -07004376// ----------------------------------------------------------------------------
4377
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004378void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004379 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004380 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004381 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4382 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4383 api1ErrorCode = CAMERA_ERROR_DISABLED;
4384 }
4385 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004386 } else {
4387 ALOGE("mRemoteCallback is NULL!!");
4388 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004389}
4390
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004391// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004392binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004393 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004394 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004395}
4396
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004397bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4398 return level == API_1;
4399}
4400
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004401CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4402 mClient(client) {
4403}
4404
4405void CameraService::Client::OpsCallback::opChanged(int32_t op,
4406 const String16& packageName) {
4407 sp<BasicClient> client = mClient.promote();
4408 if (client != NULL) {
4409 client->opChanged(op, packageName);
4410 }
4411}
4412
Mathias Agopian65ab4712010-07-14 17:59:35 -07004413// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004414// UidPolicy
4415// ----------------------------------------------------------------------------
4416
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004417void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004418 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004419 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004420
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004421 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004422 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004423 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004424 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004425 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4426 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004427 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004428 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004429 if (res == OK) {
4430 mRegistered = true;
4431 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004432 } else {
4433 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004434 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004435}
4436
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004437void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004438 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004439 return;
4440 }
4441
4442 registerWithActivityManager();
4443}
4444
4445void CameraService::UidPolicy::registerSelf() {
4446 // Use check service to see if the activity service is available
4447 // If not available then register for notifications, instead of blocking
4448 // till the service is ready
4449 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004450 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004451 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004452 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004453 } else {
4454 registerWithActivityManager();
4455 }
4456}
4457
Svet Ganova453d0d2018-01-11 15:37:58 -08004458void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004459 Mutex::Autolock _l(mUidLock);
4460
Steven Moreland2f348142019-07-02 15:59:07 -07004461 mAm.unregisterUidObserver(this);
4462 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004463 mRegistered = false;
4464 mActiveUids.clear();
4465 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004466}
4467
4468void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4469 onUidIdle(uid, disabled);
4470}
4471
4472void CameraService::UidPolicy::onUidActive(uid_t uid) {
4473 Mutex::Autolock _l(mUidLock);
4474 mActiveUids.insert(uid);
4475}
4476
4477void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4478 bool deleted = false;
4479 {
4480 Mutex::Autolock _l(mUidLock);
4481 if (mActiveUids.erase(uid) > 0) {
4482 deleted = true;
4483 }
4484 }
4485 if (deleted) {
4486 sp<CameraService> service = mService.promote();
4487 if (service != nullptr) {
4488 service->blockClientsForUid(uid);
4489 }
4490 }
4491}
4492
Emilian Peev53722fa2019-02-22 17:47:20 -08004493void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004494 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004495 bool procStateChange = false;
4496 {
4497 Mutex::Autolock _l(mUidLock);
4498 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4499 mMonitoredUids[uid].procState != procState) {
4500 mMonitoredUids[uid].procState = procState;
4501 procStateChange = true;
4502 }
4503 }
4504
4505 if (procStateChange) {
4506 sp<CameraService> service = mService.promote();
4507 if (service != nullptr) {
4508 service->notifyMonitoredUids();
4509 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004510 }
4511}
4512
Austin Borgerdddb7552023-03-30 17:53:01 -07004513/**
4514 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4515 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4516 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4517 * monitoredUids. If it is revised above some other monitoredUid, signal
4518 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4519 * foreground apps in split screen - state changes will capture all other cases.
4520 */
4521void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4522 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004523 {
4524 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004525 auto it = mMonitoredUids.find(uid);
4526
4527 if (it != mMonitoredUids.end()) {
4528 if (it->second.hasCamera) {
4529 for (auto &monitoredUid : mMonitoredUids) {
4530 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004531 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004532 notifyUidSet.emplace(monitoredUid.first);
4533 }
4534 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004535 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004536 notifyUidSet.emplace(uid);
4537 } else {
4538 for (auto &monitoredUid : mMonitoredUids) {
4539 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004540 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004541 notifyUidSet.emplace(uid);
4542 }
4543 }
4544 }
4545 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004546 }
4547 }
4548
Austin Borgerdddb7552023-03-30 17:53:01 -07004549 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004550 sp<CameraService> service = mService.promote();
4551 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004552 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004553 }
4554 }
4555}
4556
Austin Borgerdddb7552023-03-30 17:53:01 -07004557/**
4558 * Register a uid for monitoring, and note whether it owns a camera.
4559 */
4560void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004561 Mutex::Autolock _l(mUidLock);
4562 auto it = mMonitoredUids.find(uid);
4563 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004564 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004565 } else {
Austin Borger65577682022-02-17 00:25:43 +00004566 MonitoredUid monitoredUid;
4567 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004568 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004569 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004570 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004571 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004572 if (res != OK) {
4573 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4574 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004575 }
4576
4577 if (openCamera) {
4578 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004579 }
4580}
4581
Austin Borgerdddb7552023-03-30 17:53:01 -07004582/**
4583 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4584 */
4585void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004586 Mutex::Autolock _l(mUidLock);
4587 auto it = mMonitoredUids.find(uid);
4588 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004589 it->second.refCount--;
4590 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004591 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004592 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004593 if (res != OK) {
4594 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4595 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004596 } else if (closeCamera) {
4597 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004598 }
4599 } else {
4600 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4601 }
4602}
4603
Austin Borgered99f642023-06-01 16:51:35 -07004604bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004605 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004606 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004607}
4608
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004609static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4610static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004611
Austin Borgered99f642023-06-01 16:51:35 -07004612bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004613 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004614 // If activity manager is unreachable, assume everything is active
4615 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004616 return true;
4617 }
4618 auto it = mOverrideUids.find(uid);
4619 if (it != mOverrideUids.end()) {
4620 return it->second;
4621 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004622 bool active = mActiveUids.find(uid) != mActiveUids.end();
4623 if (!active) {
4624 // We want active UIDs to always access camera with their first attempt since
4625 // there is no guarantee the app is robustly written and would retry getting
4626 // the camera on failure. The inverse case is not a problem as we would take
4627 // camera away soon once we get the callback that the uid is no longer active.
4628 ActivityManager am;
4629 // Okay to access with a lock held as UID changes are dispatched without
4630 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004631 int64_t startTimeMillis = 0;
4632 do {
4633 // TODO: Fix this b/109950150!
4634 // Okay this is a hack. There is a race between the UID turning active and
4635 // activity being resumed. The proper fix is very risky, so we temporary add
4636 // some polling which should happen pretty rarely anyway as the race is hard
4637 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004638 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004639 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004640 if (active) {
4641 break;
4642 }
4643 if (startTimeMillis <= 0) {
4644 startTimeMillis = uptimeMillis();
4645 }
4646 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004647 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004648 if (remainingTimeMillis <= 0) {
4649 break;
4650 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004651 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4652
4653 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004654 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004655 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004656 } while (true);
4657
Svet Ganov7b4ab782018-03-25 12:48:10 -07004658 if (active) {
4659 // Now that we found out the UID is actually active, cache that
4660 mActiveUids.insert(uid);
4661 }
4662 }
4663 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004664}
4665
Varun Shahb42f1eb2019-04-16 14:45:13 -07004666int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4667 Mutex::Autolock _l(mUidLock);
4668 return getProcStateLocked(uid);
4669}
4670
4671int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4672 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4673 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004674 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004675 }
4676 return procState;
4677}
4678
Austin Borgered99f642023-06-01 16:51:35 -07004679void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4680 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004681 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004682}
4683
Austin Borgered99f642023-06-01 16:51:35 -07004684void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004685 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004686}
4687
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004688void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4689 Mutex::Autolock _l(mUidLock);
4690 ALOGV("UidPolicy: ActivityManager has died");
4691 mRegistered = false;
4692 mActiveUids.clear();
4693}
4694
Austin Borgered99f642023-06-01 16:51:35 -07004695void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004696 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004697 bool wasActive = false;
4698 bool isActive = false;
4699 {
4700 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004701 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004702 mOverrideUids.erase(uid);
4703 if (insert) {
4704 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4705 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004706 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004707 }
4708 if (wasActive != isActive && !isActive) {
4709 sp<CameraService> service = mService.promote();
4710 if (service != nullptr) {
4711 service->blockClientsForUid(uid);
4712 }
4713 }
4714}
4715
4716// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004717// SensorPrivacyPolicy
4718// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004719
4720void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4721{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004722 Mutex::Autolock _l(mSensorPrivacyLock);
4723 if (mRegistered) {
4724 return;
4725 }
Evan Severson09ab4002021-02-10 14:15:19 -08004726 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004727 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004728 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004729 mSpm.addToggleSensorPrivacyListener(this);
4730 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004731 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004732 if (flags::camera_privacy_allowlist()) {
4733 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4734 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4735 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4736 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004737 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004738 if (res == OK) {
4739 mRegistered = true;
4740 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4741 }
4742}
4743
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004744void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4745 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004746 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004747 return;
4748 }
4749
4750 registerWithSensorPrivacyManager();
4751}
4752
4753void CameraService::SensorPrivacyPolicy::registerSelf() {
4754 // Use checkservice to see if the sensor_privacy service is available
4755 // If service is not available then register for notification
4756 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004757 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004758 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004759 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004760 } else {
4761 registerWithSensorPrivacyManager();
4762 }
4763}
4764
Michael Grooverd1d435a2018-12-18 17:39:42 -08004765void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4766 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004767 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004768 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004769 mSpm.removeToggleSensorPrivacyListener(this);
4770 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004771 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004772 mRegistered = false;
4773 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4774}
4775
4776bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004777 if (!mRegistered) {
4778 registerWithSensorPrivacyManager();
4779 }
4780
Michael Grooverd1d435a2018-12-18 17:39:42 -08004781 Mutex::Autolock _l(mSensorPrivacyLock);
4782 return mSensorPrivacyEnabled;
4783}
4784
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004785int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4786 if (!mRegistered) {
4787 registerWithSensorPrivacyManager();
4788 }
4789
4790 Mutex::Autolock _l(mSensorPrivacyLock);
4791 return mCameraPrivacyState;
4792}
4793
Evan Seversond0b69922022-01-27 10:47:34 -08004794bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004795 if (!hasCameraPrivacyFeature()) {
4796 return false;
4797 }
Evan Seversond0b69922022-01-27 10:47:34 -08004798 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004799}
4800
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004801bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4802 if (!hasCameraPrivacyFeature()) {
4803 return SensorPrivacyManager::DISABLED;
4804 }
4805 return mSpm.isCameraPrivacyEnabled(packageName);
4806}
4807
Evan Seversond0b69922022-01-27 10:47:34 -08004808binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004809 int toggleType, int sensor, bool enabled) {
4810 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4811 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4812 {
4813 Mutex::Autolock _l(mSensorPrivacyLock);
4814 mSensorPrivacyEnabled = enabled;
4815 }
4816 // if sensor privacy is enabled then block all clients from accessing the camera
4817 if (enabled) {
4818 sp<CameraService> service = mService.promote();
4819 if (service != nullptr) {
4820 service->blockAllClients();
4821 }
4822 }
4823 }
4824 return binder::Status::ok();
4825}
4826
4827binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4828 int, int sensor, int state) {
4829 if (!flags::camera_privacy_allowlist()
4830 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4831 return binder::Status::ok();
4832 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004833 {
4834 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004835 mCameraPrivacyState = state;
4836 }
4837 sp<CameraService> service = mService.promote();
4838 if (!service) {
4839 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004840 }
4841 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004842 if (state == SensorPrivacyManager::ENABLED) {
4843 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004844 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004845 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004846 }
4847 return binder::Status::ok();
4848}
4849
4850void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4851 Mutex::Autolock _l(mSensorPrivacyLock);
4852 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4853 mRegistered = false;
4854}
4855
Evan Severson09ab4002021-02-10 14:15:19 -08004856bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004857 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4858 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4859 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4860 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4861 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004862}
4863
Michael Grooverd1d435a2018-12-18 17:39:42 -08004864// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004865// CameraState
4866// ----------------------------------------------------------------------------
4867
Austin Borgered99f642023-06-01 16:51:35 -07004868CameraService::CameraState::CameraState(const std::string& id, int cost,
4869 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004870 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004871 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004872 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004873
4874CameraService::CameraState::~CameraState() {}
4875
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004876CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004877 Mutex::Autolock lock(mStatusLock);
4878 return mStatus;
4879}
4880
Austin Borgered99f642023-06-01 16:51:35 -07004881std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004882 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004883 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004884 return res;
4885}
4886
Ruben Brunkcc776712015-02-17 20:18:47 -08004887CameraParameters CameraService::CameraState::getShimParams() const {
4888 return mShimParams;
4889}
4890
4891void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4892 mShimParams = params;
4893}
4894
4895int CameraService::CameraState::getCost() const {
4896 return mCost;
4897}
4898
Austin Borgered99f642023-06-01 16:51:35 -07004899std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004900 return mConflicting;
4901}
4902
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004903SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4904 return mSystemCameraKind;
4905}
4906
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004907bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4908 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4909 != mPhysicalCameras.end();
4910}
4911
Austin Borgered99f642023-06-01 16:51:35 -07004912bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004913 Mutex::Autolock lock(mStatusLock);
4914 auto result = mUnavailablePhysicalIds.insert(physicalId);
4915 return result.second;
4916}
4917
Austin Borgered99f642023-06-01 16:51:35 -07004918bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004919 Mutex::Autolock lock(mStatusLock);
4920 auto count = mUnavailablePhysicalIds.erase(physicalId);
4921 return count > 0;
4922}
4923
Austin Borgered99f642023-06-01 16:51:35 -07004924void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004925 Mutex::Autolock lock(mStatusLock);
4926 mClientPackage = clientPackage;
4927}
4928
Austin Borgered99f642023-06-01 16:51:35 -07004929std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004930 Mutex::Autolock lock(mStatusLock);
4931 return mClientPackage;
4932}
4933
Ruben Brunkcc776712015-02-17 20:18:47 -08004934// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004935// ClientEventListener
4936// ----------------------------------------------------------------------------
4937
4938void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004939 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004940 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004941 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004942 if (basicClient.get() != nullptr) {
4943 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004944 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004945 static_cast<int>(basicClient->getClientUid()));
4946 }
4947}
4948
4949void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004950 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004951 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004952 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004953 if (basicClient.get() != nullptr) {
4954 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004955 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004956 static_cast<int>(basicClient->getClientUid()));
4957 }
4958}
4959
4960
4961// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004962// CameraClientManager
4963// ----------------------------------------------------------------------------
4964
Ruben Brunk99e69712015-05-26 17:25:07 -07004965CameraService::CameraClientManager::CameraClientManager() {
4966 setListener(std::make_shared<ClientEventListener>());
4967}
4968
Ruben Brunkcc776712015-02-17 20:18:47 -08004969CameraService::CameraClientManager::~CameraClientManager() {}
4970
4971sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004972 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004973 auto descriptor = get(id);
4974 if (descriptor == nullptr) {
4975 return sp<BasicClient>{nullptr};
4976 }
4977 return descriptor->getValue();
4978}
4979
Austin Borgered99f642023-06-01 16:51:35 -07004980std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004981 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004982 std::ostringstream ret;
4983 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004984 bool hasAny = false;
4985 for (auto& i : all) {
4986 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004987 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004988 int32_t cost = i->getCost();
4989 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004990 int32_t score = i->getPriority().getScore();
4991 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004992 auto conflicting = i->getConflicting();
4993 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07004994 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004995 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004996 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004997 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07004998 uid_t clientUid = clientSp->getClientUid();
4999 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005000 }
Austin Borgered99f642023-06-01 16:51:35 -07005001 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5002 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005003
Ruben Brunk6267b532015-04-30 17:44:07 -07005004 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005005 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005006 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005007 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005008 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005009 }
5010
Austin Borgered99f642023-06-01 16:51:35 -07005011 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005012 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005013 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005014 }
Austin Borgered99f642023-06-01 16:51:35 -07005015 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005016 }
Austin Borgered99f642023-06-01 16:51:35 -07005017 if (hasAny) ret << "\n";
5018 ret << "]\n";
5019 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005020}
5021
5022CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005023 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5024 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005025 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005026
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005027 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005028 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005029
Austin Borgered99f642023-06-01 16:51:35 -07005030 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005031 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5032 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005033}
5034
5035CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005036 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005037 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005038 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005039 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005040 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5041 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005042}
5043
5044// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005045// InjectionStatusListener
5046// ----------------------------------------------------------------------------
5047
5048void CameraService::InjectionStatusListener::addListener(
5049 const sp<ICameraInjectionCallback>& callback) {
5050 Mutex::Autolock lock(mListenerLock);
5051 if (mCameraInjectionCallback) return;
5052 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5053 if (res == OK) {
5054 mCameraInjectionCallback = callback;
5055 }
5056}
5057
5058void CameraService::InjectionStatusListener::removeListener() {
5059 Mutex::Autolock lock(mListenerLock);
5060 if (mCameraInjectionCallback == nullptr) {
5061 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5062 return;
5063 }
5064 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5065 mCameraInjectionCallback = nullptr;
5066}
5067
5068void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005069 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005070 if (mCameraInjectionCallback == nullptr) {
5071 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5072 return;
5073 }
Cliff Wud3a05312021-04-26 23:07:31 +08005074
5075 switch (err) {
5076 case -ENODEV:
5077 mCameraInjectionCallback->onInjectionError(
5078 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5079 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005080 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005081 break;
5082 case -EBUSY:
5083 mCameraInjectionCallback->onInjectionError(
5084 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5085 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005086 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005087 break;
5088 case DEAD_OBJECT:
5089 mCameraInjectionCallback->onInjectionError(
5090 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5091 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005092 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005093 break;
5094 case INVALID_OPERATION:
5095 mCameraInjectionCallback->onInjectionError(
5096 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5097 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005098 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005099 break;
5100 case UNKNOWN_TRANSACTION:
5101 mCameraInjectionCallback->onInjectionError(
5102 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5103 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005104 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005105 break;
5106 default:
5107 mCameraInjectionCallback->onInjectionError(
5108 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5109 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005110 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005111 }
Cliff Wud8cae102021-03-11 01:37:42 +08005112}
5113
5114void CameraService::InjectionStatusListener::binderDied(
5115 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005116 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5117 auto parent = mParent.promote();
5118 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005119 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5120 if (clientDescriptor != nullptr) {
5121 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5122 baseClientPtr->stopInjection();
5123 }
Cliff Wu3b268182021-07-06 15:44:43 +08005124 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005125 }
5126}
5127
5128// ----------------------------------------------------------------------------
5129// CameraInjectionSession
5130// ----------------------------------------------------------------------------
5131
5132binder::Status CameraService::CameraInjectionSession::stopInjection() {
5133 Mutex::Autolock lock(mInjectionSessionLock);
5134 auto parent = mParent.promote();
5135 if (parent == nullptr) {
5136 ALOGE("CameraInjectionSession: Parent is gone");
5137 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5138 "Camera service encountered error");
5139 }
Cliff Wud3a05312021-04-26 23:07:31 +08005140
5141 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005142 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5143 if (clientDescriptor != nullptr) {
5144 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5145 res = baseClientPtr->stopInjection();
5146 if (res != OK) {
5147 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5148 " ret != NO_ERROR: %d", res);
5149 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5150 "Camera session encountered error");
5151 }
5152 }
Cliff Wu3b268182021-07-06 15:44:43 +08005153 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005154 return binder::Status::ok();
5155}
5156
5157// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005158
5159static const int kDumpLockRetries = 50;
5160static const int kDumpLockSleep = 60000;
5161
5162static bool tryLock(Mutex& mutex)
5163{
5164 bool locked = false;
5165 for (int i = 0; i < kDumpLockRetries; ++i) {
5166 if (mutex.tryLock() == NO_ERROR) {
5167 locked = true;
5168 break;
5169 }
5170 usleep(kDumpLockSleep);
5171 }
5172 return locked;
5173}
5174
Rucha Katakwardf223072021-06-15 10:21:00 -07005175void CameraService::cacheDump() {
5176 if (mMemFd != -1) {
5177 const Vector<String16> args;
5178 ATRACE_CALL();
5179 // Acquiring service lock here will avoid the deadlock since
5180 // cacheDump will not be called during the second disconnect.
5181 Mutex::Autolock lock(mServiceLock);
5182
5183 Mutex::Autolock l(mCameraStatesLock);
5184 // Start collecting the info for open sessions and store it in temp file.
5185 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005186 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005187 auto clientDescriptor = mActiveClientManager.get(cameraId);
5188 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005189 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005190 // Log the current open session info before device is disconnected.
5191 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5192 }
5193 }
5194 }
5195}
5196
Mathias Agopian65ab4712010-07-14 17:59:35 -07005197status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005198 ATRACE_CALL();
5199
Austin Borgered99f642023-06-01 16:51:35 -07005200 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005201 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07005202 CameraThreadState::getCallingPid(),
5203 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005204 return NO_ERROR;
5205 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005206 bool locked = tryLock(mServiceLock);
5207 // failed to lock - CameraService is probably deadlocked
5208 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005209 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005210 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005211
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005212 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005213 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005214
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005215 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005216 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005217
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005218 if (locked) mServiceLock.unlock();
5219 return NO_ERROR;
5220 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005221 dprintf(fd, "\n== Service global info: ==\n\n");
5222 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005223 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005224 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5225 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005226 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5227 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5228 }
Austin Borgered99f642023-06-01 16:51:35 -07005229 std::string activeClientString = mActiveClientManager.toString();
5230 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5231 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005232 if (mStreamUseCaseOverrides.size() > 0) {
5233 dprintf(fd, "Active stream use case overrides:");
5234 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5235 dprintf(fd, " %" PRId64, useCaseOverride);
5236 }
5237 dprintf(fd, "\n");
5238 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005239
5240 dumpEventLog(fd);
5241
5242 bool stateLocked = tryLock(mCameraStatesLock);
5243 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005244 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005245 }
5246
Emilian Peevbd8c5032018-02-14 23:05:40 +00005247 int argSize = args.size();
5248 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005249 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005250 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005251 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005252 }
5253 break;
5254 }
5255 }
5256
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005257 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005258 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005259
Austin Borgered99f642023-06-01 16:51:35 -07005260 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005261
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005262 CameraParameters p = state.second->getShimParams();
5263 if (!p.isEmpty()) {
5264 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5265 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005266 }
5267
5268 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005269 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005270 // log the current open session info
5271 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005272 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005273 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005274 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005275
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005276 }
5277
5278 if (stateLocked) mCameraStatesLock.unlock();
5279
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005280 if (locked) mServiceLock.unlock();
5281
Emilian Peevf53f66e2017-04-11 14:29:43 +01005282 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005283
5284 dprintf(fd, "\n== Vendor tags: ==\n\n");
5285
5286 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5287 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005288 sp<VendorTagDescriptorCache> cache =
5289 VendorTagDescriptorCache::getGlobalVendorTagCache();
5290 if (cache == NULL) {
5291 dprintf(fd, "No vendor tags.\n");
5292 } else {
5293 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5294 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005295 } else {
5296 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5297 }
5298
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005299 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005300 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005301 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005302
5303 // Process dump arguments, if any
5304 int n = args.size();
5305 String16 verboseOption("-v");
5306 String16 unreachableOption("--unreachable");
5307 for (int i = 0; i < n; i++) {
5308 if (args[i] == verboseOption) {
5309 // change logging level
5310 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005311 std::string levelStr = toStdString(args[i+1]);
5312 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005313 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005314 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005315 } else if (args[i] == unreachableOption) {
5316 // Dump memory analysis
5317 // TODO - should limit be an argument parameter?
5318 UnreachableMemoryInfo info;
5319 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5320 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005321 dprintf(fd, "\n== Unable to dump unreachable memory. "
5322 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005323 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005324 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005325 std::string s = info.ToString(/*log_contents*/ true);
5326 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005327 }
5328 }
5329 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005330
5331 bool serviceLocked = tryLock(mServiceLock);
5332
5333 // Dump info from previous open sessions.
5334 // Reposition the offset to beginning of the file before reading
5335
5336 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5337 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5338 ssize_t size_read;
5339 char buf[4096];
5340 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5341 // Read data from file to a small buffer and write it to fd.
5342 write(fd, buf, size_read);
5343 if (size_read == -1) {
5344 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5345 break;
5346 }
5347 }
5348 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5349 } else {
5350 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5351 }
5352
5353 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005354 return NO_ERROR;
5355}
5356
Rucha Katakwardf223072021-06-15 10:21:00 -07005357void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005358 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005359 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005360 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005361 getFormattedCurrentTime().c_str(),
5362 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005363 dprintf(fd, " Client priority score: %d state: %d\n",
5364 clientDescriptor->getPriority().getScore(),
5365 clientDescriptor->getPriority().getState());
5366 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5367
5368 auto client = clientDescriptor->getValue();
5369 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005370 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005371
5372 client->dumpClient(fd, args);
5373}
5374
Austin Borgered99f642023-06-01 16:51:35 -07005375void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005376 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005377 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005378}
5379
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005380void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005381 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005382
5383 Mutex::Autolock l(mLogLock);
5384 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005385 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005386 }
5387
5388 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005389 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005390 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005391 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005392 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005393 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005394}
5395
Austin Borgered99f642023-06-01 16:51:35 -07005396void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005397 Mutex::Autolock lock(mLogLock);
5398 if (!isClientWatchedLocked(client)) { return; }
5399
5400 std::vector<std::string> dumpVector;
5401 client->dumpWatchedEventsToVector(dumpVector);
5402
5403 if (dumpVector.empty()) { return; }
5404
Austin Borgered99f642023-06-01 16:51:35 -07005405 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005406
Austin Borgered99f642023-06-01 16:51:35 -07005407 std::string currentTime = getFormattedCurrentTime();
5408 dumpString << "Cached @ ";
5409 dumpString << currentTime;
5410 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005411
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005412 size_t i = dumpVector.size();
5413
5414 // Store the string in reverse order (latest last)
5415 while (i > 0) {
5416 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005417 dumpString << cameraId;
5418 dumpString << ":";
5419 dumpString << client->getPackageName();
5420 dumpString << " ";
5421 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005422 }
5423
Austin Borgered99f642023-06-01 16:51:35 -07005424 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005425}
5426
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005427void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005428 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005429 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5430 if (mTorchClientMap[i] == who) {
5431 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005432 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005433 status_t res = mFlashlight->setTorchMode(cameraId, false);
5434 if (res) {
5435 ALOGE("%s: torch client died but couldn't turn off torch: "
5436 "%s (%d)", __FUNCTION__, strerror(-res), res);
5437 return;
5438 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005439 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005440 break;
5441 }
5442 }
5443}
5444
Ruben Brunkcc776712015-02-17 20:18:47 -08005445/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005446
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005447 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005448 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5449 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005450 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005451 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005452 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005453
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005454 // check torch client
5455 handleTorchClientBinderDied(who);
5456
5457 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005458 if(!evictClientIdByRemote(who)) {
5459 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005460 return;
5461 }
5462
Ruben Brunkcc776712015-02-17 20:18:47 -08005463 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5464 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005465}
5466
Austin Borgered99f642023-06-01 16:51:35 -07005467void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005468 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005469}
5470
Austin Borgered99f642023-06-01 16:51:35 -07005471void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005472 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005473 // Do not lock mServiceLock here or can get into a deadlock from
5474 // connect() -> disconnect -> updateStatus
5475
5476 auto state = getCameraState(cameraId);
5477
5478 if (state == nullptr) {
5479 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005480 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005481 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005482 }
5483
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005484 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5485 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5486 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005487 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005488 return;
5489 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005490
5491 // Collect the logical cameras without holding mStatusLock in updateStatus
5492 // as that can lead to a deadlock(b/162192331).
5493 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005494 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005495 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005496 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005497 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005498 (const std::string& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005499
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005500 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005501 // Update torch status if it has a flash unit.
5502 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005503 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005504 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5505 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005506 TorchModeStatus newTorchStatus =
5507 status == StatusInternal::PRESENT ?
5508 TorchModeStatus::AVAILABLE_OFF :
5509 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005510 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005511 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005512 }
5513 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005514 }
5515
5516 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005517 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005518 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005519
Ruben Brunkcc776712015-02-17 20:18:47 -08005520 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005521 bool isVendorListener = listener->isVendorListener();
5522 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
Kwangkyu Park01f84432023-09-15 17:08:17 +09005523 listener->getListenerPid(), listener->getListenerUid())) {
Shuzhen Wangb8259792021-05-27 09:27:06 -07005524 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005525 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005526 continue;
5527 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005528 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005529 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005530 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005531 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005532 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5533 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005534 // Also trigger the callbacks for cameras that were remapped to the current
5535 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005536 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005537 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5538 for (auto& remappedCameraId : remappedCameraIds) {
5539 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005540 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005541 listener->handleBinderStatus(ret,
5542 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5543 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5544 ret.exceptionCode());
5545 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005546 }
5547 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005548}
5549
Austin Borgered99f642023-06-01 16:51:35 -07005550void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5551 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005552 auto state = getCameraState(cameraId);
5553 if (state == nullptr) {
5554 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005555 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005556 return;
5557 }
5558 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005559 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005560 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005561 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005562 }
5563
Shuzhen Wang695044d2020-03-06 09:02:23 -08005564 Mutex::Autolock lock(mStatusListenerLock);
5565
5566 for (const auto& it : mListenerList) {
5567 if (!it->isOpenCloseCallbackAllowed()) {
5568 continue;
5569 }
5570
5571 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005572 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005573 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005574 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005575 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005576 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005577
5578 it->handleBinderStatus(ret,
5579 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5580 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005581 }
5582}
5583
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005584template<class Func>
5585void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005586 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005587 std::initializer_list<StatusInternal> rejectSourceStates,
5588 Func onStatusUpdatedLocked) {
5589 Mutex::Autolock lock(mStatusLock);
5590 StatusInternal oldStatus = mStatus;
5591 mStatus = status;
5592
5593 if (oldStatus == status) {
5594 return;
5595 }
5596
5597 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005598 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005599
5600 if (oldStatus == StatusInternal::NOT_PRESENT &&
5601 (status != StatusInternal::PRESENT &&
5602 status != StatusInternal::ENUMERATING)) {
5603
5604 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5605 __FUNCTION__);
5606 mStatus = oldStatus;
5607 return;
5608 }
5609
5610 /**
5611 * Sometimes we want to conditionally do a transition.
5612 * For example if a client disconnects, we want to go to PRESENT
5613 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5614 */
5615 for (auto& rejectStatus : rejectSourceStates) {
5616 if (oldStatus == rejectStatus) {
5617 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005618 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005619 mStatus = oldStatus;
5620 return;
5621 }
5622 }
5623
5624 onStatusUpdatedLocked(cameraId, status);
5625}
5626
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005627status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005628 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005629 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005630 if (!status) {
5631 return BAD_VALUE;
5632 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005633 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5634 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005635 // invalid camera ID or the camera doesn't have a flash unit
5636 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005637 }
5638
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005639 *status = mTorchStatusMap.valueAt(index);
5640 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005641}
5642
Austin Borgered99f642023-06-01 16:51:35 -07005643status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005644 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005645 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5646 if (index == NAME_NOT_FOUND) {
5647 return BAD_VALUE;
5648 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005649 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005650
5651 return OK;
5652}
5653
Austin Borgered99f642023-06-01 16:51:35 -07005654std::list<std::string> CameraService::getLogicalCameras(
5655 const std::string& physicalCameraId) {
5656 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005657 Mutex::Autolock lock(mCameraStatesLock);
5658 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005659 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5660 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005661 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005662 }
5663 return retList;
5664}
5665
5666void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005667 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005668 SystemCameraKind deviceKind) {
5669 // mStatusListenerLock is expected to be locked
5670 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005671 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005672 // Note: we check only the deviceKind of the physical camera id
5673 // since, logical camera ids and their physical camera ids are
5674 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005675 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5676 listener->getListenerPid(), listener->getListenerUid())) {
5677 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005678 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005679 continue;
5680 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005681 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005682 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005683 listener->handleBinderStatus(ret,
5684 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5685 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5686 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005687 }
5688 }
5689}
5690
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005691
Svet Ganova453d0d2018-01-11 15:37:58 -08005692void CameraService::blockClientsForUid(uid_t uid) {
5693 const auto clients = mActiveClientManager.getAll();
5694 for (auto& current : clients) {
5695 if (current != nullptr) {
5696 const auto basicClient = current->getValue();
5697 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5698 basicClient->block();
5699 }
5700 }
5701 }
5702}
5703
Michael Grooverd1d435a2018-12-18 17:39:42 -08005704void CameraService::blockAllClients() {
5705 const auto clients = mActiveClientManager.getAll();
5706 for (auto& current : clients) {
5707 if (current != nullptr) {
5708 const auto basicClient = current->getValue();
5709 if (basicClient.get() != nullptr) {
5710 basicClient->block();
5711 }
5712 }
5713 }
5714}
5715
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005716void CameraService::blockPrivacyEnabledClients() {
5717 const auto clients = mActiveClientManager.getAll();
5718 for (auto& current : clients) {
5719 if (current != nullptr) {
5720 const auto basicClient = current->getValue();
5721 if (basicClient.get() != nullptr) {
5722 std::string pkgName = basicClient->getPackageName();
5723 bool cameraPrivacyEnabled =
5724 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5725 if (cameraPrivacyEnabled) {
5726 basicClient->block();
5727 }
5728 }
5729 }
5730 }
5731}
5732
Svet Ganova453d0d2018-01-11 15:37:58 -08005733// NOTE: This is a remote API - make sure all args are validated
5734status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005735 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005736 return PERMISSION_DENIED;
5737 }
5738 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5739 return BAD_VALUE;
5740 }
Austin Borgered99f642023-06-01 16:51:35 -07005741 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005742 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005743 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005744 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005745 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005746 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005747 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005748 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005749 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005750 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005751 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005752 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005753 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005754 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005755 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005756 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005757 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005758 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005759 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005760 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005761 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005762 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005763 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005764 handleClearStreamUseCaseOverrides();
5765 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005766 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005767 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005768 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005769 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005770 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005771 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005772 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005773 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005774 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005775 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005776 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005777 }
5778 printHelp(err);
5779 return BAD_VALUE;
5780}
5781
malikakash82ed4352023-07-21 22:44:34 +00005782status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5783 uid_t uid = IPCThreadState::self()->getCallingUid();
5784 if (uid != AID_ROOT) {
5785 dprintf(err, "Must be adb root\n");
5786 return PERMISSION_DENIED;
5787 }
5788 if (args.size() != 4) {
5789 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5790 return BAD_VALUE;
5791 }
Austin Borgered99f642023-06-01 16:51:35 -07005792 std::string packageName = toStdString(args[1]);
5793 std::string cameraIdToReplace = toStdString(args[2]);
5794 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005795 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5796 return OK;
5797}
5798
Svet Ganova453d0d2018-01-11 15:37:58 -08005799status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005800 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005801
Svet Ganova453d0d2018-01-11 15:37:58 -08005802 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005803 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005804 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005805 } else if ((args[2] != toString16("idle"))) {
5806 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005807 return BAD_VALUE;
5808 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005809
5810 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005811 if (args.size() >= 5 && args[3] == toString16("--user")) {
5812 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005813 }
5814
5815 uid_t uid;
5816 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5817 return BAD_VALUE;
5818 }
5819
5820 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005821 return NO_ERROR;
5822}
5823
5824status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005825 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005826
5827 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005828 if (args.size() >= 4 && args[2] == toString16("--user")) {
5829 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005830 }
5831
5832 uid_t uid;
5833 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005834 return BAD_VALUE;
5835 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005836
5837 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005838 return NO_ERROR;
5839}
5840
5841status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005842 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005843
5844 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005845 if (args.size() >= 4 && args[2] == toString16("--user")) {
5846 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005847 }
5848
5849 uid_t uid;
5850 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005851 return BAD_VALUE;
5852 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005853
5854 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005855 return dprintf(out, "active\n");
5856 } else {
5857 return dprintf(out, "idle\n");
5858 }
5859}
5860
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005861status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005862 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005863 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5864 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5865 Mutex::Autolock lock(mServiceLock);
5866
5867 mOverrideRotateAndCropMode = rotateValue;
5868
5869 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5870
5871 const auto clients = mActiveClientManager.getAll();
5872 for (auto& current : clients) {
5873 if (current != nullptr) {
5874 const auto basicClient = current->getValue();
5875 if (basicClient.get() != nullptr) {
5876 basicClient->setRotateAndCropOverride(rotateValue);
5877 }
5878 }
5879 }
5880
5881 return OK;
5882}
5883
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005884status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5885 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005886 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005887 if ((*end != '\0') ||
5888 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5889 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5890 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5891 return BAD_VALUE;
5892 }
5893
5894 Mutex::Autolock lock(mServiceLock);
5895 mOverrideAutoframingMode = autoframingValue;
5896
5897 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5898
5899 const auto clients = mActiveClientManager.getAll();
5900 for (auto& current : clients) {
5901 if (current != nullptr) {
5902 const auto basicClient = current->getValue();
5903 if (basicClient.get() != nullptr) {
5904 basicClient->setAutoframingOverride(autoframingValue);
5905 }
5906 }
5907 }
5908
5909 return OK;
5910}
5911
Ravneetaeb20dc2022-03-30 05:33:03 +00005912status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005913 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005914
5915 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5916
5917 Mutex::Autolock lock(mServiceLock);
5918
5919 mCameraServiceWatchdogEnabled = enableWatchdog;
5920
5921 const auto clients = mActiveClientManager.getAll();
5922 for (auto& current : clients) {
5923 if (current != nullptr) {
5924 const auto basicClient = current->getValue();
5925 if (basicClient.get() != nullptr) {
5926 basicClient->setCameraServiceWatchdog(enableWatchdog);
5927 }
5928 }
5929 }
5930
5931 return OK;
5932}
5933
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005934status_t CameraService::handleGetRotateAndCrop(int out) {
5935 Mutex::Autolock lock(mServiceLock);
5936
5937 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5938}
5939
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005940status_t CameraService::handleGetAutoframing(int out) {
5941 Mutex::Autolock lock(mServiceLock);
5942
5943 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5944}
5945
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005946status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5947 char *endPtr;
5948 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005949 std::string maskString = toStdString(args[1]);
5950 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005951
5952 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005953 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005954 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5955
5956 Mutex::Autolock lock(mServiceLock);
5957
5958 mImageDumpMask = maskValue;
5959
5960 return OK;
5961}
5962
5963status_t CameraService::handleGetImageDumpMask(int out) {
5964 Mutex::Autolock lock(mServiceLock);
5965
5966 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5967}
5968
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005969status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005970 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005971 if (errno != 0) return BAD_VALUE;
5972
5973 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5974 Mutex::Autolock lock(mServiceLock);
5975
5976 mOverrideCameraMuteMode = (muteValue == 1);
5977
5978 const auto clients = mActiveClientManager.getAll();
5979 for (auto& current : clients) {
5980 if (current != nullptr) {
5981 const auto basicClient = current->getValue();
5982 if (basicClient.get() != nullptr) {
5983 if (basicClient->supportsCameraMute()) {
5984 basicClient->setCameraMute(mOverrideCameraMuteMode);
5985 }
5986 }
5987 }
5988 }
5989
5990 return OK;
5991}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005992
Shuzhen Wang16610a62022-12-15 22:38:07 -08005993status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5994 std::vector<int64_t> useCasesOverride;
5995 for (size_t i = 1; i < args.size(); i++) {
5996 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005997 std::string arg = toStdString(args[i]);
5998 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005999 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006000 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006001 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006002 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006003 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006004 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006005 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006006 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006007 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006008 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006009 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006010 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006011 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6012 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006013 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006014 return BAD_VALUE;
6015 }
6016 useCasesOverride.push_back(useCase);
6017 }
6018
6019 Mutex::Autolock lock(mServiceLock);
6020 mStreamUseCaseOverrides = std::move(useCasesOverride);
6021
6022 return OK;
6023}
6024
6025void CameraService::handleClearStreamUseCaseOverrides() {
6026 Mutex::Autolock lock(mServiceLock);
6027 mStreamUseCaseOverrides.clear();
6028}
6029
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006030status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6031 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006032 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006033 if ((*end != '\0') ||
6034 (zoomOverrideValue != -1 &&
6035 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6036 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6037 return BAD_VALUE;
6038 }
6039
6040 Mutex::Autolock lock(mServiceLock);
6041 mZoomOverrideValue = zoomOverrideValue;
6042
6043 const auto clients = mActiveClientManager.getAll();
6044 for (auto& current : clients) {
6045 if (current != nullptr) {
6046 const auto basicClient = current->getValue();
6047 if (basicClient.get() != nullptr) {
6048 if (basicClient->supportsZoomOverride()) {
6049 basicClient->setZoomOverride(mZoomOverrideValue);
6050 }
6051 }
6052 }
6053 }
6054
6055 return OK;
6056}
6057
Avichal Rakesh84147132021-11-11 17:47:11 -08006058status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006059 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006060 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006061 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006062 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006063 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006064 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006065 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006066 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006067 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006068 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006069 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006070 dprintf(outFd, "Camera service watch commands:\n"
6071 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6072 " starts watching the provided tags for clients with provided package\n"
6073 " recognizes tag shorthands like '3a'\n"
6074 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006075 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006076 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006077 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006078 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006079 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006080 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006081 return BAD_VALUE;
6082}
6083
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006084status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6085 Mutex::Autolock lock(mLogLock);
6086 size_t tagsIdx; // index of '-m'
6087 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006088 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006089 if (tagsIdx < args.size() - 1) {
6090 tags = args[tagsIdx + 1];
6091 } else {
6092 dprintf(outFd, "No tags provided.\n");
6093 return BAD_VALUE;
6094 }
6095
6096 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006097 // watch all clients if no clients are provided
6098 String16 clients = toString16(kWatchAllClientsFlag);
6099 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006100 clientsIdx++);
6101 if (clientsIdx < args.size() - 1) {
6102 clients = args[clientsIdx + 1];
6103 }
Austin Borgered99f642023-06-01 16:51:35 -07006104 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006105
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006106 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006107 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006108
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006109 bool serviceLock = tryLock(mServiceLock);
6110 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006111 auto cameraClients = mActiveClientManager.getAll();
6112 for (const auto &clientDescriptor: cameraClients) {
6113 if (clientDescriptor == nullptr) { continue; }
6114 sp<BasicClient> client = clientDescriptor->getValue();
6115 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006116
6117 if (isClientWatchedLocked(client.get())) {
6118 client->startWatchingTags(mMonitorTags, outFd);
6119 numWatchedClients++;
6120 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006121 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006122 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6123
6124 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006125 return OK;
6126}
6127
6128status_t CameraService::stopWatchingTags(int outFd) {
6129 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006130 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006131 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006132
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006133 mWatchedClientPackages.clear();
6134 mWatchedClientsDumpCache.clear();
6135
6136 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006137 auto cameraClients = mActiveClientManager.getAll();
6138 for (const auto &clientDescriptor : cameraClients) {
6139 if (clientDescriptor == nullptr) { continue; }
6140 sp<BasicClient> client = clientDescriptor->getValue();
6141 if (client.get() == nullptr) { continue; }
6142 client->stopWatchingTags(outFd);
6143 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006144 dprintf(outFd, "Stopped watching all clients.\n");
6145 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006146 return OK;
6147}
6148
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006149status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6150 Mutex::Autolock lock(mLogLock);
6151 size_t clearedSize = mWatchedClientsDumpCache.size();
6152 mWatchedClientsDumpCache.clear();
6153 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6154 return OK;
6155}
6156
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006157status_t CameraService::printWatchedTags(int outFd) {
6158 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006159 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006160
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006161 bool printedSomething = false; // tracks if any monitoring information was printed
6162 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006163
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006164 bool serviceLock = tryLock(mServiceLock);
6165 // get all watched clients that are currently connected
6166 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6167 if (clientDescriptor == nullptr) { continue; }
6168
6169 sp<BasicClient> client = clientDescriptor->getValue();
6170 if (client.get() == nullptr) { continue; }
6171 if (!isClientWatchedLocked(client.get())) { continue; }
6172
6173 std::vector<std::string> dumpVector;
6174 client->dumpWatchedEventsToVector(dumpVector);
6175
6176 size_t printIdx = dumpVector.size();
6177 if (printIdx == 0) {
6178 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006179 }
6180
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006181 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006182 const std::string &cameraId = clientDescriptor->getKey();
6183 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006184 while(printIdx > 0) {
6185 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006186 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006187 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006188 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006189 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006190 printedSomething = true;
6191
6192 connectedMonitoredClients.emplace(client->getPackageName());
6193 }
6194 if (serviceLock) { mServiceLock.unlock(); }
6195
6196 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6197 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006198 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006199 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6200 continue;
6201 }
6202
Austin Borgered99f642023-06-01 16:51:35 -07006203 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006204 dprintf(outFd, "%s\n", kv.second.c_str());
6205 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006206 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006207
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006208 if (!printedSomething) {
6209 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006210 }
6211
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006212 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006213}
6214
Avichal Rakesh84147132021-11-11 17:47:11 -08006215// Print all events in vector `events' that came after lastPrintedEvent
6216void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006217 const std::string &cameraId,
6218 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006219 const std::vector<std::string> &events,
6220 const std::string &lastPrintedEvent) {
6221 if (events.empty()) { return; }
6222
6223 // index of lastPrintedEvent in events.
6224 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6225 size_t lastPrintedIdx;
6226 for (lastPrintedIdx = 0;
6227 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6228 lastPrintedIdx++);
6229
6230 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6231
Avichal Rakesh84147132021-11-11 17:47:11 -08006232 // print events in chronological order (latest event last)
6233 size_t idxToPrint = lastPrintedIdx;
6234 do {
6235 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006236 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6237 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006238 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006239}
6240
6241// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6242// command should be interrupted if the user presses the return key, or if user loses any way to
6243// signal interrupt.
6244// If timeoutMs == 0, this function will always return false
6245bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6246 struct timeval startTime;
6247 int startTimeError = gettimeofday(&startTime, nullptr);
6248 if (startTimeError) {
6249 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6250 return true;
6251 }
6252
6253 const nfds_t numFds = 1;
6254 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6255
6256 struct timeval currTime;
6257 char buffer[2];
6258 while(true) {
6259 int currTimeError = gettimeofday(&currTime, nullptr);
6260 if (currTimeError) {
6261 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6262 return true;
6263 }
6264
6265 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6266 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6267 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6268
6269 if (remainingTimeMs <= 0) {
6270 // No user interrupt within timeoutMs, don't interrupt watch command
6271 return false;
6272 }
6273
6274 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6275 if (numFdsUpdated < 0) {
6276 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6277 return true;
6278 }
6279
6280 if (numFdsUpdated == 0) {
6281 // No user input within timeoutMs, don't interrupt watch command
6282 return false;
6283 }
6284
6285 if (!(pollFd.revents & POLLIN)) {
6286 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6287 return true;
6288 }
6289
6290 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6291 if (sizeRead < 0) {
6292 dprintf(outFd, "Error reading user input. Exiting.\n");
6293 return true;
6294 }
6295
6296 if (sizeRead == 0) {
6297 // Reached end of input fd (can happen if input is piped)
6298 // User has no way to signal an interrupt, so interrupt here
6299 return true;
6300 }
6301
6302 if (buffer[0] == '\n') {
6303 // User pressed return, interrupt watch command.
6304 return true;
6305 }
6306 }
6307}
6308
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006309status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6310 int inFd, int outFd) {
6311 // Figure out refresh interval, if present in args
6312 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006313 if (args.size() > 2) {
6314 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006315 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006316 intervalIdx++);
6317
6318 size_t intervalValIdx = intervalIdx + 1;
6319 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006320 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006321 if (errno) { return BAD_VALUE; }
6322 }
6323 }
6324
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006325 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6326 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006327
Avichal Rakesh84147132021-11-11 17:47:11 -08006328 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006329 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006330
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006331 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006332 bool serviceLock = tryLock(mServiceLock);
6333 auto cameraClients = mActiveClientManager.getAll();
6334 if (serviceLock) { mServiceLock.unlock(); }
6335
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006336 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006337 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006338 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006339
6340 sp<BasicClient> client = clientDescriptor->getValue();
6341 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006342 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006343
Austin Borgered99f642023-06-01 16:51:35 -07006344 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006345 // This also initializes the map entries with an empty string
6346 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6347
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006348 std::vector<std::string> latestEvents;
6349 client->dumpWatchedEventsToVector(latestEvents);
6350
6351 if (!latestEvents.empty()) {
6352 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006353 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006354 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006355 latestEvents,
6356 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006357 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006358 }
6359 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006360 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006361 break;
6362 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006363 }
6364 return OK;
6365}
6366
Austin Borgered99f642023-06-01 16:51:35 -07006367void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006368 mWatchedClientPackages.clear();
6369
Austin Borgered99f642023-06-01 16:51:35 -07006370 std::istringstream iss(clients);
6371 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006372
Austin Borgered99f642023-06-01 16:51:35 -07006373 while (std::getline(iss, nextClient, ',')) {
6374 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006375 // Don't need to track any other package if 'all' is present
6376 mWatchedClientPackages.clear();
6377 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6378 break;
6379 }
6380
6381 // track package names
6382 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006383 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006384}
6385
Svet Ganova453d0d2018-01-11 15:37:58 -08006386status_t CameraService::printHelp(int out) {
6387 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006388 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6389 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6390 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006391 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6392 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6393 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006394 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6395 " Valid values 0=false, 1=true, 2=auto\n"
6396 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006397 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6398 " Valid values 0=OFF, 1=ON for JPEG\n"
6399 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006400 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006401 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6402 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6403 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6404 " on. In case the number of usecases is smaller than the number of streams, the\n"
6405 " last use case is assigned to all the remaining streams. In case of multiple\n"
6406 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6407 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6408 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6409 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006410 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6411 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006412 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6413 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006414 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006415 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006416 " help print this message\n");
6417}
6418
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006419bool CameraService::isClientWatched(const BasicClient *client) {
6420 Mutex::Autolock lock(mLogLock);
6421 return isClientWatchedLocked(client);
6422}
6423
6424bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6425 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6426 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6427}
6428
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006429int32_t CameraService::updateAudioRestriction() {
6430 Mutex::Autolock lock(mServiceLock);
6431 return updateAudioRestrictionLocked();
6432}
6433
6434int32_t CameraService::updateAudioRestrictionLocked() {
6435 int32_t mode = 0;
6436 // iterate through all active client
6437 for (const auto& i : mActiveClientManager.getAll()) {
6438 const auto clientSp = i->getValue();
6439 mode |= clientSp->getAudioRestriction();
6440 }
6441
6442 bool modeChanged = (mAudioRestriction != mode);
6443 mAudioRestriction = mode;
6444 if (modeChanged) {
6445 mAppOps.setCameraAudioRestriction(mode);
6446 }
6447 return mode;
6448}
6449
Austin Borgered99f642023-06-01 16:51:35 -07006450status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006451 sp<BasicClient> clientSp) {
6452 std::unique_ptr<AutoConditionLock> lock =
6453 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6454 status_t res = NO_ERROR;
6455 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006456 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006457 mInjectionStatusListener->notifyInjectionError(
6458 externalCamId, UNKNOWN_TRANSACTION);
6459 clientSp->notifyError(
6460 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6461 CaptureResultExtras());
6462
6463 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6464 // other clients from connecting in mServiceLockWrapper if held
6465 mServiceLock.unlock();
6466
6467 // Clear caller identity temporarily so client disconnect PID checks work correctly
6468 int64_t token = CameraThreadState::clearCallingIdentity();
6469 clientSp->disconnect();
6470 CameraThreadState::restoreCallingIdentity(token);
6471
6472 // Reacquire mServiceLock
6473 mServiceLock.lock();
6474 }
6475
6476 return res;
6477}
6478
Cliff Wud3a05312021-04-26 23:07:31 +08006479void CameraService::clearInjectionParameters() {
6480 {
6481 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006482 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006483 mInjectionInternalCamId = "";
6484 }
6485 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006486 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006487}
6488
Mathias Agopian65ab4712010-07-14 17:59:35 -07006489}; // namespace android