blob: ebe771e6acfab53cbd7e2b0634727d97cda570e4 [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 Borger17e3ebe2024-02-14 15:02:11 -0800131// 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 Borger17e3ebe2024-02-14 15:02:11 -0800156 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
157 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
Austin Borger74fca042022-05-23 12:41:21 -0700158 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
159 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Austin Borger17e3ebe2024-02-14 15:02:11 -0800160 mAttributionAndPermissionUtils(attributionAndPermissionUtils == nullptr ?
161 std::make_shared<AttributionAndPermissionUtils>(this)\
162 : attributionAndPermissionUtils),
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());
Ruben Brunkcc776712015-02-17 20:18:47 -0800169 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700170 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
171 if (mMemFd == -1) {
172 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
173 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700174}
175
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800176// The word 'System' here does not refer to clients only on the system
177// partition. They just need to have a android system uid.
178static bool doesClientHaveSystemUid() {
179 return (CameraThreadState::getCallingUid() < AID_APP_START);
180}
181
Charles Chena7b613c2023-01-24 21:57:33 +0000182// Enable processes with isolated AID to request the binder
183void CameraService::instantiate() {
184 CameraService::publish(true);
185}
186
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800187void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700188 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800189 return;
190 }
191
192 ALOGV("appops service registered. setting camera audio restriction");
193 mAppOps.setCameraAudioRestriction(mAudioRestriction);
194}
195
Iliyan Malchev8951a972011-04-14 16:55:59 -0700196void CameraService::onFirstRef()
197{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700198
Ruben Brunkcc776712015-02-17 20:18:47 -0800199 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800200
Iliyan Malchev8951a972011-04-14 16:55:59 -0700201 BnCameraService::onFirstRef();
202
Ruben Brunk99e69712015-05-26 17:25:07 -0700203 // Update battery life tracking if service is restarting
204 BatteryNotifier& notifier(BatteryNotifier::getInstance());
205 notifier.noteResetCamera();
206 notifier.noteResetFlashlight();
207
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800208 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800209
Emilian Peevf53f66e2017-04-11 14:29:43 +0100210 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800211 if (res == OK) {
212 mInitialized = true;
213 }
214
Svet Ganova453d0d2018-01-11 15:37:58 -0800215 mUidPolicy = new UidPolicy(this);
216 mUidPolicy->registerSelf();
Austin Borger17e3ebe2024-02-14 15:02:11 -0800217 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800218 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800219 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800220
221 // appops function setCamerAudioRestriction uses getService which
222 // is blocking till the appops service is ready. To enable early
223 // boot availability for cameraservice, use checkService which is
224 // non blocking and register for notifications
225 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700226 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800227 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700228 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800229 } else {
230 mAppOps.setCameraAudioRestriction(mAudioRestriction);
231 }
232
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700233 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
234 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000235 // Deprecated, so it will fail to register on newer devices
236 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700237 __FUNCTION__);
238 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700239
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700240 if (!AidlCameraService::registerService(this)) {
241 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
242 }
243
Shuzhen Wang24b44152019-09-20 10:38:11 -0700244 // This needs to be last call in this function, so that it's as close to
245 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700246 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700247 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800248}
249
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800250status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800251 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100252
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800253 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000254 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800255 {
256 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800257
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800258 if (nullptr == mCameraProviderManager.get()) {
259 mCameraProviderManager = new CameraProviderManager();
260 res = mCameraProviderManager->initialize(this);
261 if (res != OK) {
262 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
263 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700264 logServiceError("Unable to initialize camera provider manager",
265 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100267 }
268 }
269
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800270
271 // Setup vendor tags before we call get_camera_info the first time
272 // because HAL might need to setup static vendor keys in get_camera_info
273 // TODO: maybe put this into CameraProviderManager::initialize()?
274 mCameraProviderManager->setUpVendorTags();
275
276 if (nullptr == mFlashlight.get()) {
277 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700278 }
279
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800280 res = mFlashlight->findFlashUnits();
281 if (res != OK) {
282 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
283 }
284
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000285 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800286 }
287
288
289 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700290 if (getCameraState(cameraId) == nullptr) {
291 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800292 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000293 if (unavailPhysicalIds.count(cameraId) > 0) {
294 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700295 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000296 }
297 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800298 }
299
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700300 // Derive primary rear/front cameras, and filter their charactierstics.
301 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700302 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700303 // Assume internal cameras are advertised from the same
304 // provider. If multiple providers are registered at different time,
305 // and each provider contains multiple internal color cameras, the current
306 // logic may filter the characteristics of more than one front/rear color
307 // cameras.
308 Mutex::Autolock l(mServiceLock);
309 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700310 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700311
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800312 return OK;
313}
314
Austin Borgered99f642023-06-01 16:51:35 -0700315void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700316 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800317 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800318 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700319 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
320 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000321 ALOGV("%s: Skipping torch callback for system-only camera device %s",
322 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700323 continue;
324 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700325 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700326 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700327 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
328 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000329 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
330 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700331 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000332 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
333 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700334 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000335 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
336 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
337 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800338 }
339}
340
Mathias Agopian65ab4712010-07-14 17:59:35 -0700341CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800342 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800343 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800344 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800345 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700346}
347
Emilian Peevaee727d2017-05-04 16:35:48 +0100348void CameraService::onNewProviderRegistered() {
349 enumerateProviders();
350}
351
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700352void CameraService::filterAPI1SystemCameraLocked(
353 const std::vector<std::string> &normalDeviceIds) {
354 mNormalDeviceIdsWithoutSystemCamera.clear();
355 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700356 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700357 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700358 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
359 continue;
360 }
361 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700362 // All system camera ids will necessarily come after public camera
363 // device ids as per the HAL interface contract.
364 break;
365 }
366 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
367 }
368 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
369 mNormalDeviceIdsWithoutSystemCamera.size());
370}
371
Austin Borgered99f642023-06-01 16:51:35 -0700372status_t CameraService::getSystemCameraKind(const std::string& cameraId,
373 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700374 auto state = getCameraState(cameraId);
375 if (state != nullptr) {
376 *kind = state->getSystemCameraKind();
377 return OK;
378 }
379 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700380 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700381}
382
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800383void CameraService::updateCameraNumAndIds() {
384 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700385 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
386 // Excludes hidden secure cameras
387 mNumberOfCameras =
388 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
389 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800390 mNormalDeviceIds =
391 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700392 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800393}
394
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700395void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700396 // To claim to be S Performance primary cameras, the cameras must be
397 // backward compatible. So performance class primary camera Ids must be API1
398 // compatible.
399 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
400 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
401 int facing = -1;
402 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800403 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700404 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800405 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700406 if (facing == -1) {
407 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
408 return;
409 }
410
411 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
412 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700413 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
414 if (res == OK) {
415 mPerfClassPrimaryCameraIds.insert(cameraId);
416 } else {
417 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
418 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
419 break;
420 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700421
422 if (facing == hardware::CAMERA_FACING_BACK) {
423 firstRearCameraSeen = true;
424 }
425 if (facing == hardware::CAMERA_FACING_FRONT) {
426 firstFrontCameraSeen = true;
427 }
428 }
429
430 if (firstRearCameraSeen && firstFrontCameraSeen) {
431 break;
432 }
433 }
434}
435
Austin Borgered99f642023-06-01 16:51:35 -0700436void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700437 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100438 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
439 if (res != OK) {
440 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
441 return;
442 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000443 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700444 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
445 if (res != OK) {
446 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
447 return;
448 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000449 std::vector<std::string> physicalCameraIds;
450 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700451 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100452 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700453 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100454 }
455
456 {
457 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700458 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000459 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100460 }
461
Austin Borgered99f642023-06-01 16:51:35 -0700462 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100463 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700464 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800465
Austin Borgered99f642023-06-01 16:51:35 -0700466 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100467 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800468
469 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700470 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100471}
472
Austin Borgered99f642023-06-01 16:51:35 -0700473void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800474 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700475 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100476 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700477 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100478 }
479
480 {
481 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700482 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100483 }
484}
485
Austin Borgered99f642023-06-01 16:51:35 -0700486void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800487 CameraDeviceStatus newHalStatus) {
488 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700489 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700490
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800491 StatusInternal newStatus = mapToInternal(newHalStatus);
492
Austin Borgered99f642023-06-01 16:51:35 -0700493 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800494
495 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700496 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700498 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100499
500 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700501 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100502
Austin Borgered99f642023-06-01 16:51:35 -0700503 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700504 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700505 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700506 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700507 return;
508 }
509
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800510 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800511
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800512 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800513 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700514 return;
515 }
516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000518 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
519 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800520
521 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
522 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700523 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800524
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800525 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700526 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800527 // Don't do this in updateStatus to avoid deadlock over mServiceLock
528 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700529
Ruben Brunkcc776712015-02-17 20:18:47 -0800530 // Remove cached shim parameters
531 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700532
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800533 // Remove online as well as offline client from the list of active clients,
534 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700535 clientToDisconnectOnline = removeClientLocked(cameraId);
536 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700537 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800538
Austin Borgered99f642023-06-01 16:51:35 -0700539 disconnectClient(cameraId, clientToDisconnectOnline);
540 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700541
Austin Borgered99f642023-06-01 16:51:35 -0700542 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800543 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800544 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000545 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
546 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700547 }
Austin Borgered99f642023-06-01 16:51:35 -0700548 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700549 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800550}
Igor Murashkincba2c162013-03-20 15:56:31 -0700551
Austin Borgered99f642023-06-01 16:51:35 -0700552void CameraService::onDeviceStatusChanged(const std::string& id,
553 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800554 CameraDeviceStatus newHalStatus) {
555 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700556 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800557
558 StatusInternal newStatus = mapToInternal(newHalStatus);
559
560 std::shared_ptr<CameraState> state = getCameraState(id);
561
562 if (state == nullptr) {
563 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700564 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800565 return;
566 }
567
568 StatusInternal logicalCameraStatus = state->getStatus();
569 if (logicalCameraStatus != StatusInternal::PRESENT &&
570 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
571 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700572 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800573 return;
574 }
575
576 bool updated = false;
577 if (newStatus == StatusInternal::PRESENT) {
578 updated = state->removeUnavailablePhysicalId(physicalId);
579 } else {
580 updated = state->addUnavailablePhysicalId(physicalId);
581 }
582
583 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700584 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800585 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000586 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800587 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000588 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800589 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700590 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
591 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
592 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700593 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700594 return;
595 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800596 Mutex::Autolock lock(mStatusListenerLock);
597 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700598 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
599 listener->getListenerPid(), listener->getListenerUid())) {
600 ALOGV("Skipping discovery callback for system-only camera device %s",
601 id.c_str());
602 continue;
603 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700604 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700605 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700606 listener->handleBinderStatus(ret,
607 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
608 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
609 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800610 }
611 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700612}
613
Austin Borgered99f642023-06-01 16:51:35 -0700614void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800615 if (clientToDisconnect.get() != nullptr) {
616 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700617 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800618 // Notify the client of disconnection
619 clientToDisconnect->notifyError(
620 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
621 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800622 clientToDisconnect->disconnect();
623 }
624}
625
Austin Borgered99f642023-06-01 16:51:35 -0700626void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800627 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700628 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
629 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
630 if (res != OK) {
631 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700632 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700633 return;
634 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800635 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700636 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800637}
638
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700639
Austin Borgered99f642023-06-01 16:51:35 -0700640void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700641 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
642 Mutex::Autolock al(mTorchStatusMutex);
643 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
644}
645
Austin Borgered99f642023-06-01 16:51:35 -0700646void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800647 int32_t newStrengthLevel) {
648 Mutex::Autolock lock(mStatusListenerLock);
649 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700650 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700651 i->handleBinderStatus(ret,
652 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
653 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800654 }
655}
656
Austin Borgered99f642023-06-01 16:51:35 -0700657void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700658 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800659 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700660 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800661
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800662 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800663 status_t res = getTorchStatusLocked(cameraId, &status);
664 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700665 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700666 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800667 return;
668 }
669 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800670 return;
671 }
672
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800673 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800674 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800675 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
676 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800677 return;
678 }
679
Ruben Brunkcc776712015-02-17 20:18:47 -0800680 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700681 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700682 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700683 auto iter = mTorchUidMap.find(cameraId);
684 if (iter != mTorchUidMap.end()) {
685 int oldUid = iter->second.second;
686 int newUid = iter->second.first;
687 BatteryNotifier& notifier(BatteryNotifier::getInstance());
688 if (oldUid != newUid) {
689 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800690 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700691 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700692 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800693 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700694 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700695 }
696 iter->second.second = newUid;
697 } else {
698 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800699 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700700 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700701 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700702 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700703 }
704 }
705 }
706 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700707 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800708}
709
Austin Borger17e3ebe2024-02-14 15:02:11 -0800710bool CameraService::isAutomotiveDevice() const {
711 return mAttributionAndPermissionUtils->isAutomotiveDevice();
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700712}
713
Austin Borger17e3ebe2024-02-14 15:02:11 -0800714bool CameraService::isAutomotivePrivilegedClient(int32_t uid) const {
715 return mAttributionAndPermissionUtils->isAutomotivePrivilegedClient(uid);
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700716}
717
Austin Borger17e3ebe2024-02-14 15:02:11 -0800718bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700719 // Returns false if this is not an automotive device type.
720 if (!isAutomotiveDevice())
721 return false;
722
723 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700724 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700725 return false;
726
727 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
728 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
729 // This isn't a known camera ID, so it's not a system camera.
730 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
731 return false;
732 }
733
734 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
735 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
736 return false;
737 }
738
739 CameraMetadata cameraInfo;
740 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700741 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700742 if (res != OK){
743 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
744 cam_id.c_str());
745 return false;
746 }
747
748 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
749 if (auto_location.count != 1)
750 return false;
751
752 uint8_t location = auto_location.data.u8[0];
753 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
754 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
755 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
756 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
757 return false;
758 }
759
760 return true;
761}
762
Austin Borger17e3ebe2024-02-14 15:02:11 -0800763static AttributionSourceState attributionSourceFromPidAndUid(int callingPid, int callingUid) {
764 AttributionSourceState attributionSource{};
765 attributionSource.pid = callingPid;
766 attributionSource.uid = callingUid;
767 return attributionSource;
768}
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700769
Austin Borger17e3ebe2024-02-14 15:02:11 -0800770bool CameraService::hasPermissionsForCamera(int callingPid, int callingUid) const {
771 return hasPermissionsForCamera(std::string(), callingPid, callingUid);
772}
773
774bool CameraService::hasPermissionsForCamera(const std::string& cameraId, int callingPid,
775 int callingUid) const {
776 auto attributionSource = attributionSourceFromPidAndUid(callingPid, callingUid);
777 return mAttributionAndPermissionUtils->hasPermissionsForCamera(cameraId, attributionSource);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700778}
779
Austin Borger1c1bee02023-06-01 16:51:35 -0700780bool CameraService::hasPermissionsForSystemCamera(const std::string& cameraId, int callingPid,
Austin Borger17e3ebe2024-02-14 15:02:11 -0800781 int callingUid, bool checkCameraPermissions) const {
782 auto attributionSource = attributionSourceFromPidAndUid(callingPid, callingUid);
783 return mAttributionAndPermissionUtils->hasPermissionsForSystemCamera(
784 cameraId, attributionSource, checkCameraPermissions);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700785}
786
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700787bool CameraService::hasPermissionsForCameraHeadlessSystemUser(const std::string& cameraId,
Austin Borger17e3ebe2024-02-14 15:02:11 -0800788 int callingPid, int callingUid) const {
789 auto attributionSource = attributionSourceFromPidAndUid(callingPid, callingUid);
790 return mAttributionAndPermissionUtils->hasPermissionsForCameraHeadlessSystemUser(
791 cameraId, attributionSource);
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700792}
793
Austin Borger17e3ebe2024-02-14 15:02:11 -0800794bool CameraService::hasPermissionsForCameraPrivacyAllowlist(int callingPid, int callingUid) const {
795 auto attributionSource = attributionSourceFromPidAndUid(callingPid, callingUid);
796 return mAttributionAndPermissionUtils->hasPermissionsForCameraPrivacyAllowlist(
797 attributionSource);
798}
799
800bool CameraService::hasPermissionsForOpenCloseListener(int callingPid, int callingUid) const {
801 auto attributionSource = attributionSourceFromPidAndUid(callingPid, callingUid);
802 return mAttributionAndPermissionUtils->hasPermissionsForOpenCloseListener(
803 attributionSource);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +0000804}
805
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800806Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700807 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100808 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700809 bool hasSystemCameraPermissions =
Austin Borger1c1bee02023-06-01 16:51:35 -0700810 hasPermissionsForSystemCamera(std::string(), CameraThreadState::getCallingPid(),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700811 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700812 switch (type) {
813 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700814 if (hasSystemCameraPermissions) {
815 *numCameras = static_cast<int>(mNormalDeviceIds.size());
816 } else {
817 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
818 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700820 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700821 if (hasSystemCameraPermissions) {
822 *numCameras = mNumberOfCameras;
823 } else {
824 *numCameras = mNumberOfCamerasWithoutSystemCamera;
825 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800826 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700827 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800828 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700829 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800830 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
831 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700832 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800833 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700834}
835
malikakash73125c62023-07-21 22:44:34 +0000836Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700837 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000838 const int pid = CameraThreadState::getCallingPid();
839 const int uid = CameraThreadState::getCallingUid();
840 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
841 __FUNCTION__, pid, uid);
842 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
843 "Permission Denial: no permission to configure camera id mapping");
844 }
845 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000846 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000847 if (!parseStatus.isOk()) {
848 return parseStatus;
849 }
850 remapCameraIds(cameraIdRemappingMap);
851 return Status::ok();
852}
853
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700854Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
855 /* out */
856 hardware::camera2::impl::CameraMetadataNative* request) {
857 ATRACE_CALL();
858
859 if (!flags::feature_combination_query()) {
860 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
861 "Camera subsystem doesn't support this method!");
862 }
863 if (!mInitialized) {
864 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
865 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
866 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
867 }
868
869 const std::string cameraId = resolveCameraId(unresolvedCameraId,
870 CameraThreadState::getCallingUid());
871
872 binder::Status res;
873 if (request == nullptr) {
874 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
875 "Camera %s: Error creating default request", cameraId.c_str());
876 return res;
877 }
878 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
879 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
880 cameraId, templateId, &tempId);
881 if (!res.isOk()) {
882 ALOGE("%s: Camera %s: failed to map request Template %d",
883 __FUNCTION__, cameraId.c_str(), templateId);
884 return res;
885 }
886
887 if (shouldRejectSystemCameraConnection(cameraId)) {
888 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
889 "request for system only device %s: ", cameraId.c_str());
890 }
891
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700892 CameraMetadata metadata;
893 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
894 if (err == OK) {
895 request->swap(metadata);
896 } else if (err == BAD_VALUE) {
897 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
898 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
899 cameraId.c_str(), templateId, strerror(-err), err);
900 } else {
901 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
902 "Camera %s: Error creating default request for template %d: %s (%d)",
903 cameraId.c_str(), templateId, strerror(-err), err);
904 }
905 return res;
906}
907
908Status CameraService::isSessionConfigurationWithParametersSupported(
909 const std::string& unresolvedCameraId,
910 const SessionConfiguration& sessionConfiguration,
911 /*out*/
912 bool* supported) {
913 ATRACE_CALL();
914
915 if (!flags::feature_combination_query()) {
916 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
917 "Camera subsystem doesn't support this method!");
918 }
919 if (!mInitialized) {
920 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
921 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
922 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
923 }
924
925 const std::string cameraId = resolveCameraId(unresolvedCameraId,
926 CameraThreadState::getCallingUid());
927 if (supported == nullptr) {
928 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
929 unresolvedCameraId.c_str());
930 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
931 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
932 }
933
934 if (shouldRejectSystemCameraConnection(cameraId)) {
935 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
936 "session configuration with parameters support for system only device %s: ",
937 cameraId.c_str());
938 }
939
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700940 *supported = false;
941 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
942 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
943 supported);
944 binder::Status res;
945 switch (ret) {
946 case OK:
947 // Expected, do nothing.
948 break;
949 case INVALID_OPERATION: {
950 std::string msg = fmt::sprintf(
951 "Camera %s: Session configuration query not supported!",
952 cameraId.c_str());
953 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
954 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
955 }
956
957 break;
958 default: {
959 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
960 strerror(-ret), ret);
961 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
962 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
963 msg.c_str());
964 }
965 }
966
967 return res;
968}
969
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800970Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
971 int targetSdkVersion, bool overrideToPortrait,
972 const SessionConfiguration& sessionConfiguration,
973 /*out*/ CameraMetadata* outMetadata) {
974 ATRACE_CALL();
975
976 if (!mInitialized) {
977 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
978 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
979 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
980 }
981
982 const std::string cameraId =
983 resolveCameraId(unresolvedCameraId, CameraThreadState::getCallingUid());
984
985 if (outMetadata == nullptr) {
986 std::string msg =
987 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
988 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
989 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
990 }
991
992 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
993 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
994
995 status_t ret = mCameraProviderManager->getSessionCharacteristics(
996 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
997
998 // TODO(b/303645857): Remove fingerprintable metadata if the caller process does not have
999 // camera access permission.
1000
1001 Status res = Status::ok();
1002 switch (ret) {
1003 case OK:
1004 // Expected, no handling needed.
1005 break;
1006 case INVALID_OPERATION: {
1007 std::string msg = fmt::sprintf(
1008 "Camera %s: Session characteristics query not supported!",
1009 cameraId.c_str());
1010 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
1011 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1012 }
1013 break;
1014 default: {
1015 std::string msg = fmt::sprintf("Camera %s: Error: %s (%d)", cameraId.c_str(),
1016 strerror(-ret), ret);
1017 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1018 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1019 }
1020 }
1021
1022 return res;
1023}
1024
malikakash82ed4352023-07-21 22:44:34 +00001025Status CameraService::parseCameraIdRemapping(
1026 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001027 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001028 std::string packageName;
1029 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +00001030 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001031 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001032 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001033 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1034 "CameraIdRemapping: Package name cannot be empty");
1035 }
malikakash214f6e62023-08-10 23:50:56 +00001036 if (packageIdRemapping.cameraIdsToReplace.size()
1037 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001038 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1039 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001040 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001041 }
malikakash214f6e62023-08-10 23:50:56 +00001042 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001043 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1044 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001045 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001046 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1047 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001048 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001049 }
1050 if (cameraIdToReplace == updatedCameraId) {
1051 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1052 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1053 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001054 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001055 }
1056 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001057 }
1058 }
1059 return Status::ok();
1060}
1061
1062void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1063 // Acquire mServiceLock and prevent other clients from connecting
1064 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1065 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1066
malikakashedb38962023-09-06 00:03:35 +00001067 // Collect all existing clients for camera Ids that are being
1068 // remapped in the new cameraIdRemapping, but only if they were being used by a
1069 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001070 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001071 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001072 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1073 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001074 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001075 id0.c_str(), id1.c_str());
1076 auto clientDescriptor = mActiveClientManager.get(id0);
1077 if (clientDescriptor != nullptr) {
1078 sp<BasicClient> clientSp = clientDescriptor->getValue();
1079 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001080 // This camera is being used by a targeted packageName and
1081 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001082 clientsToDisconnect.push_back(clientSp);
1083 cameraIdsToUpdate.push_back(id0);
1084 }
1085 }
1086 }
1087 }
1088
malikakashedb38962023-09-06 00:03:35 +00001089 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001090 // Notify the clients about the disconnection.
1091 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001092 CaptureResultExtras{});
1093 }
malikakash82ed4352023-07-21 22:44:34 +00001094
1095 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1096 // blocking other clients from connecting in mServiceLockWrapper if held.
1097 mServiceLock.unlock();
1098
malikakashedb38962023-09-06 00:03:35 +00001099 // Clear calling identity for disconnect() PID checks.
1100 int64_t token = CameraThreadState::clearCallingIdentity();
1101
malikakash82ed4352023-07-21 22:44:34 +00001102 // Disconnect clients.
1103 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001104 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1105 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001106 clientSp->disconnect();
1107 }
1108
malikakashedb38962023-09-06 00:03:35 +00001109 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1110 clientsToDisconnect.clear();
1111
1112 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001113 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001114
1115 {
1116 Mutex::Autolock lock(mCameraIdRemappingLock);
1117 // Update mCameraIdRemapping.
1118 mCameraIdRemapping.clear();
1119 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1120 }
malikakash82ed4352023-07-21 22:44:34 +00001121}
1122
malikakash22af94c2023-12-04 18:13:14 +00001123Status CameraService::injectSessionParams(
1124 const std::string& cameraId,
1125 const CameraMetadata& sessionParams) {
1126 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
1127 const int pid = CameraThreadState::getCallingPid();
1128 const int uid = CameraThreadState::getCallingUid();
1129 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1130 __FUNCTION__, pid, uid);
1131 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1132 "Permission Denial: no permission to inject session params");
1133 }
1134
1135 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1136 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1137
1138 auto clientDescriptor = mActiveClientManager.get(cameraId);
1139 if (clientDescriptor == nullptr) {
1140 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1141 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1142 "No active client for camera id %s", cameraId.c_str());
1143 }
1144
1145 sp<BasicClient> clientSp = clientDescriptor->getValue();
1146 status_t res = clientSp->injectSessionParams(sessionParams);
1147
1148 if (res != OK) {
1149 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1150 "Error injecting session params into camera \"%s\": %s (%d)",
1151 cameraId.c_str(), strerror(-res), res);
1152 }
1153 return Status::ok();
1154}
1155
Austin Borgered99f642023-06-01 16:51:35 -07001156std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1157 const std::string& inputCameraId, int clientUid) {
1158 std::string packageName = getPackageNameFromUid(clientUid);
1159 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001160 Mutex::Autolock lock(mCameraIdRemappingLock);
1161 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1162 packageMapIter != mCameraIdRemapping.end()) {
1163 for (auto& [id0, id1]: packageMapIter->second) {
1164 if (id1 == inputCameraId) {
1165 cameraIds.push_back(id0);
1166 }
1167 }
1168 }
1169 return cameraIds;
1170}
1171
Austin Borgered99f642023-06-01 16:51:35 -07001172std::string CameraService::resolveCameraId(
1173 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001174 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001175 const std::string& packageName) {
1176 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001177 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001178 packageNameVal = getPackageNameFromUid(clientUid);
1179 }
malikakash65d20692023-09-07 01:06:33 +00001180 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001181 // We shouldn't remap cameras for processes with system/vendor UIDs.
1182 return inputCameraId;
1183 }
malikakash82ed4352023-07-21 22:44:34 +00001184 Mutex::Autolock lock(mCameraIdRemappingLock);
1185 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1186 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001187 auto packageMap = packageMapIter->second;
1188 if (auto replacementIdIter = packageMap.find(inputCameraId);
1189 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001190 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001191 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001192 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001193 replacementIdIter->second.c_str());
1194 return replacementIdIter->second;
1195 }
1196 }
1197 return inputCameraId;
1198}
1199
Austin Borger18b30a72022-10-27 12:20:29 -07001200Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001201 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001202 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001203 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001204 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
1205 std::string cameraIdStr = resolveCameraId(
1206 unresolvedCameraId, CameraThreadState::getCallingUid());
1207
Austin Borgered99f642023-06-01 16:51:35 -07001208 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001209 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1210 "characteristics for system only device %s: ", cameraIdStr.c_str());
1211 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001212
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001213 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001214 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001215 return STATUS_ERROR(ERROR_DISCONNECTED,
1216 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001217 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001218 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001219 CameraThreadState::getCallingPid(), CameraThreadState::getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001220 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1221 if (hasSystemCameraPermissions) {
1222 cameraIdBound = mNumberOfCameras;
1223 }
1224 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001225 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1226 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001227 }
1228
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001229 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001230 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001231 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001232 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001233 if (err != OK) {
1234 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1235 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1236 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001237 logServiceError(std::string("Error retrieving camera info from device ")
1238 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001239 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001240
Ruben Brunkcc776712015-02-17 20:18:47 -08001241 return ret;
1242}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001243
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001244std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001245 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
1246 auto callingPid = CameraThreadState::getCallingPid();
1247 auto callingUid = CameraThreadState::getCallingUid();
Austin Borger17e3ebe2024-02-14 15:02:11 -08001248 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1249 callingPid, callingUid, /* checkCameraPermissions= */ false);
1250 if (systemCameraPermissions || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001251 deviceIds = &mNormalDeviceIds;
1252 }
1253 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001254 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001255 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001256 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001257 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001258
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001259 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001260}
1261
Austin Borgered99f642023-06-01 16:51:35 -07001262std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001263 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001264 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001265}
1266
Austin Borgered99f642023-06-01 16:51:35 -07001267Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001268 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001269 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001270
malikakashedb38962023-09-06 00:03:35 +00001271 const std::string cameraId = resolveCameraId(unresolvedCameraId,
1272 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -07001273
Zhijun He2b59be82013-09-25 10:14:30 -07001274 if (!cameraInfo) {
1275 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001276 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001277 }
1278
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001279 if (!mInitialized) {
1280 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001281 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001282 return STATUS_ERROR(ERROR_DISCONNECTED,
1283 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001284 }
1285
Austin Borgered99f642023-06-01 16:51:35 -07001286 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001287 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001288 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001289 }
1290
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001291 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001292
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001293 bool overrideForPerfClass =
1294 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001295 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001296 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001297 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001298 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001299 if (res == NAME_NOT_FOUND) {
1300 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001301 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001302 strerror(-res), res);
1303 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001304 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1305 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001306 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001307 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001308 strerror(-res), res);
1309 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001310 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001311 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001312 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1313 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001314 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001315 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001316 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001317 int callingPid = CameraThreadState::getCallingPid();
1318 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001319 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001320 // If it's not calling from cameraserver, check the permission only if
1321 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1322 // it would've already been checked in shouldRejectSystemCameraConnection.
Austin Borger17e3ebe2024-02-14 15:02:11 -08001323 bool checkPermissionForCamera = hasPermissionsForCamera(cameraId, callingPid, callingUid);
Emilian Peeve20c6372018-08-14 18:45:53 +01001324 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001325 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001326 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001327 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001328 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001329 &tagsRemoved);
1330 if (res != OK) {
1331 cameraInfo->clear();
1332 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1333 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001334 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001335 }
1336 }
1337
1338 if (!tagsRemoved.empty()) {
1339 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1340 tagsRemoved.data(), tagsRemoved.size());
1341 if (res != OK) {
1342 cameraInfo->clear();
1343 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001344 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001345 strerror(-res), res);
1346 }
1347 }
1348
Zhijun He2b59be82013-09-25 10:14:30 -07001349 return ret;
1350}
1351
malikakashedb38962023-09-06 00:03:35 +00001352Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001353 int32_t* torchStrength) {
1354 ATRACE_CALL();
1355 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001356 const std::string cameraId = resolveCameraId(
malikakash65d20692023-09-07 01:06:33 +00001357 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001358 if (!mInitialized) {
1359 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1360 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1361 }
1362
1363 if(torchStrength == NULL) {
1364 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1365 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1366 }
1367
Austin Borgered99f642023-06-01 16:51:35 -07001368 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001369 if (res != OK) {
1370 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001371 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001372 strerror(-res), res);
1373 }
1374 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1375 return Status::ok();
1376}
1377
Austin Borgered99f642023-06-01 16:51:35 -07001378std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001379 time_t now = time(nullptr);
1380 char formattedTime[64];
1381 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001382 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001383}
1384
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001385Status CameraService::getCameraVendorTagDescriptor(
1386 /*out*/
1387 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001388 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001389 if (!mInitialized) {
1390 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001391 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001392 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001393 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1394 if (globalDescriptor != nullptr) {
1395 *desc = *(globalDescriptor.get());
1396 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001397 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001398}
1399
Emilian Peev71c73a22017-03-21 16:35:51 +00001400Status CameraService::getCameraVendorTagCache(
1401 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1402 ATRACE_CALL();
1403 if (!mInitialized) {
1404 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1405 return STATUS_ERROR(ERROR_DISCONNECTED,
1406 "Camera subsystem not available");
1407 }
1408 sp<VendorTagDescriptorCache> globalCache =
1409 VendorTagDescriptorCache::getGlobalVendorTagCache();
1410 if (globalCache != nullptr) {
1411 *cache = *(globalCache.get());
1412 }
1413 return Status::ok();
1414}
1415
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001416void CameraService::clearCachedVariables() {
1417 BasicClient::BasicClient::sCameraService = nullptr;
1418}
1419
Austin Borgered99f642023-06-01 16:51:35 -07001420std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001421 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001422 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001423
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001424 int deviceVersion = 0;
1425
Emilian Peevf53f66e2017-04-11 14:29:43 +01001426 status_t res;
1427 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001428 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001429 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001430 if (res != OK || transport == IPCTransport::INVALID) {
1431 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001432 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001433 return std::make_pair(-1, IPCTransport::INVALID) ;
1434 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001435 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001436
Emilian Peevf53f66e2017-04-11 14:29:43 +01001437 hardware::CameraInfo info;
1438 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001439 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001440 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001441 if (res != OK) {
1442 return std::make_pair(-1, IPCTransport::INVALID);
1443 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001444 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001445 if (orientation) {
1446 *orientation = info.orientation;
1447 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001448 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001449
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001450 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001451}
1452
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001454 switch(err) {
1455 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001456 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001457 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1459 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001460 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 return STATUS_ERROR(ERROR_DISCONNECTED,
1462 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001463 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1465 "Camera HAL encountered error %d: %s",
1466 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001467 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001468}
1469
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001470Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001471 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1472 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001473 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001474 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001475 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001476 bool forceSlowJpegMode, const std::string& originalCameraId,
1477 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001478 // For HIDL devices
1479 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1480 // Create CameraClient based on device version reported by the HAL.
1481 int deviceVersion = deviceVersionAndTransport.first;
1482 switch(deviceVersion) {
1483 case CAMERA_DEVICE_API_VERSION_1_0:
1484 ALOGE("Camera using old HAL version: %d", deviceVersion);
1485 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1486 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001487 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001488 break;
1489 case CAMERA_DEVICE_API_VERSION_3_0:
1490 case CAMERA_DEVICE_API_VERSION_3_1:
1491 case CAMERA_DEVICE_API_VERSION_3_2:
1492 case CAMERA_DEVICE_API_VERSION_3_3:
1493 case CAMERA_DEVICE_API_VERSION_3_4:
1494 case CAMERA_DEVICE_API_VERSION_3_5:
1495 case CAMERA_DEVICE_API_VERSION_3_6:
1496 case CAMERA_DEVICE_API_VERSION_3_7:
1497 break;
1498 default:
1499 // Should not be reachable
1500 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1501 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1502 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001503 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001504 }
1505 }
1506 if (effectiveApiLevel == API_1) { // Camera1 API route
1507 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001508 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger17e3ebe2024-02-14 15:02:11 -08001509 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001510 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001511 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1512 forceSlowJpegMode);
1513 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1514 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001515 } else { // Camera2 API route
1516 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1517 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001518 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger17e3ebe2024-02-14 15:02:11 -08001519 cameraService->mCameraServiceProxyWrapper,
1520 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001521 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001522 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001523 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001524 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001525 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001526}
1527
Austin Borgered99f642023-06-01 16:51:35 -07001528std::string CameraService::toString(std::set<userid_t> intSet) {
1529 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001530 bool first = true;
1531 for (userid_t i : intSet) {
1532 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001533 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001534 first = false;
1535 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001536 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001537 }
1538 }
Austin Borgered99f642023-06-01 16:51:35 -07001539 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001540}
1541
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001542int32_t CameraService::mapToInterface(TorchModeStatus status) {
1543 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1544 switch (status) {
1545 case TorchModeStatus::NOT_AVAILABLE:
1546 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1547 break;
1548 case TorchModeStatus::AVAILABLE_OFF:
1549 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1550 break;
1551 case TorchModeStatus::AVAILABLE_ON:
1552 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1553 break;
1554 default:
1555 ALOGW("Unknown new flash status: %d", status);
1556 }
1557 return serviceStatus;
1558}
1559
1560CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1561 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1562 switch (status) {
1563 case CameraDeviceStatus::NOT_PRESENT:
1564 serviceStatus = StatusInternal::NOT_PRESENT;
1565 break;
1566 case CameraDeviceStatus::PRESENT:
1567 serviceStatus = StatusInternal::PRESENT;
1568 break;
1569 case CameraDeviceStatus::ENUMERATING:
1570 serviceStatus = StatusInternal::ENUMERATING;
1571 break;
1572 default:
1573 ALOGW("Unknown new HAL device status: %d", status);
1574 }
1575 return serviceStatus;
1576}
1577
1578int32_t CameraService::mapToInterface(StatusInternal status) {
1579 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1580 switch (status) {
1581 case StatusInternal::NOT_PRESENT:
1582 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1583 break;
1584 case StatusInternal::PRESENT:
1585 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1586 break;
1587 case StatusInternal::ENUMERATING:
1588 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1589 break;
1590 case StatusInternal::NOT_AVAILABLE:
1591 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1592 break;
1593 case StatusInternal::UNKNOWN:
1594 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1595 break;
1596 default:
1597 ALOGW("Unknown new internal device status: %d", status);
1598 }
1599 return serviceStatus;
1600}
1601
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001603 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001604
Austin Borgered99f642023-06-01 16:51:35 -07001605 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001606 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001607 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001609 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1610 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001611 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001612 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001613 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001614 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001615 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001616 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001617 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001618}
1619
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001621 /*out*/
1622 CameraParameters* parameters) {
1623
1624 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1625
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001627
1628 if (parameters == NULL) {
1629 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001630 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001631 }
1632
malikakashedb38962023-09-06 00:03:35 +00001633 std::string unresolvedCameraId = std::to_string(cameraId);
1634 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1635 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001636
1637 // Check if we already have parameters
1638 {
1639 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001640 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001641 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001642 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001643 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001645 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001646 }
1647 CameraParameters p = cameraState->getShimParams();
1648 if (!p.isEmpty()) {
1649 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651 }
1652 }
1653
Jayant Chowdhary12361932018-08-27 14:46:13 -07001654 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001656 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001657 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001658 // Error already logged by callee
1659 return ret;
1660 }
1661
1662 // Check for parameters again
1663 {
1664 // Scope for service lock
1665 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001666 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001668 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001669 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001670 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001671 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001672 CameraParameters p = cameraState->getShimParams();
1673 if (!p.isEmpty()) {
1674 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001675 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001676 }
1677 }
1678
Ruben Brunkcc776712015-02-17 20:18:47 -08001679 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1680 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001681 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001682}
1683
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001684// Can camera service trust the caller based on the calling UID?
Austin Borger17e3ebe2024-02-14 15:02:11 -08001685bool CameraService::isTrustedCallingUid(uid_t uid) const {
1686 return mAttributionAndPermissionUtils->isTrustedCallingUid(uid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001687}
1688
Austin Borger17e3ebe2024-02-14 15:02:11 -08001689status_t CameraService::getUidForPackage(const std::string &packageName, int userId,
1690 /*inout*/uid_t& uid, int err) const {
1691 return mAttributionAndPermissionUtils->getUidForPackage(packageName, userId, uid, err);
Nicholas Sauera3620332019-04-03 14:05:17 -07001692}
1693
Austin Borgered99f642023-06-01 16:51:35 -07001694Status CameraService::validateConnectLocked(const std::string& cameraId,
1695 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001696 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001697
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001698#ifdef __BRILLO__
1699 UNUSED(clientName8);
1700 UNUSED(clientUid);
1701 UNUSED(clientPid);
1702 UNUSED(originalClientPid);
1703#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001704 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1705 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001706 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001707 return allowed;
1708 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001709#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001710
Jayant Chowdhary12361932018-08-27 14:46:13 -07001711 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001712
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001713 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001714 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1715 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001716 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001717 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001718 }
1719
Ruben Brunkcc776712015-02-17 20:18:47 -08001720 if (getCameraState(cameraId) == nullptr) {
1721 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001722 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001723 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001724 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001725 }
1726
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001727 status_t err = checkIfDeviceIsUsable(cameraId);
1728 if (err != NO_ERROR) {
1729 switch(err) {
1730 case -ENODEV:
1731 case -EBUSY:
1732 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001733 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001734 default:
1735 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001736 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001737 }
1738 }
1739 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001740}
1741
Austin Borgered99f642023-06-01 16:51:35 -07001742Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1743 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001744 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001745 int callingPid = CameraThreadState::getCallingPid();
1746 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001747
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001748 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001749 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001750 clientUid = callingUid;
1751 } else if (!isTrustedCallingUid(callingUid)) {
1752 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1753 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001754 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1755 "Untrusted caller (calling PID %d, UID %d) trying to "
1756 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001757 callingPid, callingUid, cameraId.c_str(),
1758 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001759 }
1760
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001761 // Check if we can trust clientPid
1762 if (clientPid == USE_CALLING_PID) {
1763 clientPid = callingPid;
1764 } else if (!isTrustedCallingUid(callingUid)) {
1765 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1766 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001767 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1768 "Untrusted caller (calling PID %d, UID %d) trying to "
1769 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001770 callingPid, callingUid, cameraId.c_str(),
1771 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001772 }
1773
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001774 if (shouldRejectSystemCameraConnection(cameraId)) {
1775 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1776 cameraId.c_str());
1777 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001778 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001779 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001780 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1781 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001782 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001783 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001784 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001785
1786 }
1787
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001788 // If it's not calling from cameraserver, check the permission if the
1789 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1790 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger17e3ebe2024-02-14 15:02:11 -08001791 bool checkPermissionForCamera = hasPermissionsForCamera(cameraId, clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001792 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001793 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001794 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001795 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1796 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001797 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001798 }
1799
Svet Ganova453d0d2018-01-11 15:37:58 -08001800 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001801 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001802 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001803 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1804 clientPid, clientUid);
1805 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001806 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1807 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001808 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001809 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001810 }
1811
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001812 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1813 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1814 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1815 if ((!isAutomotivePrivilegedClient(callingUid) ||
1816 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1817 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001818 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1819 return STATUS_ERROR_FMT(ERROR_DISABLED,
1820 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001821 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001822 }
1823
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001824 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1825 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001826 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001827 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001828
Ruben Brunk6267b532015-04-30 17:44:07 -07001829 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001830
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001831 // For non-system clients : Only allow clients who are being used by the current foreground
1832 // device user, unless calling from our own process.
1833 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001834 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001835 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1836 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001837 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001838 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1839 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001840 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001841 }
1842
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001843 if (flags::camera_hsum_permission()) {
1844 // If the System User tries to access the camera when the device is running in
1845 // headless system user mode, ensure that client has the required permission
1846 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger17e3ebe2024-02-14 15:02:11 -08001847 if (mAttributionAndPermissionUtils->isHeadlessSystemUserMode()
1848 && (clientUserId == USER_SYSTEM)
1849 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001850 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1851 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1852 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1853 User without camera headless system user permission",
1854 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
1855 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001856 }
1857
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001859}
1860
Austin Borgered99f642023-06-01 16:51:35 -07001861status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001863 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001864 if (cameraState == nullptr) {
1865 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001866 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001867 return -ENODEV;
1868 }
1869
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001870 StatusInternal currentStatus = cameraState->getStatus();
1871 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001872 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001873 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001874 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001875 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001877 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001878 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001879 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001880
Ruben Brunkcc776712015-02-17 20:18:47 -08001881 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001882}
1883
Ruben Brunkcc776712015-02-17 20:18:47 -08001884void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001885 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001886
Ruben Brunkcc776712015-02-17 20:18:47 -08001887 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001888 auto clientDescriptor =
1889 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001890 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001891 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1892
1893 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001894 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001895
1896 if (evicted.size() > 0) {
1897 // This should never happen - clients should already have been removed in disconnect
1898 for (auto& i : evicted) {
1899 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001900 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001901 }
1902
1903 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1904 __FUNCTION__);
1905 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001906
1907 // And register a death notification for the client callback. Do
1908 // this last to avoid Binder policy where a nested Binder
1909 // transaction might be pre-empted to service the client death
1910 // notification if the client process dies before linkToDeath is
1911 // invoked.
1912 sp<IBinder> remoteCallback = client->getRemote();
1913 if (remoteCallback != nullptr) {
1914 remoteCallback->linkToDeath(this);
1915 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001916}
1917
Austin Borgered99f642023-06-01 16:51:35 -07001918status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1919 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1920 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001921 /*out*/
1922 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001923 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001924 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001925 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001926 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001927 DescriptorPtr clientDescriptor;
1928 {
1929 if (effectiveApiLevel == API_1) {
1930 // If we are using API1, any existing client for this camera ID with the same remote
1931 // should be returned rather than evicted to allow MediaRecorder to work properly.
1932
1933 auto current = mActiveClientManager.get(cameraId);
1934 if (current != nullptr) {
1935 auto clientSp = current->getValue();
1936 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001937 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001938 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001939 " API level, evicting prior client...");
1940 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001941 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001942 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001943 *client = clientSp;
1944 return NO_ERROR;
1945 }
1946 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001947 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001948 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001949
Ruben Brunkcc776712015-02-17 20:18:47 -08001950 // Get state for the given cameraId
1951 auto state = getCameraState(cameraId);
1952 if (state == nullptr) {
1953 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001954 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001955 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001956 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001957 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001958
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001959 sp<IServiceManager> sm = defaultServiceManager();
1960 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
1961 if (!binder && isAutomotivePrivilegedClient(CameraThreadState::getCallingUid())) {
1962 // If processinfo service is not available and the client is automotive privileged
1963 // client used for safety critical uses cases such as rear-view and surround-view which
1964 // needs to be available before android boot completes, then use the hardcoded values
1965 // for the process state and priority score. As this scenario is before android system
1966 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1967 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1968 // visible on the top.
1969 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1970 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1971 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1972 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1973 } else {
1974 // Get current active client PIDs
1975 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1976 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001977
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001978 std::vector<int> priorityScores(ownerPids.size());
1979 std::vector<int> states(ownerPids.size());
1980
1981 // Get priority scores of all active PIDs
1982 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1983 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1984 if (err != OK) {
1985 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1986 return err;
1987 }
1988
1989 // Update all active clients' priorities
1990 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1991 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1992 pidToPriorityMap.emplace(ownerPids[i],
1993 resource_policy::ClientPriority(priorityScores[i], states[i],
1994 /* isVendorClient won't get copied over*/ false,
1995 /* oomScoreOffset won't get copied over*/ 0));
1996 }
1997 mActiveClientManager.updatePriorities(pidToPriorityMap);
1998
1999 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2000 int32_t actualState = states[states.size() - 1];
2001
2002 // Make descriptor for incoming client. We store the oomScoreOffset
2003 // since we might need it later on new handleEvictionsLocked and
2004 // ProcessInfoService would not take that into account.
2005 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2006 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2007 state->getConflicting(), actualScore, clientPid, actualState,
2008 oomScoreOffset, systemNativeClient);
2009 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002010
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002011 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2012
Ruben Brunkcc776712015-02-17 20:18:47 -08002013 // Find clients that would be evicted
2014 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2015
2016 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2017 // background, so we cannot do evictions
2018 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2019 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2020 " priority).", clientPid);
2021
2022 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002023 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 auto incompatibleClients =
2025 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2026
Austin Borgered99f642023-06-01 16:51:35 -07002027 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2028 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2029 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002030 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002031
2032 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002033 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002034 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002035 i->getKey().c_str(),
2036 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002037 i->getOwnerId(), i->getPriority().getScore(),
2038 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002039 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002040 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2041 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002042 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 }
2044
2045 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002046 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002047 mEventLog.add(msg);
2048
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002049 auto current = mActiveClientManager.get(cameraId);
2050 if (current != nullptr) {
2051 return -EBUSY; // CAMERA_IN_USE
2052 } else {
2053 return -EUSERS; // MAX_CAMERAS_IN_USE
2054 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002055 }
2056
2057 for (auto& i : evicted) {
2058 sp<BasicClient> clientSp = i->getValue();
2059 if (clientSp.get() == nullptr) {
2060 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2061
2062 // TODO: Remove this
2063 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2064 __FUNCTION__);
2065 mActiveClientManager.remove(i);
2066 continue;
2067 }
2068
2069 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002070 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002071 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002072
Ruben Brunkcc776712015-02-17 20:18:47 -08002073 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002074 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002075 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2076 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002077 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002078 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002079 i->getPriority().getState(), cameraId.c_str(),
2080 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002081 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002082
2083 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002084 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002085 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002086 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002087 }
2088
Ruben Brunkcc776712015-02-17 20:18:47 -08002089 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2090 // other clients from connecting in mServiceLockWrapper if held
2091 mServiceLock.unlock();
2092
2093 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002094 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002095
2096 // Destroy evicted clients
2097 for (auto& i : evictedClients) {
2098 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002099 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002100 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002101
Jayant Chowdhary12361932018-08-27 14:46:13 -07002102 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002103
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002104 for (const auto& i : evictedClients) {
2105 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002106 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002107 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2108 if (ret == TIMED_OUT) {
2109 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002110 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2111 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002112 return -EBUSY;
2113 }
2114 if (ret != NO_ERROR) {
2115 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002116 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2117 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002118 return ret;
2119 }
2120 }
2121
2122 evictedClients.clear();
2123
Ruben Brunkcc776712015-02-17 20:18:47 -08002124 // Once clients have been disconnected, relock
2125 mServiceLock.lock();
2126
2127 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2128 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2129 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002130 }
2131
Ruben Brunkcc776712015-02-17 20:18:47 -08002132 *partial = clientDescriptor;
2133 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002134}
2135
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002136Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002137 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002138 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002139 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002140 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002141 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002142 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002143 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002144 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002145 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002146 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002147
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002148 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002149 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002150
malikakashedb38962023-09-06 00:03:35 +00002151 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
2152 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
2153 CameraThreadState::getCallingUid());
2154
Ruben Brunkcc776712015-02-17 20:18:47 -08002155 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002156 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2157 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002158 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002159 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002160
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002161 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002162 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
2163 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002164 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002165 }
2166
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002167 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002168
2169 const sp<IServiceManager> sm(defaultServiceManager());
2170 const auto& mActivityManager = getActivityManager();
2171 if (mActivityManager) {
2172 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2173 CameraThreadState::getCallingUid(),
2174 CameraThreadState::getCallingPid());
2175 }
2176
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002177 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002178}
2179
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002180bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2181 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002182 // If the client is not a vendor client, don't add listener if
2183 // a) the camera is a publicly hidden secure camera OR
2184 // b) the camera is a system only camera and the client doesn't
2185 // have android.permission.SYSTEM_CAMERA permissions.
2186 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2187 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002188 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002189 return true;
2190 }
2191 return false;
2192}
2193
Austin Borgered99f642023-06-01 16:51:35 -07002194bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002195 // Rules for rejection:
2196 // 1) If cameraserver tries to access this camera device, accept the
2197 // connection.
2198 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002199 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002200 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2201 // and the serving thread is a non hwbinder thread, the client must have
2202 // android.permission.SYSTEM_CAMERA permissions to connect.
2203
2204 int cPid = CameraThreadState::getCallingPid();
2205 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002206 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002207 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2208 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002209 // This isn't a known camera ID, so it's not a system camera
2210 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2211 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002212 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002213
2214 // (1) Cameraserver trying to connect, accept.
Austin Borger17e3ebe2024-02-14 15:02:11 -08002215 if (mAttributionAndPermissionUtils->isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002216 return false;
2217 }
2218 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002219 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002220 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2221 return true;
2222 }
2223 // (3) Here we only check for permissions if it is a system only camera device. This is since
2224 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2225 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2226 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002227 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002228 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002229 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2230 cameraId.c_str());
2231 return true;
2232 }
2233
2234 return false;
2235}
2236
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002237Status CameraService::connectDevice(
2238 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002239 const std::string& unresolvedCameraId,
2240 const std::string& clientPackageName,
2241 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002242 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002243 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08002244 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002245 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002246
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002247 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002248 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002249 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002250 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002251 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002252 bool systemNativeClient = false;
2253 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
2254 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07002255 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
2256 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002257 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002258 }
malikakashedb38962023-09-06 00:03:35 +00002259 const std::string cameraId = resolveCameraId(
2260 unresolvedCameraId,
2261 CameraThreadState::getCallingUid(),
2262 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002263
2264 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002265 std::string msg =
2266 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2267 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2268 cameraId.c_str());
2269 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2270 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002271 }
2272
Austin Borger9bfa0a72022-08-03 17:50:40 -07002273 userid_t clientUserId = multiuser_get_user_id(clientUid);
2274 int callingUid = CameraThreadState::getCallingUid();
2275 if (clientUid == USE_CALLING_UID) {
2276 clientUserId = multiuser_get_user_id(callingUid);
2277 }
2278
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002279 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2280 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002281 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2282 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002283 std::string msg = "Camera disabled by device policy";
2284 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2285 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002286 }
2287
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002288 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002289 if (oomScoreOffset > 0
2290 && !hasPermissionsForSystemCamera(cameraId, callingPid,
2291 CameraThreadState::getCallingUid())
2292 && !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07002293 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002294 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002295 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2296 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2297 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002298 }
2299
Austin Borgered99f642023-06-01 16:51:35 -07002300 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2301 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002302 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002303 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002304 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002305
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002306 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002307 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002308 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002309 }
2310
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002311 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002312 Mutex::Autolock lock(mServiceLock);
2313
2314 // Clear the previous cached logs and reposition the
2315 // file offset to beginning of the file to log new data.
2316 // If either truncate or lseek fails, close the previous file and create a new one.
2317 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2318 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2319 // Close the previous memfd.
2320 close(mMemFd);
2321 // If failure to wipe the data, then create a new file and
2322 // assign the new value to mMemFd.
2323 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2324 if (mMemFd == -1) {
2325 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2326 }
2327 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002328 const sp<IServiceManager> sm(defaultServiceManager());
2329 const auto& mActivityManager = getActivityManager();
2330 if (mActivityManager) {
2331 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2332 CameraThreadState::getCallingUid(),
2333 CameraThreadState::getCallingPid());
2334 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002335 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002336}
2337
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002338bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2339 int callingPid, int callingUid) {
2340 if (!isAutomotiveDevice()) {
2341 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2342 }
2343
2344 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2345 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2346 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2347 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2348 "using camera %s", callingUid, cam_id.c_str());
2349 return false;
2350 }
2351
2352 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2353 return true;
2354 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2355 return false;
2356 } else if ((mSensorPrivacyPolicy->getCameraPrivacyState()
2357 == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS) ||
2358 (mSensorPrivacyPolicy->getCameraPrivacyState()
2359 == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS) ||
2360 (mSensorPrivacyPolicy->getCameraPrivacyState() ==
2361 SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_APPS)) {
2362 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2363 return false;
2364 } else {
2365 return true;
2366 }
2367 }
2368 return false;
2369}
2370
Austin Borgered99f642023-06-01 16:51:35 -07002371std::string CameraService::getPackageNameFromUid(int clientUid) {
2372 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002373
2374 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002375 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002376 if (binder == 0) {
2377 ALOGE("Cannot get permission service");
2378 // Return empty package name and the further interaction
2379 // with camera will likely fail
2380 return packageName;
2381 }
2382
2383 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2384 Vector<String16> packages;
2385
2386 permCtrl->getPackagesForUid(clientUid, packages);
2387
2388 if (packages.isEmpty()) {
2389 ALOGE("No packages for calling UID %d", clientUid);
2390 // Return empty package name and the further interaction
2391 // with camera will likely fail
2392 return packageName;
2393 }
2394
2395 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002396 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002397
2398 return packageName;
2399}
2400
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002401template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002402Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2403 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2404 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002405 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002406 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002407 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002408 binder::Status ret = binder::Status::ok();
2409
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002410 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002411 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002412 int packageUid = (clientUid == USE_CALLING_UID) ?
2413 CameraThreadState::getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002414 if (clientPackageNameMaybe.size() <= 0) {
2415 // NDK calls don't come with package names, but we need one for various cases.
2416 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2417 // do exist. For all authentication cases, all packages under the same UID get the
2418 // same permissions, so picking any associated package name is sufficient. For some
2419 // other cases, this may give inaccurate names for clients in logs.
2420 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002421 clientPackageName = getPackageNameFromUid(packageUid);
2422 } else {
2423 clientPackageName = clientPackageNameMaybe;
2424 }
2425
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002426 int originalClientPid = 0;
2427
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002428 int packagePid = (clientPid == USE_CALLING_PID) ?
2429 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002430 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002431 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002432 static_cast<int>(effectiveApiLevel));
2433
Shuzhen Wang316781a2020-08-18 18:11:01 -07002434 nsecs_t openTimeNs = systemTime();
2435
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002436 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002437 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002438 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002439
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002440 {
2441 // Acquire mServiceLock and prevent other clients from connecting
2442 std::unique_ptr<AutoConditionLock> lock =
2443 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2444
2445 if (lock == nullptr) {
2446 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2447 , clientPid);
2448 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2449 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002450 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002451 }
2452
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002453 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002454 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002455 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2456 return ret;
2457 }
2458
2459 // Check the shim parameters after acquiring lock, if they have already been updated and
2460 // we were doing a shim update, return immediately
2461 if (shimUpdateOnly) {
2462 auto cameraState = getCameraState(cameraId);
2463 if (cameraState != nullptr) {
2464 if (!cameraState->getShimParams().isEmpty()) return ret;
2465 }
2466 }
2467
2468 status_t err;
2469
2470 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002471 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002472 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002473 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2474 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002475 switch (err) {
2476 case -ENODEV:
2477 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2478 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002479 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002480 case -EBUSY:
2481 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2482 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002483 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002484 case -EUSERS:
2485 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2486 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002487 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002488 default:
2489 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2490 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002491 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002492 }
2493 }
2494
2495 if (clientTmp.get() != nullptr) {
2496 // Handle special case for API1 MediaRecorder where the existing client is returned
2497 device = static_cast<CLIENT*>(clientTmp.get());
2498 return ret;
2499 }
2500
2501 // give flashlight a chance to close devices if necessary.
2502 mFlashlight->prepareDeviceOpen(cameraId);
2503
Austin Borger18b30a72022-10-27 12:20:29 -07002504 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002505 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002506 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2507 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002508 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002509 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002510 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002511 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002512 }
2513
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002514 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002515 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002516 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002517 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002518 clientFeatureId, cameraId, api1CameraId, facing,
2519 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002520 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002521 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002522 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002523 return ret;
2524 }
2525 client = static_cast<CLIENT*>(tmp.get());
2526
2527 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2528 __FUNCTION__);
2529
Austin Borgered99f642023-06-01 16:51:35 -07002530 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002531 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002532 if (err != OK) {
2533 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002534 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002535 mServiceLock.unlock();
2536 client->disconnect();
2537 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002538 switch(err) {
2539 case BAD_VALUE:
2540 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002541 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002542 case -EBUSY:
2543 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002544 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002545 case -EUSERS:
2546 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2547 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002548 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002549 case PERMISSION_DENIED:
2550 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002551 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002552 case -EACCES:
2553 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002554 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002555 case -ENODEV:
2556 default:
2557 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002558 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002559 strerror(-err), err);
2560 }
2561 }
2562
2563 // Update shim paremeters for legacy clients
2564 if (effectiveApiLevel == API_1) {
2565 // Assume we have always received a Client subclass for API1
2566 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2567 String8 rawParams = shimClient->getParameters();
2568 CameraParameters params(rawParams);
2569
2570 auto cameraState = getCameraState(cameraId);
2571 if (cameraState != nullptr) {
2572 cameraState->setShimParams(params);
2573 } else {
2574 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002575 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002576 }
2577 }
2578
Ravneetaeb20dc2022-03-30 05:33:03 +00002579 // Enable/disable camera service watchdog
2580 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2581
Emilian Peev6d45db82024-01-18 20:11:54 +00002582 CameraMetadata chars;
2583 bool rotateAndCropSupported = true;
2584 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2585 &chars, overrideToPortrait);
2586 if (err == OK) {
2587 auto availableRotateCropEntry = chars.find(
2588 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2589 if (availableRotateCropEntry.count <= 1) {
2590 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002591 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002592 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002593 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2594 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002595 }
2596
Emilian Peev6d45db82024-01-18 20:11:54 +00002597 if (rotateAndCropSupported) {
2598 // Set rotate-and-crop override behavior
2599 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2600 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2601 } else if (overrideToPortrait && portraitRotation != 0) {
2602 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2603 switch (portraitRotation) {
2604 case 90:
2605 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2606 break;
2607 case 180:
2608 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2609 break;
2610 case 270:
2611 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2612 break;
2613 default:
2614 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2615 break;
2616 }
2617 client->setRotateAndCropOverride(rotateAndCropMode);
2618 } else {
2619 client->setRotateAndCropOverride(
2620 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2621 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2622 }
2623 }
2624
2625 bool autoframingSupported = true;
2626 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2627 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2628 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2629 autoframingSupported = false;
2630 }
2631
2632 if (autoframingSupported) {
2633 // Set autoframing override behaviour
2634 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2635 client->setAutoframingOverride(mOverrideAutoframingMode);
2636 } else {
2637 client->setAutoframingOverride(
2638 mCameraServiceProxyWrapper->getAutoframingOverride(
2639 clientPackageName));
2640 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002641 }
2642
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002643 bool isCameraPrivacyEnabled;
2644 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002645 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002646 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2647 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2648 } else {
2649 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002650 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002651 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002652
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002653 if (client->supportsCameraMute()) {
2654 client->setCameraMute(
2655 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2656 } else if (isCameraPrivacyEnabled) {
2657 // no camera mute supported, but privacy is on! => disconnect
2658 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2659 client->getPackageName().c_str(), cameraId.c_str());
2660 // Do not hold mServiceLock while disconnecting clients, but
2661 // retain the condition blocking other clients from connecting
2662 // in mServiceLockWrapper if held.
2663 mServiceLock.unlock();
2664 // Clear caller identity temporarily so client disconnect PID
2665 // checks work correctly
2666 int64_t token = CameraThreadState::clearCallingIdentity();
2667 // Note AppOp to trigger the "Unblock" dialog
2668 client->noteAppOp();
2669 client->disconnect();
2670 CameraThreadState::restoreCallingIdentity(token);
2671 // Reacquire mServiceLock
2672 mServiceLock.lock();
2673
2674 return STATUS_ERROR_FMT(ERROR_DISABLED,
2675 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002676 }
2677
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002678 if (shimUpdateOnly) {
2679 // If only updating legacy shim parameters, immediately disconnect client
2680 mServiceLock.unlock();
2681 client->disconnect();
2682 mServiceLock.lock();
2683 } else {
2684 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002685 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002686 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002687
2688 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002689 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002690 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002691 } // lock is destroyed, allow further connect calls
2692
2693 // Important: release the mutex here so the client can call back into the service from its
2694 // destructor (can be at the end of the call)
2695 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002696
2697 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002698 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002699 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002700
Cliff Wud3a05312021-04-26 23:07:31 +08002701 {
2702 Mutex::Autolock lock(mInjectionParametersLock);
2703 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2704 mInjectionInitPending = false;
2705 status_t res = NO_ERROR;
2706 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2707 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002708 sp<BasicClient> clientSp = clientDescriptor->getValue();
2709 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2710 if(res != OK) {
2711 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2712 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002713 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002714 }
2715 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002716 if (res != OK) {
2717 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2718 }
2719 } else {
2720 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002721 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002722 res = NO_INIT;
2723 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2724 }
2725 }
2726 }
2727
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002728 return ret;
2729}
2730
Austin Borgered99f642023-06-01 16:51:35 -07002731status_t CameraService::addOfflineClient(const std::string &cameraId,
2732 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002733 if (offlineClient.get() == nullptr) {
2734 return BAD_VALUE;
2735 }
2736
2737 {
2738 // Acquire mServiceLock and prevent other clients from connecting
2739 std::unique_ptr<AutoConditionLock> lock =
2740 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2741
2742 if (lock == nullptr) {
2743 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2744 , __FUNCTION__, offlineClient->getClientPid());
2745 return TIMED_OUT;
2746 }
2747
2748 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2749 if (onlineClientDesc.get() == nullptr) {
2750 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2751 cameraId.c_str());
2752 return BAD_VALUE;
2753 }
2754
2755 // Offline clients do not evict or conflict with other online devices. Resource sharing
2756 // conflicts are handled by the camera provider which will either succeed or fail before
2757 // reaching this method.
2758 const auto& onlinePriority = onlineClientDesc->getPriority();
2759 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2760 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002761 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002762 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002763 // native clients don't have offline processing support.
2764 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002765 if (offlineClientDesc == nullptr) {
2766 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2767 return BAD_VALUE;
2768 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002769
2770 // Allow only one offline device per camera
2771 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2772 if (!incompatibleClients.empty()) {
2773 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2774 return BAD_VALUE;
2775 }
2776
Austin Borgered99f642023-06-01 16:51:35 -07002777 std::string monitorTags = isClientWatched(offlineClient.get())
2778 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002779 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002780 if (err != OK) {
2781 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2782 return err;
2783 }
2784
2785 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2786 if (evicted.size() > 0) {
2787 for (auto& i : evicted) {
2788 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002789 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002790 }
2791
2792 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2793 "properly", __FUNCTION__);
2794
2795 return BAD_VALUE;
2796 }
2797
2798 logConnectedOffline(offlineClientDesc->getKey(),
2799 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002800 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002801
2802 sp<IBinder> remoteCallback = offlineClient->getRemote();
2803 if (remoteCallback != nullptr) {
2804 remoteCallback->linkToDeath(this);
2805 }
2806 } // lock is destroyed, allow further connect calls
2807
2808 return OK;
2809}
2810
Austin Borgered99f642023-06-01 16:51:35 -07002811Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger1c1bee02023-06-01 16:51:35 -07002812 int32_t torchStrength, const sp<IBinder>& clientBinder) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002813 Mutex::Autolock lock(mServiceLock);
2814
2815 ATRACE_CALL();
2816 if (clientBinder == nullptr) {
2817 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2818 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2819 "Torch client binder in null.");
2820 }
2821
Rucha Katakwar38284522021-11-10 11:25:21 -08002822 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002823 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002824 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002825 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002826 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002827 }
2828
2829 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002830 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002831 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002832 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002833 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002834 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002835 }
2836
2837 StatusInternal cameraStatus = state->getStatus();
2838 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2839 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002840 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002841 (int)cameraStatus);
2842 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002843 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002844 }
2845
2846 {
2847 Mutex::Autolock al(mTorchStatusMutex);
2848 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002849 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002850 if (err != OK) {
2851 if (err == NAME_NOT_FOUND) {
2852 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002853 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002854 }
2855 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002856 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002857 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2858 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002859 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002860 }
2861
2862 if (status == TorchModeStatus::NOT_AVAILABLE) {
2863 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2864 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002865 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002866 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2867 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002868 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002869 } else {
2870 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002871 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002872 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2873 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002874 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002875 }
2876 }
2877 }
2878
2879 {
2880 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002881 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002882 }
2883 // Check if the current torch strength level is same as the new one.
2884 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002885 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002886
Austin Borgered99f642023-06-01 16:51:35 -07002887 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002888
2889 if (err != OK) {
2890 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002891 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002892 switch (err) {
2893 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002894 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2895 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002896 errorCode = ERROR_ILLEGAL_ARGUMENT;
2897 break;
2898 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002899 msg = fmt::sprintf("Camera \"%s\" is in use",
2900 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002901 errorCode = ERROR_CAMERA_IN_USE;
2902 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002903 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002904 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002905 "valid range.", torchStrength);
2906 errorCode = ERROR_ILLEGAL_ARGUMENT;
2907 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002908 default:
Austin Borgered99f642023-06-01 16:51:35 -07002909 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002910 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002911 }
Austin Borgered99f642023-06-01 16:51:35 -07002912 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2913 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002914 }
2915
2916 {
2917 // update the link to client's death
2918 // Store the last client that turns on each camera's torch mode.
2919 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002920 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002922 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002923 } else {
2924 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2925 mTorchClientMap.replaceValueAt(index, clientBinder);
2926 }
2927 clientBinder->linkToDeath(this);
2928 }
2929
2930 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002931 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002932 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002933 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002934 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002935 }
2936 return Status::ok();
2937}
2938
malikakash73125c62023-07-21 22:44:34 +00002939Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002940 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002941 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002942
2943 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002944 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002945 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002946 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2947 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002948 }
2949
Jayant Chowdhary12361932018-08-27 14:46:13 -07002950 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002951 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002952
Austin Borgered99f642023-06-01 16:51:35 -07002953 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002954 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002955 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002956 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002957 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002958 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002959 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002960 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002961 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002962 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002963 }
2964
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002965 StatusInternal cameraStatus = state->getStatus();
2966 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002967 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002968 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2969 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002970 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002971 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002972 }
2973
2974 {
2975 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002976 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002977 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002978 if (err != OK) {
2979 if (err == NAME_NOT_FOUND) {
2980 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002981 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002982 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002983 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002984 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002985 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002986 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002987 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002988 }
2989
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002990 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002991 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002992 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002993 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002994 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2995 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002996 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002997 } else {
2998 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002999 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003000 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3001 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003002 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003003 }
3004 }
3005 }
3006
Ruben Brunk99e69712015-05-26 17:25:07 -07003007 {
3008 // Update UID map - this is used in the torch status changed callbacks, so must be done
3009 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003010 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003011 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003012 }
3013
Austin Borgered99f642023-06-01 16:51:35 -07003014 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003015
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003016 if (err != OK) {
3017 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003018 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019 switch (err) {
3020 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003021 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3022 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003023 errorCode = ERROR_ILLEGAL_ARGUMENT;
3024 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003025 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003026 msg = fmt::sprintf("Camera \"%s\" is in use",
3027 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003028 errorCode = ERROR_CAMERA_IN_USE;
3029 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003030 default:
Austin Borgered99f642023-06-01 16:51:35 -07003031 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003032 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003033 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 errorCode = ERROR_INVALID_OPERATION;
3035 }
Austin Borgered99f642023-06-01 16:51:35 -07003036 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3037 logServiceError(msg, errorCode);
3038 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003039 }
3040
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003041 {
3042 // update the link to client's death
3043 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003044 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003045 if (enabled) {
3046 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003047 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003048 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003049 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003050 mTorchClientMap.replaceValueAt(index, clientBinder);
3051 }
3052 clientBinder->linkToDeath(this);
3053 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003054 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003055 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003056 }
3057
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003058 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003059 std::string torchState = enabled ? "on" : "off";
3060 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3061 torchState.c_str(), clientPid);
3062 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003063 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003064}
3065
Austin Borgered99f642023-06-01 16:51:35 -07003066void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3067 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3068 mTorchUidMap[cameraId].first = uid;
3069 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003070 } else {
3071 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003072 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003073 }
3074}
3075
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003076Status CameraService::notifySystemEvent(int32_t eventId,
3077 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003078 const int pid = CameraThreadState::getCallingPid();
3079 const int selfPid = getpid();
3080
3081 // Permission checks
3082 if (pid != selfPid) {
3083 // Ensure we're being called by system_server, or similar process with
3084 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003085 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003086 const int uid = CameraThreadState::getCallingUid();
3087 ALOGE("Permission Denial: cannot send updates to camera service about system"
3088 " events from pid=%d, uid=%d", pid, uid);
3089 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003090 "No permission to send updates to camera service about system events"
3091 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003092 }
3093 }
3094
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003095 ATRACE_CALL();
3096
Ruben Brunk36597b22015-03-20 22:15:57 -07003097 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003098 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003099 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003100 // from a system server crash
3101 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003102 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003103 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003104 break;
3105 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003106 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3107 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003108 if (args.size() != 1) {
3109 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3110 "USB Device Event requires 1 argument");
3111 }
3112
Valentin Iftime29e2e152021-08-13 15:17:33 +02003113 // Notify CameraProviderManager for lazy HALs
3114 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3115 std::to_string(args[0]));
3116 break;
3117 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003118 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003119 default: {
3120 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3121 eventId);
3122 break;
3123 }
3124 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003125 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003126}
3127
Emilian Peev53722fa2019-02-22 17:47:20 -08003128void CameraService::notifyMonitoredUids() {
3129 Mutex::Autolock lock(mStatusListenerLock);
3130
3131 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003132 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003133 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3134 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003135 }
3136}
3137
Austin Borgerdddb7552023-03-30 17:53:01 -07003138void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3139 Mutex::Autolock lock(mStatusListenerLock);
3140
3141 for (const auto& it : mListenerList) {
3142 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3143 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3144 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3145 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3146 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3147 }
3148 }
3149}
3150
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003151Status CameraService::notifyDeviceStateChange(int64_t newState) {
3152 const int pid = CameraThreadState::getCallingPid();
3153 const int selfPid = getpid();
3154
3155 // Permission checks
3156 if (pid != selfPid) {
3157 // Ensure we're being called by system_server, or similar process with
3158 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003159 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003160 const int uid = CameraThreadState::getCallingUid();
3161 ALOGE("Permission Denial: cannot send updates to camera service about device"
3162 " state changes from pid=%d, uid=%d", pid, uid);
3163 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3164 "No permission to send updates to camera service about device state"
3165 " changes from pid=%d, uid=%d", pid, uid);
3166 }
3167 }
3168
3169 ATRACE_CALL();
3170
Austin Borger18b30a72022-10-27 12:20:29 -07003171 {
3172 Mutex::Autolock lock(mServiceLock);
3173 mDeviceState = newState;
3174 }
3175
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003176 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003177
3178 return Status::ok();
3179}
3180
Emilian Peev8b64f282021-03-25 16:49:57 -07003181Status CameraService::notifyDisplayConfigurationChange() {
3182 ATRACE_CALL();
3183 const int callingPid = CameraThreadState::getCallingPid();
3184 const int selfPid = getpid();
3185
3186 // Permission checks
3187 if (callingPid != selfPid) {
3188 // Ensure we're being called by system_server, or similar process with
3189 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003190 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07003191 const int uid = CameraThreadState::getCallingUid();
3192 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3193 " changes from pid=%d, uid=%d", callingPid, uid);
3194 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3195 "No permission to send updates to camera service about orientation"
3196 " changes from pid=%d, uid=%d", callingPid, uid);
3197 }
3198 }
3199
3200 Mutex::Autolock lock(mServiceLock);
3201
3202 // Don't do anything if rotate-and-crop override via cmd is active
3203 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3204
3205 const auto clients = mActiveClientManager.getAll();
3206 for (auto& current : clients) {
3207 if (current != nullptr) {
3208 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003209 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3210 basicClient->setRotateAndCropOverride(
3211 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3212 basicClient->getPackageName(),
3213 basicClient->getCameraFacing(),
3214 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003215 }
3216 }
3217 }
3218
3219 return Status::ok();
3220}
3221
3222Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003223 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3224 ATRACE_CALL();
3225 if (!concurrentCameraIds) {
3226 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3227 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3228 }
3229
3230 if (!mInitialized) {
3231 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003232 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003233 return STATUS_ERROR(ERROR_DISCONNECTED,
3234 "Camera subsystem is not available");
3235 }
3236 // First call into the provider and get the set of concurrent camera
3237 // combinations
3238 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003239 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003240 for (auto &combination : concurrentCameraCombinations) {
3241 std::vector<std::string> validCombination;
3242 for (auto &cameraId : combination) {
3243 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003244 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003245 if (state == nullptr) {
3246 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3247 continue;
3248 }
3249 StatusInternal status = state->getStatus();
3250 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3251 continue;
3252 }
Austin Borgered99f642023-06-01 16:51:35 -07003253 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003254 continue;
3255 }
3256 validCombination.push_back(cameraId);
3257 }
3258 if (validCombination.size() != 0) {
3259 concurrentCameraIds->push_back(std::move(validCombination));
3260 }
3261 }
3262 return Status::ok();
3263}
3264
3265Status CameraService::isConcurrentSessionConfigurationSupported(
3266 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003267 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003268 if (!isSupported) {
3269 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3270 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3271 }
3272
3273 if (!mInitialized) {
3274 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3275 return STATUS_ERROR(ERROR_DISCONNECTED,
3276 "Camera subsystem is not available");
3277 }
3278
3279 // Check for camera permissions
Austin Borger17e3ebe2024-02-14 15:02:11 -08003280 int callingPid = CameraThreadState::getCallingPid();
3281 int callingUid = CameraThreadState::getCallingUid();
3282 bool hasCameraPermission = ((callingPid == getpid()) ||
3283 hasPermissionsForCamera(callingPid, callingUid));
3284 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003285 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3286 "android.permission.CAMERA needed to call"
3287 "isConcurrentSessionConfigurationSupported");
3288 }
3289
3290 status_t res =
3291 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003292 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3293 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003294 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003295 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003296 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003297 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3298 "support %s (%d)", strerror(-res), res);
3299 }
3300 return Status::ok();
3301}
3302
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003303Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3304 /*out*/
3305 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003306 return addListenerHelper(listener, cameraStatuses);
3307}
3308
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003309binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3310 std::vector<hardware::CameraStatus>* cameraStatuses) {
3311 return addListenerHelper(listener, cameraStatuses, false, true);
3312}
3313
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003314Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3315 /*out*/
3316 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003317 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003318
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003319 ATRACE_CALL();
3320
Igor Murashkinbfc99152013-02-27 12:55:20 -08003321 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003322
Ruben Brunk3450ba72015-06-16 11:00:37 -07003323 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003324 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003325 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003326 }
3327
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003328 auto clientPid = CameraThreadState::getCallingPid();
Austin Borger17e3ebe2024-02-14 15:02:11 -08003329 auto clientUid = CameraThreadState::getCallingUid();
3330 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003331
Igor Murashkinbfc99152013-02-27 12:55:20 -08003332 Mutex::Autolock lock(mServiceLock);
3333
Ruben Brunkcc776712015-02-17 20:18:47 -08003334 {
3335 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003336 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003337 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003338 ALOGW("%s: Tried to add listener %p which was already subscribed",
3339 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003340 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003341 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003342 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003343
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003344 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003345 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3346 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003347 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003348 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003349 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003350 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003351 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3352 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3353 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003354 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003355 // The listener still needs to be added to the list of listeners, regardless of what
3356 // permissions the listener process has / whether it is a vendor listener. Since it might be
3357 // eligible to listen to other camera ids.
3358 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003359 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003360 }
3361
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003362 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003363 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003364 Mutex::Autolock lock(mCameraStatesLock);
3365 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003366 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003367 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003368 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003369 }
3370 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003371 // Remove the camera statuses that should be hidden from the client, we do
3372 // this after collecting the states in order to avoid holding
3373 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3374 // the same time.
3375 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3376 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3377 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3378 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3379 ALOGE("%s: Invalid camera id %s, skipping status update",
3380 __FUNCTION__, s.cameraId.c_str());
3381 return true;
3382 }
3383 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3384 clientUid);}), cameraStatuses->end());
3385
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003386 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003387 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003388 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003389 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003390 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003391
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003392 /*
3393 * Immediately signal current torch status to this listener only
3394 * This may be a subset of all the devices, so don't include it in the response directly
3395 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003396 {
3397 Mutex::Autolock al(mTorchStatusMutex);
3398 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003399 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003400 // The camera id is visible to the client. Fine to send torch
3401 // callback.
3402 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3403 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3404 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003405 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003406 }
3407
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003408 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003409}
Ruben Brunkcc776712015-02-17 20:18:47 -08003410
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003411Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003412 ATRACE_CALL();
3413
Igor Murashkinbfc99152013-02-27 12:55:20 -08003414 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3415
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003416 if (listener == 0) {
3417 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003418 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003419 }
3420
Igor Murashkinbfc99152013-02-27 12:55:20 -08003421 Mutex::Autolock lock(mServiceLock);
3422
Ruben Brunkcc776712015-02-17 20:18:47 -08003423 {
3424 Mutex::Autolock lock(mStatusListenerLock);
3425 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003426 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003427 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003428 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003429 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003430 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003431 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003432 }
3433 }
3434
3435 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3436 __FUNCTION__, listener.get());
3437
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003438 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003439}
3440
Austin Borgered99f642023-06-01 16:51:35 -07003441Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003442
3443 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003444 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3445
3446 if (parameters == NULL) {
3447 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003448 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003449 }
3450
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003451 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003452
3453 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003454 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003455 // Error logged by caller
3456 return ret;
3457 }
3458
3459 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003460
Austin Borgered99f642023-06-01 16:51:35 -07003461 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003462
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003463 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003464}
3465
Austin Borgered99f642023-06-01 16:51:35 -07003466Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003467 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003468 ATRACE_CALL();
3469
malikakashedb38962023-09-06 00:03:35 +00003470 const std::string cameraId = resolveCameraId(
3471 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003472
Austin Borgered99f642023-06-01 16:51:35 -07003473 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003474
3475 switch (apiVersion) {
3476 case API_VERSION_1:
3477 case API_VERSION_2:
3478 break;
3479 default:
Austin Borgered99f642023-06-01 16:51:35 -07003480 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3481 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3482 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003483 }
3484
Austin Borger18b30a72022-10-27 12:20:29 -07003485 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003486 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003487 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003488 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3489 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3490 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003491 }
3492 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3493 int deviceVersion = deviceVersionAndTransport.first;
3494 switch (deviceVersion) {
3495 case CAMERA_DEVICE_API_VERSION_1_0:
3496 case CAMERA_DEVICE_API_VERSION_3_0:
3497 case CAMERA_DEVICE_API_VERSION_3_1:
3498 if (apiVersion == API_VERSION_2) {
3499 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003500 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003501 *isSupported = false;
3502 } else { // if (apiVersion == API_VERSION_1) {
3503 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003504 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003505 *isSupported = true;
3506 }
3507 break;
3508 case CAMERA_DEVICE_API_VERSION_3_2:
3509 case CAMERA_DEVICE_API_VERSION_3_3:
3510 case CAMERA_DEVICE_API_VERSION_3_4:
3511 case CAMERA_DEVICE_API_VERSION_3_5:
3512 case CAMERA_DEVICE_API_VERSION_3_6:
3513 case CAMERA_DEVICE_API_VERSION_3_7:
3514 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003515 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003516 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003517 break;
3518 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003519 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3520 deviceVersion, cameraId.c_str());
3521 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3522 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003523 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003524 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003525 } else {
3526 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003527 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003528 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003529}
3530
Austin Borgered99f642023-06-01 16:51:35 -07003531Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003532 /*out*/ bool *isSupported) {
3533 ATRACE_CALL();
3534
malikakashedb38962023-09-06 00:03:35 +00003535 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3536 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003537
Austin Borgered99f642023-06-01 16:51:35 -07003538 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3539 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003540
3541 return Status::ok();
3542}
3543
Cliff Wud8cae102021-03-11 01:37:42 +08003544Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003545 const std::string& packageName, const std::string& internalCamId,
3546 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003547 const sp<ICameraInjectionCallback>& callback,
3548 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003549 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003550 ATRACE_CALL();
3551
Austin Borgered99f642023-06-01 16:51:35 -07003552 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003553 const int pid = CameraThreadState::getCallingPid();
3554 const int uid = CameraThreadState::getCallingUid();
3555 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3556 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3557 "Permission Denial: no permission to inject camera");
3558 }
3559
3560 ALOGV(
3561 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3562 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003563 __FUNCTION__, packageName.c_str(),
3564 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003565
Cliff Wud3a05312021-04-26 23:07:31 +08003566 {
3567 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003568 mInjectionInternalCamId = internalCamId;
3569 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003570 mInjectionStatusListener->addListener(callback);
3571 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003572 status_t res = NO_ERROR;
3573 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3574 // If the client already exists, we can directly connect to the camera device through the
3575 // client's injectCamera(), otherwise we need to wait until the client is established
3576 // (execute connectHelper()) before injecting the camera to the camera device.
3577 if (clientDescriptor != nullptr) {
3578 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003579 sp<BasicClient> clientSp = clientDescriptor->getValue();
3580 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3581 if(res != OK) {
3582 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3583 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003584 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003585 }
3586 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003587 if(res != OK) {
3588 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3589 }
3590 } else {
3591 mInjectionInitPending = true;
3592 }
3593 }
Cliff Wud8cae102021-03-11 01:37:42 +08003594
Cliff Wud3a05312021-04-26 23:07:31 +08003595 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003596}
3597
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003598Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003599 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003600 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3601 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3602 return Status::ok();
3603}
3604
Ruben Brunkcc776712015-02-17 20:18:47 -08003605void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003606 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003607 for (auto& i : mActiveClientManager.getAll()) {
3608 auto clientSp = i->getValue();
3609 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003610 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003611 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003612 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003613 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003614 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003615}
3616
Ruben Brunkcc776712015-02-17 20:18:47 -08003617bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003618 bool ret = false;
3619 {
3620 // Acquire mServiceLock and prevent other clients from connecting
3621 std::unique_ptr<AutoConditionLock> lock =
3622 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003623
Igor Murashkin634a5152013-02-20 17:15:11 -08003624
Ruben Brunkcc776712015-02-17 20:18:47 -08003625 std::vector<sp<BasicClient>> evicted;
3626 for (auto& i : mActiveClientManager.getAll()) {
3627 auto clientSp = i->getValue();
3628 if (clientSp.get() == nullptr) {
3629 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3630 mActiveClientManager.remove(i);
3631 continue;
3632 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003633 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003634 mActiveClientManager.remove(i);
3635 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003636
Ruben Brunkcc776712015-02-17 20:18:47 -08003637 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003638 clientSp->notifyError(
3639 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003640 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003641 }
3642 }
3643
Ruben Brunkcc776712015-02-17 20:18:47 -08003644 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3645 // other clients from connecting in mServiceLockWrapper if held
3646 mServiceLock.unlock();
3647
Ruben Brunk36597b22015-03-20 22:15:57 -07003648 // Do not clear caller identity, remote caller should be client proccess
3649
Ruben Brunkcc776712015-02-17 20:18:47 -08003650 for (auto& i : evicted) {
3651 if (i.get() != nullptr) {
3652 i->disconnect();
3653 ret = true;
3654 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003655 }
3656
Ruben Brunkcc776712015-02-17 20:18:47 -08003657 // Reacquire mServiceLock
3658 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003659
Ruben Brunkcc776712015-02-17 20:18:47 -08003660 } // lock is destroyed, allow further connect calls
3661
3662 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003663}
3664
Ruben Brunkcc776712015-02-17 20:18:47 -08003665std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003666 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003667 std::shared_ptr<CameraState> state;
3668 {
3669 Mutex::Autolock lock(mCameraStatesLock);
3670 auto iter = mCameraStates.find(cameraId);
3671 if (iter != mCameraStates.end()) {
3672 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003673 }
3674 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003675 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003676}
3677
Austin Borgered99f642023-06-01 16:51:35 -07003678sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003679 // Remove from active clients list
3680 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3681 if (clientDescriptorPtr == nullptr) {
3682 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003683 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003684 return sp<BasicClient>{nullptr};
3685 }
3686
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003687 sp<BasicClient> client = clientDescriptorPtr->getValue();
3688 if (client.get() != nullptr) {
3689 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3690 }
3691 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003692}
3693
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003694void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003695 // Acquire mServiceLock and prevent other clients from connecting
3696 std::unique_ptr<AutoConditionLock> lock =
3697 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3698
Ruben Brunk6267b532015-04-30 17:44:07 -07003699 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003700 for (size_t i = 0; i < newUserIds.size(); i++) {
3701 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003702 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003703 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003704 return;
3705 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003706 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003707 }
3708
Ruben Brunka8ca9152015-04-07 14:23:40 -07003709
Ruben Brunk6267b532015-04-30 17:44:07 -07003710 if (newAllowedUsers == mAllowedUsers) {
3711 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3712 return;
3713 }
3714
3715 logUserSwitch(mAllowedUsers, newAllowedUsers);
3716
3717 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003718
3719 // Current user has switched, evict all current clients.
3720 std::vector<sp<BasicClient>> evicted;
3721 for (auto& i : mActiveClientManager.getAll()) {
3722 auto clientSp = i->getValue();
3723
3724 if (clientSp.get() == nullptr) {
3725 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3726 continue;
3727 }
3728
Ruben Brunk6267b532015-04-30 17:44:07 -07003729 // Don't evict clients that are still allowed.
3730 uid_t clientUid = clientSp->getClientUid();
3731 userid_t clientUserId = multiuser_get_user_id(clientUid);
3732 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3733 continue;
3734 }
3735
Ruben Brunk36597b22015-03-20 22:15:57 -07003736 evicted.push_back(clientSp);
3737
Ruben Brunk36597b22015-03-20 22:15:57 -07003738 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003739 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003740
Ruben Brunk36597b22015-03-20 22:15:57 -07003741 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003742 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003743 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003744 " to user switch.", i->getKey().c_str(),
3745 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003746 i->getOwnerId(), i->getPriority().getScore(),
3747 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003748
3749 }
3750
3751 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3752 // blocking other clients from connecting in mServiceLockWrapper if held.
3753 mServiceLock.unlock();
3754
3755 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003756 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003757
3758 for (auto& i : evicted) {
3759 i->disconnect();
3760 }
3761
Jayant Chowdhary12361932018-08-27 14:46:13 -07003762 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003763
3764 // Reacquire mServiceLock
3765 mServiceLock.lock();
3766}
Ruben Brunkcc776712015-02-17 20:18:47 -08003767
Austin Borgered99f642023-06-01 16:51:35 -07003768void CameraService::logEvent(const std::string &event) {
3769 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003770 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003771 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003772 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003773 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003774 mEventLog.add(msg);
3775 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3776 // Error event not added to the dumpsys log before
3777 mEventLog.add(msg);
3778 sServiceErrorEventSet.insert(msg);
3779 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003780}
3781
Austin Borgered99f642023-06-01 16:51:35 -07003782void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3783 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003785 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3786 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003787}
3788
Austin Borgered99f642023-06-01 16:51:35 -07003789void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3790 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003791 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003792 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3793 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003794}
3795
Austin Borgered99f642023-06-01 16:51:35 -07003796void CameraService::logConnected(const std::string &cameraId, int clientPid,
3797 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003798 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003799 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3800 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003801}
3802
Austin Borgered99f642023-06-01 16:51:35 -07003803void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3804 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003805 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003806 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3807 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003808}
3809
Austin Borgered99f642023-06-01 16:51:35 -07003810void CameraService::logRejected(const std::string &cameraId, int clientPid,
3811 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003812 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003813 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3814 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003815}
3816
Austin Borgered99f642023-06-01 16:51:35 -07003817void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3818 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003819 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003820 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3821 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003822}
3823
Ruben Brunk6267b532015-04-30 17:44:07 -07003824void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3825 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003826 std::string newUsers = toString(newUserIds);
3827 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003828 if (oldUsers.size() == 0) {
3829 oldUsers = "<None>";
3830 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003831 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003832 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3833 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003834}
3835
Austin Borgered99f642023-06-01 16:51:35 -07003836void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003837 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003838 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003839}
3840
Austin Borgered99f642023-06-01 16:51:35 -07003841void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003842 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003843 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003844}
3845
Austin Borgered99f642023-06-01 16:51:35 -07003846void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003847 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003848 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003849}
3850
Austin Borgered99f642023-06-01 16:51:35 -07003851void CameraService::logServiceError(const std::string &msg, int errorCode) {
3852 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3853 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003854}
3855
Ruben Brunk36597b22015-03-20 22:15:57 -07003856status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3857 uint32_t flags) {
3858
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859 // Permission checks
3860 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003861 case SHELL_COMMAND_TRANSACTION: {
3862 int in = data.readFileDescriptor();
3863 int out = data.readFileDescriptor();
3864 int err = data.readFileDescriptor();
3865 int argc = data.readInt32();
3866 Vector<String16> args;
3867 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3868 args.add(data.readString16());
3869 }
3870 sp<IBinder> unusedCallback;
3871 sp<IResultReceiver> resultReceiver;
3872 status_t status;
3873 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3874 return status;
3875 }
3876 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3877 return status;
3878 }
3879 status = shellCommand(in, out, err, args);
3880 if (resultReceiver != nullptr) {
3881 resultReceiver->send(status);
3882 }
3883 return NO_ERROR;
3884 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 }
3886
3887 return BnCameraService::onTransact(code, data, reply, flags);
3888}
3889
Mathias Agopian65ab4712010-07-14 17:59:35 -07003890// We share the media players for shutter and recording sound for all clients.
3891// A reference count is kept to determine when we will actually release the
3892// media players.
3893
Jaekyun Seokef498052018-03-23 13:09:44 +09003894sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3895 sp<MediaPlayer> mp = new MediaPlayer();
3896 status_t error;
3897 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003898 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003899 error = mp->prepare();
3900 }
3901 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003902 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003903 mp->disconnect();
3904 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003905 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 }
3907 return mp;
3908}
3909
username5755fea2018-12-27 09:48:08 +08003910void CameraService::increaseSoundRef() {
3911 Mutex::Autolock lock(mSoundLock);
3912 mSoundRef++;
3913}
3914
3915void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003916 ATRACE_CALL();
3917
username5755fea2018-12-27 09:48:08 +08003918 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3919 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3920 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3921 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3922 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3923 }
3924 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3925 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3926 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3927 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003928 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003929 }
3930 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3931 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3932 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3933 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3934 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003935 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003936}
3937
username5755fea2018-12-27 09:48:08 +08003938void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003940 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003941 if (--mSoundRef) return;
3942
3943 for (int i = 0; i < NUM_SOUNDS; i++) {
3944 if (mSoundPlayer[i] != 0) {
3945 mSoundPlayer[i]->disconnect();
3946 mSoundPlayer[i].clear();
3947 }
3948 }
3949}
3950
3951void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003952 ATRACE_CALL();
3953
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003955 if (kind < 0 || kind >= NUM_SOUNDS) {
3956 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3957 return;
3958 }
3959
Mathias Agopian65ab4712010-07-14 17:59:35 -07003960 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003961 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003962 sp<MediaPlayer> player = mSoundPlayer[kind];
3963 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003964 player->seekTo(0);
3965 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003966 }
3967}
3968
3969// ----------------------------------------------------------------------------
3970
3971CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003972 const sp<ICameraClient>& cameraClient,
Austin Borger17e3ebe2024-02-14 15:02:11 -08003973 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07003974 const std::string& clientPackageName, bool systemNativeClient,
3975 const std::optional<std::string>& clientFeatureId,
3976 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003977 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003978 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003979 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003980 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003981 IInterface::asBinder(cameraClient),
Austin Borger17e3ebe2024-02-14 15:02:11 -08003982 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003983 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003984 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003985 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003986 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003987 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003988{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003989 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003990 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003991
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003992 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003993
username5755fea2018-12-27 09:48:08 +08003994 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003995
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003996 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997}
3998
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999// tear down the client
4000CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004001 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004002 mDestructionStarted = true;
4003
username5755fea2018-12-27 09:48:08 +08004004 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004005 // unconditionally disconnect. function is idempotent
4006 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004007}
4008
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004009sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4010
Igor Murashkin634a5152013-02-20 17:15:11 -08004011CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004012 const sp<IBinder>& remoteCallback,
Austin Borger17e3ebe2024-02-14 15:02:11 -08004013 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004014 const std::string& clientPackageName, bool nativeClient,
4015 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004016 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004017 int servicePid, bool overrideToPortrait):
Austin Borger17e3ebe2024-02-14 15:02:11 -08004018 mAttributionAndPermissionUtils(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004019 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004020 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004021 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4022 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004023 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004024 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004025 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004026 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004027 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004028 mRemoteBinder(remoteCallback),
4029 mOpsActive(false),
4030 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004031{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004032 if (sCameraService == nullptr) {
4033 sCameraService = cameraService;
4034 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004035
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004036 // There are 2 scenarios in which a client won't have AppOps operations
4037 // (both scenarios : native clients)
4038 // 1) It's an system native client*, the package name will be empty
4039 // and it will return from this function in the previous if condition
4040 // (This is the same as the previously existing behavior).
4041 // 2) It is a system native client, but its package name has been
4042 // modified for debugging, however it still must not use AppOps since
4043 // the package name is not a real one.
4044 //
4045 // * system native client - native client with UID < AID_APP_START. It
4046 // doesn't exclude clients not on the system partition.
4047 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004048 mAppOpsManager = std::make_unique<AppOpsManager>();
4049 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004050
Austin Borger17e3ebe2024-02-14 15:02:11 -08004051 mUidIsTrusted = mAttributionAndPermissionUtils->isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004052}
4053
4054CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004055 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004056 mDestructionStarted = true;
4057}
4058
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004059binder::Status CameraService::BasicClient::disconnect() {
4060 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004061 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004062 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004063 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004064 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004065
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004066 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004067 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004068 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004069 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004070
4071 sp<IBinder> remote = getRemote();
4072 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004073 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004074 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004075
4076 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004077 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004078 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004079 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004080 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004081
Igor Murashkincba2c162013-03-20 15:56:31 -07004082 // client shouldn't be able to call into us anymore
4083 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004084
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004085 const auto& mActivityManager = getActivityManager();
4086 if (mActivityManager) {
4087 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
4088 CameraThreadState::getCallingUid(),
4089 CameraThreadState::getCallingPid());
4090 }
4091
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004092 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004093}
4094
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004095status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4096 // No dumping of clients directly over Binder,
4097 // must go through CameraService::dump
4098 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004099 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004100 return OK;
4101}
4102
Austin Borgered99f642023-06-01 16:51:35 -07004103status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004104 // Can't watch tags directly, must go through CameraService::startWatchingTags
4105 return OK;
4106}
4107
4108status_t CameraService::BasicClient::stopWatchingTags(int) {
4109 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4110 return OK;
4111}
4112
4113status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4114 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4115 return OK;
4116}
4117
Austin Borgered99f642023-06-01 16:51:35 -07004118std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004119 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004120}
4121
Emilian Peev8b64f282021-03-25 16:49:57 -07004122int CameraService::BasicClient::getCameraFacing() const {
4123 return mCameraFacing;
4124}
4125
4126int CameraService::BasicClient::getCameraOrientation() const {
4127 return mOrientation;
4128}
Ruben Brunkcc776712015-02-17 20:18:47 -08004129
4130int CameraService::BasicClient::getClientPid() const {
4131 return mClientPid;
4132}
4133
Ruben Brunk6267b532015-04-30 17:44:07 -07004134uid_t CameraService::BasicClient::getClientUid() const {
4135 return mClientUid;
4136}
4137
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004138bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4139 // Defaults to API2.
4140 return level == API_2;
4141}
4142
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004143status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004144 {
4145 Mutex::Autolock l(mAudioRestrictionLock);
4146 mAudioRestriction = mode;
4147 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004148 sCameraService->updateAudioRestriction();
4149 return OK;
4150}
4151
4152int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004153 return sCameraService->updateAudioRestriction();
4154}
4155
4156int32_t CameraService::BasicClient::getAudioRestriction() const {
4157 Mutex::Autolock l(mAudioRestrictionLock);
4158 return mAudioRestriction;
4159}
4160
4161bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4162 switch (mode) {
4163 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4164 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4165 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4166 return true;
4167 default:
4168 return false;
4169 }
4170}
4171
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004172status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4173 if (mode == AppOpsManager::MODE_ERRORED) {
4174 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004175 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004176 return PERMISSION_DENIED;
4177 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4178 // If the calling Uid is trusted (a native service), the AppOpsManager could
4179 // return MODE_IGNORED. Do not treat such case as error.
4180 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4181 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004182
4183 bool isCameraPrivacyEnabled;
4184 if (flags::camera_privacy_allowlist()) {
4185 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4186 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4187 } else {
4188 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004189 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004190 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004191 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4192 // We prefer to successfully open the camera and perform camera muting
4193 // or blocking in connectHelper as handleAppOpMode can be called before the
4194 // connection has been fully established and at that time camera muting
4195 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004196 if (!isUidActive || !isCameraPrivacyEnabled) {
4197 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004198 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004199 // Return the same error as for device policy manager rejection
4200 return -EACCES;
4201 }
4202 }
4203 return OK;
4204}
4205
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004206status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004207 ATRACE_CALL();
4208
Igor Murashkine6800ce2013-03-04 17:25:57 -08004209 {
4210 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004211 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004212 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004213 if (mAppOpsManager != nullptr) {
4214 // Notify app ops that the camera is not available
4215 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004216
4217 if (flags::watch_foreground_changes()) {
4218 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4219 toString16(mClientPackageName),
4220 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4221 } else {
4222 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004223 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004224 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004225
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004226 // Just check for camera acccess here on open - delay startOp until
4227 // camera frames start streaming in startCameraStreamingOps
4228 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004229 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004230 status_t res = handleAppOpMode(mode);
4231 if (res != OK) {
4232 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004233 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004234 }
4235
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004236 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004237
4238 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004239 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004240
Austin Borgerdddb7552023-03-30 17:53:01 -07004241 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004242
Shuzhen Wang695044d2020-03-06 09:02:23 -08004243 // Notify listeners of camera open/close status
4244 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4245
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004246 return OK;
4247}
4248
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004249status_t CameraService::BasicClient::startCameraStreamingOps() {
4250 ATRACE_CALL();
4251
4252 if (!mOpsActive) {
4253 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4254 return INVALID_OPERATION;
4255 }
4256 if (mOpsStreaming) {
4257 ALOGV("%s: Streaming already active!", __FUNCTION__);
4258 return OK;
4259 }
4260
4261 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004262 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004263
4264 if (mAppOpsManager != nullptr) {
4265 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004266 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4267 toString16(mClientFeatureId),
4268 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004269 status_t res = handleAppOpMode(mode);
4270 if (res != OK) {
4271 return res;
4272 }
4273 }
4274
4275 mOpsStreaming = true;
4276
4277 return OK;
4278}
4279
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004280status_t CameraService::BasicClient::noteAppOp() {
4281 ATRACE_CALL();
4282
4283 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004284 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004285
4286 // noteAppOp is only used for when camera mute is not supported, in order
4287 // to trigger the sensor privacy "Unblock" dialog
4288 if (mAppOpsManager != nullptr) {
4289 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004290 toString16(mClientPackageName), toString16(mClientFeatureId),
4291 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004292 status_t res = handleAppOpMode(mode);
4293 if (res != OK) {
4294 return res;
4295 }
4296 }
4297
4298 return OK;
4299}
4300
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004301status_t CameraService::BasicClient::finishCameraStreamingOps() {
4302 ATRACE_CALL();
4303
4304 if (!mOpsActive) {
4305 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4306 return INVALID_OPERATION;
4307 }
4308 if (!mOpsStreaming) {
4309 ALOGV("%s: Streaming not active!", __FUNCTION__);
4310 return OK;
4311 }
4312
4313 if (mAppOpsManager != nullptr) {
4314 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004315 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004316 mOpsStreaming = false;
4317 }
4318
4319 return OK;
4320}
4321
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004322status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004323 ATRACE_CALL();
4324
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004325 if (mOpsStreaming) {
4326 // Make sure we've notified everyone about camera stopping
4327 finishCameraStreamingOps();
4328 }
4329
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004330 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004331 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004332 mOpsActive = false;
4333
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004334 // This function is called when a client disconnects. This should
4335 // release the camera, but actually only if it was in a proper
4336 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004337 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004338 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004339
Ruben Brunkcc776712015-02-17 20:18:47 -08004340 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004341 sCameraService->updateStatus(StatusInternal::PRESENT,
4342 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004343 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004344 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004345 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4346 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004347 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004348 mOpsCallback.clear();
4349
Austin Borgerdddb7552023-03-30 17:53:01 -07004350 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004351
Shuzhen Wang695044d2020-03-06 09:02:23 -08004352 // Notify listeners of camera open/close status
4353 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4354
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004355 return OK;
4356}
4357
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004358void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004359 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004360 if (mAppOpsManager == nullptr) {
4361 return;
4362 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004363 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004364 if (op != AppOpsManager::OP_CAMERA) {
4365 ALOGW("Unexpected app ops notification received: %d", op);
4366 return;
4367 }
4368
4369 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004370 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004371 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004372 ALOGV("checkOp returns: %d, %s ", res,
4373 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4374 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4375 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4376 "UNKNOWN");
4377
Shuzhen Wang64900852021-02-05 09:03:29 -08004378 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004379 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4380 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004381 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004382 } else if (res == AppOpsManager::MODE_IGNORED) {
4383 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004384
Austin Borgerca1e0062023-06-28 11:32:55 -07004385 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4386 // If not visible, but still active, then we want to block instead of muting the camera.
4387 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4388 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4389
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004390 bool isCameraPrivacyEnabled;
4391 if (flags::camera_privacy_allowlist()) {
4392 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4393 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4394 } else {
4395 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004396 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004397 }
4398
4399 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004400 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4401 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4402 isCameraPrivacyEnabled);
4403 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4404 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4405 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004406 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004407 if (flags::watch_foreground_changes()) {
4408 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4409 setCameraMute(true);
4410 } else {
4411 block();
4412 }
4413 } else {
4414 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4415 setCameraMute(true);
4416 } else if (!isUidActive
4417 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4418 block();
4419 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004420 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004421 }
Evan Severson09ab4002021-02-10 14:15:19 -08004422 } else if (res == AppOpsManager::MODE_ALLOWED) {
4423 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004424 }
4425}
4426
Svet Ganova453d0d2018-01-11 15:37:58 -08004427void CameraService::BasicClient::block() {
4428 ATRACE_CALL();
4429
4430 // Reset the client PID to allow server-initiated disconnect,
4431 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004432 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004433 CaptureResultExtras resultExtras; // a dummy result (invalid)
4434 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4435 disconnect();
4436}
4437
Mathias Agopian65ab4712010-07-14 17:59:35 -07004438// ----------------------------------------------------------------------------
4439
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004440void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004441 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004442 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004443 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4444 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4445 api1ErrorCode = CAMERA_ERROR_DISABLED;
4446 }
4447 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004448 } else {
4449 ALOGE("mRemoteCallback is NULL!!");
4450 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004451}
4452
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004453// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004454binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004455 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004456 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004457}
4458
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004459bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4460 return level == API_1;
4461}
4462
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004463CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4464 mClient(client) {
4465}
4466
4467void CameraService::Client::OpsCallback::opChanged(int32_t op,
4468 const String16& packageName) {
4469 sp<BasicClient> client = mClient.promote();
4470 if (client != NULL) {
4471 client->opChanged(op, packageName);
4472 }
4473}
4474
Mathias Agopian65ab4712010-07-14 17:59:35 -07004475// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004476// UidPolicy
4477// ----------------------------------------------------------------------------
4478
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004479void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004480 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004481 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004482
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004483 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004484 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004485 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004486 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004487 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4488 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004489 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004490 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004491 if (res == OK) {
4492 mRegistered = true;
4493 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004494 } else {
4495 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004496 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004497}
4498
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004499void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004500 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004501 return;
4502 }
4503
4504 registerWithActivityManager();
4505}
4506
4507void CameraService::UidPolicy::registerSelf() {
4508 // Use check service to see if the activity service is available
4509 // If not available then register for notifications, instead of blocking
4510 // till the service is ready
4511 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004512 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004513 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004514 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004515 } else {
4516 registerWithActivityManager();
4517 }
4518}
4519
Svet Ganova453d0d2018-01-11 15:37:58 -08004520void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004521 Mutex::Autolock _l(mUidLock);
4522
Steven Moreland2f348142019-07-02 15:59:07 -07004523 mAm.unregisterUidObserver(this);
4524 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004525 mRegistered = false;
4526 mActiveUids.clear();
4527 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004528}
4529
4530void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4531 onUidIdle(uid, disabled);
4532}
4533
4534void CameraService::UidPolicy::onUidActive(uid_t uid) {
4535 Mutex::Autolock _l(mUidLock);
4536 mActiveUids.insert(uid);
4537}
4538
4539void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4540 bool deleted = false;
4541 {
4542 Mutex::Autolock _l(mUidLock);
4543 if (mActiveUids.erase(uid) > 0) {
4544 deleted = true;
4545 }
4546 }
4547 if (deleted) {
4548 sp<CameraService> service = mService.promote();
4549 if (service != nullptr) {
4550 service->blockClientsForUid(uid);
4551 }
4552 }
4553}
4554
Emilian Peev53722fa2019-02-22 17:47:20 -08004555void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004556 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004557 bool procStateChange = false;
4558 {
4559 Mutex::Autolock _l(mUidLock);
4560 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4561 mMonitoredUids[uid].procState != procState) {
4562 mMonitoredUids[uid].procState = procState;
4563 procStateChange = true;
4564 }
4565 }
4566
4567 if (procStateChange) {
4568 sp<CameraService> service = mService.promote();
4569 if (service != nullptr) {
4570 service->notifyMonitoredUids();
4571 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004572 }
4573}
4574
Austin Borgerdddb7552023-03-30 17:53:01 -07004575/**
4576 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4577 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4578 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4579 * monitoredUids. If it is revised above some other monitoredUid, signal
4580 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4581 * foreground apps in split screen - state changes will capture all other cases.
4582 */
4583void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4584 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004585 {
4586 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004587 auto it = mMonitoredUids.find(uid);
4588
4589 if (it != mMonitoredUids.end()) {
4590 if (it->second.hasCamera) {
4591 for (auto &monitoredUid : mMonitoredUids) {
4592 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004593 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004594 notifyUidSet.emplace(monitoredUid.first);
4595 }
4596 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004597 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004598 notifyUidSet.emplace(uid);
4599 } else {
4600 for (auto &monitoredUid : mMonitoredUids) {
4601 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004602 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004603 notifyUidSet.emplace(uid);
4604 }
4605 }
4606 }
4607 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004608 }
4609 }
4610
Austin Borgerdddb7552023-03-30 17:53:01 -07004611 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004612 sp<CameraService> service = mService.promote();
4613 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004614 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004615 }
4616 }
4617}
4618
Austin Borgerdddb7552023-03-30 17:53:01 -07004619/**
4620 * Register a uid for monitoring, and note whether it owns a camera.
4621 */
4622void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004623 Mutex::Autolock _l(mUidLock);
4624 auto it = mMonitoredUids.find(uid);
4625 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004626 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004627 } else {
Austin Borger65577682022-02-17 00:25:43 +00004628 MonitoredUid monitoredUid;
4629 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004630 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004631 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004632 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004633 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004634 if (res != OK) {
4635 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4636 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004637 }
4638
4639 if (openCamera) {
4640 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004641 }
4642}
4643
Austin Borgerdddb7552023-03-30 17:53:01 -07004644/**
4645 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4646 */
4647void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004648 Mutex::Autolock _l(mUidLock);
4649 auto it = mMonitoredUids.find(uid);
4650 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004651 it->second.refCount--;
4652 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004653 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004654 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004655 if (res != OK) {
4656 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4657 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004658 } else if (closeCamera) {
4659 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004660 }
4661 } else {
4662 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4663 }
4664}
4665
Austin Borgered99f642023-06-01 16:51:35 -07004666bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004667 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004668 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004669}
4670
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004671static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4672static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004673
Austin Borgered99f642023-06-01 16:51:35 -07004674bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004675 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004676 // If activity manager is unreachable, assume everything is active
4677 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004678 return true;
4679 }
4680 auto it = mOverrideUids.find(uid);
4681 if (it != mOverrideUids.end()) {
4682 return it->second;
4683 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004684 bool active = mActiveUids.find(uid) != mActiveUids.end();
4685 if (!active) {
4686 // We want active UIDs to always access camera with their first attempt since
4687 // there is no guarantee the app is robustly written and would retry getting
4688 // the camera on failure. The inverse case is not a problem as we would take
4689 // camera away soon once we get the callback that the uid is no longer active.
4690 ActivityManager am;
4691 // Okay to access with a lock held as UID changes are dispatched without
4692 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004693 int64_t startTimeMillis = 0;
4694 do {
4695 // TODO: Fix this b/109950150!
4696 // Okay this is a hack. There is a race between the UID turning active and
4697 // activity being resumed. The proper fix is very risky, so we temporary add
4698 // some polling which should happen pretty rarely anyway as the race is hard
4699 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004700 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004701 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004702 if (active) {
4703 break;
4704 }
4705 if (startTimeMillis <= 0) {
4706 startTimeMillis = uptimeMillis();
4707 }
4708 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004709 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004710 if (remainingTimeMillis <= 0) {
4711 break;
4712 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004713 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4714
4715 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004716 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004717 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004718 } while (true);
4719
Svet Ganov7b4ab782018-03-25 12:48:10 -07004720 if (active) {
4721 // Now that we found out the UID is actually active, cache that
4722 mActiveUids.insert(uid);
4723 }
4724 }
4725 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004726}
4727
Varun Shahb42f1eb2019-04-16 14:45:13 -07004728int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4729 Mutex::Autolock _l(mUidLock);
4730 return getProcStateLocked(uid);
4731}
4732
4733int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4734 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4735 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004736 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004737 }
4738 return procState;
4739}
4740
Austin Borgered99f642023-06-01 16:51:35 -07004741void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4742 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004743 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004744}
4745
Austin Borgered99f642023-06-01 16:51:35 -07004746void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004747 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004748}
4749
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004750void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4751 Mutex::Autolock _l(mUidLock);
4752 ALOGV("UidPolicy: ActivityManager has died");
4753 mRegistered = false;
4754 mActiveUids.clear();
4755}
4756
Austin Borgered99f642023-06-01 16:51:35 -07004757void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004758 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004759 bool wasActive = false;
4760 bool isActive = false;
4761 {
4762 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004763 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004764 mOverrideUids.erase(uid);
4765 if (insert) {
4766 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4767 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004768 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004769 }
4770 if (wasActive != isActive && !isActive) {
4771 sp<CameraService> service = mService.promote();
4772 if (service != nullptr) {
4773 service->blockClientsForUid(uid);
4774 }
4775 }
4776}
4777
4778// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004779// SensorPrivacyPolicy
4780// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004781
4782void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4783{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004784 Mutex::Autolock _l(mSensorPrivacyLock);
4785 if (mRegistered) {
4786 return;
4787 }
Evan Severson09ab4002021-02-10 14:15:19 -08004788 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004789 mSpm.addSensorPrivacyListener(this);
Austin Borger17e3ebe2024-02-14 15:02:11 -08004790 if (mAttributionAndPermissionUtils->isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004791 mSpm.addToggleSensorPrivacyListener(this);
4792 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004793 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004794 if (flags::camera_privacy_allowlist()) {
4795 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4796 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4797 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4798 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004799 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004800 if (res == OK) {
4801 mRegistered = true;
4802 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4803 }
4804}
4805
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004806void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4807 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004808 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004809 return;
4810 }
4811
4812 registerWithSensorPrivacyManager();
4813}
4814
4815void CameraService::SensorPrivacyPolicy::registerSelf() {
4816 // Use checkservice to see if the sensor_privacy service is available
4817 // If service is not available then register for notification
4818 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004819 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004820 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004821 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004822 } else {
4823 registerWithSensorPrivacyManager();
4824 }
4825}
4826
Michael Grooverd1d435a2018-12-18 17:39:42 -08004827void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4828 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004829 mSpm.removeSensorPrivacyListener(this);
Austin Borger17e3ebe2024-02-14 15:02:11 -08004830 if (mAttributionAndPermissionUtils->isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004831 mSpm.removeToggleSensorPrivacyListener(this);
4832 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004833 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004834 mRegistered = false;
4835 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4836}
4837
4838bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004839 if (!mRegistered) {
4840 registerWithSensorPrivacyManager();
4841 }
4842
Michael Grooverd1d435a2018-12-18 17:39:42 -08004843 Mutex::Autolock _l(mSensorPrivacyLock);
4844 return mSensorPrivacyEnabled;
4845}
4846
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004847int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4848 if (!mRegistered) {
4849 registerWithSensorPrivacyManager();
4850 }
4851
4852 Mutex::Autolock _l(mSensorPrivacyLock);
4853 return mCameraPrivacyState;
4854}
4855
Evan Seversond0b69922022-01-27 10:47:34 -08004856bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004857 if (!hasCameraPrivacyFeature()) {
4858 return false;
4859 }
Evan Seversond0b69922022-01-27 10:47:34 -08004860 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004861}
4862
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004863bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4864 if (!hasCameraPrivacyFeature()) {
4865 return SensorPrivacyManager::DISABLED;
4866 }
4867 return mSpm.isCameraPrivacyEnabled(packageName);
4868}
4869
Evan Seversond0b69922022-01-27 10:47:34 -08004870binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004871 int toggleType, int sensor, bool enabled) {
4872 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4873 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4874 {
4875 Mutex::Autolock _l(mSensorPrivacyLock);
4876 mSensorPrivacyEnabled = enabled;
4877 }
4878 // if sensor privacy is enabled then block all clients from accessing the camera
4879 if (enabled) {
4880 sp<CameraService> service = mService.promote();
4881 if (service != nullptr) {
4882 service->blockAllClients();
4883 }
4884 }
4885 }
4886 return binder::Status::ok();
4887}
4888
4889binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4890 int, int sensor, int state) {
4891 if (!flags::camera_privacy_allowlist()
4892 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4893 return binder::Status::ok();
4894 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004895 {
4896 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004897 mCameraPrivacyState = state;
4898 }
4899 sp<CameraService> service = mService.promote();
4900 if (!service) {
4901 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004902 }
4903 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004904 if (state == SensorPrivacyManager::ENABLED) {
4905 service->blockAllClients();
4906 } else if ((state == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_APPS)
4907 || (state == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_HELPFUL_APPS)
4908 || (state == SensorPrivacyManager::AUTOMOTIVE_DRIVER_ASSISTANCE_REQUIRED_APPS)) {
4909 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004910 }
4911 return binder::Status::ok();
4912}
4913
4914void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4915 Mutex::Autolock _l(mSensorPrivacyLock);
4916 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4917 mRegistered = false;
4918}
4919
Evan Severson09ab4002021-02-10 14:15:19 -08004920bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004921 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4922 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4923 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4924 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4925 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004926}
4927
Michael Grooverd1d435a2018-12-18 17:39:42 -08004928// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004929// CameraState
4930// ----------------------------------------------------------------------------
4931
Austin Borgered99f642023-06-01 16:51:35 -07004932CameraService::CameraState::CameraState(const std::string& id, int cost,
4933 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004934 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004935 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004936 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004937
4938CameraService::CameraState::~CameraState() {}
4939
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004940CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004941 Mutex::Autolock lock(mStatusLock);
4942 return mStatus;
4943}
4944
Austin Borgered99f642023-06-01 16:51:35 -07004945std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004946 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004947 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004948 return res;
4949}
4950
Ruben Brunkcc776712015-02-17 20:18:47 -08004951CameraParameters CameraService::CameraState::getShimParams() const {
4952 return mShimParams;
4953}
4954
4955void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4956 mShimParams = params;
4957}
4958
4959int CameraService::CameraState::getCost() const {
4960 return mCost;
4961}
4962
Austin Borgered99f642023-06-01 16:51:35 -07004963std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004964 return mConflicting;
4965}
4966
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004967SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4968 return mSystemCameraKind;
4969}
4970
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004971bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4972 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4973 != mPhysicalCameras.end();
4974}
4975
Austin Borgered99f642023-06-01 16:51:35 -07004976bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004977 Mutex::Autolock lock(mStatusLock);
4978 auto result = mUnavailablePhysicalIds.insert(physicalId);
4979 return result.second;
4980}
4981
Austin Borgered99f642023-06-01 16:51:35 -07004982bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004983 Mutex::Autolock lock(mStatusLock);
4984 auto count = mUnavailablePhysicalIds.erase(physicalId);
4985 return count > 0;
4986}
4987
Austin Borgered99f642023-06-01 16:51:35 -07004988void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004989 Mutex::Autolock lock(mStatusLock);
4990 mClientPackage = clientPackage;
4991}
4992
Austin Borgered99f642023-06-01 16:51:35 -07004993std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004994 Mutex::Autolock lock(mStatusLock);
4995 return mClientPackage;
4996}
4997
Ruben Brunkcc776712015-02-17 20:18:47 -08004998// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004999// ClientEventListener
5000// ----------------------------------------------------------------------------
5001
5002void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005003 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005004 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005005 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005006 if (basicClient.get() != nullptr) {
5007 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005008 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005009 static_cast<int>(basicClient->getClientUid()));
5010 }
5011}
5012
5013void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005014 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005015 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005016 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005017 if (basicClient.get() != nullptr) {
5018 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005019 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005020 static_cast<int>(basicClient->getClientUid()));
5021 }
5022}
5023
5024
5025// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005026// CameraClientManager
5027// ----------------------------------------------------------------------------
5028
Ruben Brunk99e69712015-05-26 17:25:07 -07005029CameraService::CameraClientManager::CameraClientManager() {
5030 setListener(std::make_shared<ClientEventListener>());
5031}
5032
Ruben Brunkcc776712015-02-17 20:18:47 -08005033CameraService::CameraClientManager::~CameraClientManager() {}
5034
5035sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005036 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005037 auto descriptor = get(id);
5038 if (descriptor == nullptr) {
5039 return sp<BasicClient>{nullptr};
5040 }
5041 return descriptor->getValue();
5042}
5043
Austin Borgered99f642023-06-01 16:51:35 -07005044std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005045 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005046 std::ostringstream ret;
5047 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005048 bool hasAny = false;
5049 for (auto& i : all) {
5050 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005051 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005052 int32_t cost = i->getCost();
5053 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005054 int32_t score = i->getPriority().getScore();
5055 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005056 auto conflicting = i->getConflicting();
5057 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005058 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005059 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005060 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005061 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005062 uid_t clientUid = clientSp->getClientUid();
5063 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005064 }
Austin Borgered99f642023-06-01 16:51:35 -07005065 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5066 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005067
Ruben Brunk6267b532015-04-30 17:44:07 -07005068 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005069 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005070 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005071 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005072 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005073 }
5074
Austin Borgered99f642023-06-01 16:51:35 -07005075 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005076 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005077 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005078 }
Austin Borgered99f642023-06-01 16:51:35 -07005079 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005080 }
Austin Borgered99f642023-06-01 16:51:35 -07005081 if (hasAny) ret << "\n";
5082 ret << "]\n";
5083 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005084}
5085
5086CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005087 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5088 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005089 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005090
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005091 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005092 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005093
Austin Borgered99f642023-06-01 16:51:35 -07005094 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005095 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5096 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005097}
5098
5099CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005100 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005101 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005102 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005103 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005104 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5105 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005106}
5107
5108// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005109// InjectionStatusListener
5110// ----------------------------------------------------------------------------
5111
5112void CameraService::InjectionStatusListener::addListener(
5113 const sp<ICameraInjectionCallback>& callback) {
5114 Mutex::Autolock lock(mListenerLock);
5115 if (mCameraInjectionCallback) return;
5116 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5117 if (res == OK) {
5118 mCameraInjectionCallback = callback;
5119 }
5120}
5121
5122void CameraService::InjectionStatusListener::removeListener() {
5123 Mutex::Autolock lock(mListenerLock);
5124 if (mCameraInjectionCallback == nullptr) {
5125 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5126 return;
5127 }
5128 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5129 mCameraInjectionCallback = nullptr;
5130}
5131
5132void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005133 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005134 if (mCameraInjectionCallback == nullptr) {
5135 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5136 return;
5137 }
Cliff Wud3a05312021-04-26 23:07:31 +08005138
5139 switch (err) {
5140 case -ENODEV:
5141 mCameraInjectionCallback->onInjectionError(
5142 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5143 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005144 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005145 break;
5146 case -EBUSY:
5147 mCameraInjectionCallback->onInjectionError(
5148 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5149 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005150 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005151 break;
5152 case DEAD_OBJECT:
5153 mCameraInjectionCallback->onInjectionError(
5154 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5155 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005156 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005157 break;
5158 case INVALID_OPERATION:
5159 mCameraInjectionCallback->onInjectionError(
5160 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5161 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005162 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005163 break;
5164 case UNKNOWN_TRANSACTION:
5165 mCameraInjectionCallback->onInjectionError(
5166 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5167 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005168 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005169 break;
5170 default:
5171 mCameraInjectionCallback->onInjectionError(
5172 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5173 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005174 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005175 }
Cliff Wud8cae102021-03-11 01:37:42 +08005176}
5177
5178void CameraService::InjectionStatusListener::binderDied(
5179 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005180 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5181 auto parent = mParent.promote();
5182 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005183 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5184 if (clientDescriptor != nullptr) {
5185 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5186 baseClientPtr->stopInjection();
5187 }
Cliff Wu3b268182021-07-06 15:44:43 +08005188 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005189 }
5190}
5191
5192// ----------------------------------------------------------------------------
5193// CameraInjectionSession
5194// ----------------------------------------------------------------------------
5195
5196binder::Status CameraService::CameraInjectionSession::stopInjection() {
5197 Mutex::Autolock lock(mInjectionSessionLock);
5198 auto parent = mParent.promote();
5199 if (parent == nullptr) {
5200 ALOGE("CameraInjectionSession: Parent is gone");
5201 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5202 "Camera service encountered error");
5203 }
Cliff Wud3a05312021-04-26 23:07:31 +08005204
5205 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005206 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5207 if (clientDescriptor != nullptr) {
5208 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5209 res = baseClientPtr->stopInjection();
5210 if (res != OK) {
5211 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5212 " ret != NO_ERROR: %d", res);
5213 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5214 "Camera session encountered error");
5215 }
5216 }
Cliff Wu3b268182021-07-06 15:44:43 +08005217 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005218 return binder::Status::ok();
5219}
5220
5221// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005222
5223static const int kDumpLockRetries = 50;
5224static const int kDumpLockSleep = 60000;
5225
5226static bool tryLock(Mutex& mutex)
5227{
5228 bool locked = false;
5229 for (int i = 0; i < kDumpLockRetries; ++i) {
5230 if (mutex.tryLock() == NO_ERROR) {
5231 locked = true;
5232 break;
5233 }
5234 usleep(kDumpLockSleep);
5235 }
5236 return locked;
5237}
5238
Rucha Katakwardf223072021-06-15 10:21:00 -07005239void CameraService::cacheDump() {
5240 if (mMemFd != -1) {
5241 const Vector<String16> args;
5242 ATRACE_CALL();
5243 // Acquiring service lock here will avoid the deadlock since
5244 // cacheDump will not be called during the second disconnect.
5245 Mutex::Autolock lock(mServiceLock);
5246
5247 Mutex::Autolock l(mCameraStatesLock);
5248 // Start collecting the info for open sessions and store it in temp file.
5249 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005250 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005251 auto clientDescriptor = mActiveClientManager.get(cameraId);
5252 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005253 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005254 // Log the current open session info before device is disconnected.
5255 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5256 }
5257 }
5258 }
5259}
5260
Mathias Agopian65ab4712010-07-14 17:59:35 -07005261status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005262 ATRACE_CALL();
5263
Austin Borgered99f642023-06-01 16:51:35 -07005264 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005265 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07005266 CameraThreadState::getCallingPid(),
5267 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005268 return NO_ERROR;
5269 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005270 bool locked = tryLock(mServiceLock);
5271 // failed to lock - CameraService is probably deadlocked
5272 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005273 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005274 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005275
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005276 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005277 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005278
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005279 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005280 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005281
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005282 if (locked) mServiceLock.unlock();
5283 return NO_ERROR;
5284 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005285 dprintf(fd, "\n== Service global info: ==\n\n");
5286 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005287 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005288 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5289 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005290 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5291 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5292 }
Austin Borgered99f642023-06-01 16:51:35 -07005293 std::string activeClientString = mActiveClientManager.toString();
5294 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5295 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005296 if (mStreamUseCaseOverrides.size() > 0) {
5297 dprintf(fd, "Active stream use case overrides:");
5298 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5299 dprintf(fd, " %" PRId64, useCaseOverride);
5300 }
5301 dprintf(fd, "\n");
5302 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005303
5304 dumpEventLog(fd);
5305
5306 bool stateLocked = tryLock(mCameraStatesLock);
5307 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005308 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005309 }
5310
Emilian Peevbd8c5032018-02-14 23:05:40 +00005311 int argSize = args.size();
5312 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005313 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005314 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005315 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005316 }
5317 break;
5318 }
5319 }
5320
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005321 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005322 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005323
Austin Borgered99f642023-06-01 16:51:35 -07005324 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005325
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005326 CameraParameters p = state.second->getShimParams();
5327 if (!p.isEmpty()) {
5328 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5329 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005330 }
5331
5332 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005333 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005334 // log the current open session info
5335 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005336 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005337 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005338 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005339
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005340 }
5341
5342 if (stateLocked) mCameraStatesLock.unlock();
5343
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005344 if (locked) mServiceLock.unlock();
5345
Emilian Peevf53f66e2017-04-11 14:29:43 +01005346 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005347
5348 dprintf(fd, "\n== Vendor tags: ==\n\n");
5349
5350 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5351 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005352 sp<VendorTagDescriptorCache> cache =
5353 VendorTagDescriptorCache::getGlobalVendorTagCache();
5354 if (cache == NULL) {
5355 dprintf(fd, "No vendor tags.\n");
5356 } else {
5357 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5358 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005359 } else {
5360 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5361 }
5362
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005363 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005364 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005365 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005366
5367 // Process dump arguments, if any
5368 int n = args.size();
5369 String16 verboseOption("-v");
5370 String16 unreachableOption("--unreachable");
5371 for (int i = 0; i < n; i++) {
5372 if (args[i] == verboseOption) {
5373 // change logging level
5374 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005375 std::string levelStr = toStdString(args[i+1]);
5376 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005377 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005378 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005379 } else if (args[i] == unreachableOption) {
5380 // Dump memory analysis
5381 // TODO - should limit be an argument parameter?
5382 UnreachableMemoryInfo info;
5383 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5384 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005385 dprintf(fd, "\n== Unable to dump unreachable memory. "
5386 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005387 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005388 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005389 std::string s = info.ToString(/*log_contents*/ true);
5390 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005391 }
5392 }
5393 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005394
5395 bool serviceLocked = tryLock(mServiceLock);
5396
5397 // Dump info from previous open sessions.
5398 // Reposition the offset to beginning of the file before reading
5399
5400 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5401 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5402 ssize_t size_read;
5403 char buf[4096];
5404 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5405 // Read data from file to a small buffer and write it to fd.
5406 write(fd, buf, size_read);
5407 if (size_read == -1) {
5408 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5409 break;
5410 }
5411 }
5412 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5413 } else {
5414 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5415 }
5416
5417 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005418 return NO_ERROR;
5419}
5420
Rucha Katakwardf223072021-06-15 10:21:00 -07005421void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005422 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005423 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005424 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005425 getFormattedCurrentTime().c_str(),
5426 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005427 dprintf(fd, " Client priority score: %d state: %d\n",
5428 clientDescriptor->getPriority().getScore(),
5429 clientDescriptor->getPriority().getState());
5430 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5431
5432 auto client = clientDescriptor->getValue();
5433 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005434 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005435
5436 client->dumpClient(fd, args);
5437}
5438
Austin Borgered99f642023-06-01 16:51:35 -07005439void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005440 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005441 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005442}
5443
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005444void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005445 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005446
5447 Mutex::Autolock l(mLogLock);
5448 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005449 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005450 }
5451
5452 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005453 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005454 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005455 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005456 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005457 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005458}
5459
Austin Borgered99f642023-06-01 16:51:35 -07005460void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005461 Mutex::Autolock lock(mLogLock);
5462 if (!isClientWatchedLocked(client)) { return; }
5463
5464 std::vector<std::string> dumpVector;
5465 client->dumpWatchedEventsToVector(dumpVector);
5466
5467 if (dumpVector.empty()) { return; }
5468
Austin Borgered99f642023-06-01 16:51:35 -07005469 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005470
Austin Borgered99f642023-06-01 16:51:35 -07005471 std::string currentTime = getFormattedCurrentTime();
5472 dumpString << "Cached @ ";
5473 dumpString << currentTime;
5474 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005475
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005476 size_t i = dumpVector.size();
5477
5478 // Store the string in reverse order (latest last)
5479 while (i > 0) {
5480 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005481 dumpString << cameraId;
5482 dumpString << ":";
5483 dumpString << client->getPackageName();
5484 dumpString << " ";
5485 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005486 }
5487
Austin Borgered99f642023-06-01 16:51:35 -07005488 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005489}
5490
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005491void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005492 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005493 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5494 if (mTorchClientMap[i] == who) {
5495 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005496 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005497 status_t res = mFlashlight->setTorchMode(cameraId, false);
5498 if (res) {
5499 ALOGE("%s: torch client died but couldn't turn off torch: "
5500 "%s (%d)", __FUNCTION__, strerror(-res), res);
5501 return;
5502 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005503 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005504 break;
5505 }
5506 }
5507}
5508
Ruben Brunkcc776712015-02-17 20:18:47 -08005509/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005510
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005511 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005512 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5513 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005514 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005515 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005516 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005517
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005518 // check torch client
5519 handleTorchClientBinderDied(who);
5520
5521 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005522 if(!evictClientIdByRemote(who)) {
5523 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005524 return;
5525 }
5526
Ruben Brunkcc776712015-02-17 20:18:47 -08005527 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5528 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005529}
5530
Austin Borgered99f642023-06-01 16:51:35 -07005531void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005532 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005533}
5534
Austin Borgered99f642023-06-01 16:51:35 -07005535void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005536 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005537 // Do not lock mServiceLock here or can get into a deadlock from
5538 // connect() -> disconnect -> updateStatus
5539
5540 auto state = getCameraState(cameraId);
5541
5542 if (state == nullptr) {
5543 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005544 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005545 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005546 }
5547
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005548 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5549 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5550 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005551 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005552 return;
5553 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005554
5555 // Collect the logical cameras without holding mStatusLock in updateStatus
5556 // as that can lead to a deadlock(b/162192331).
5557 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005558 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005559 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005560 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005561 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005562 (const std::string& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005563
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005564 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005565 // Update torch status if it has a flash unit.
5566 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005567 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005568 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5569 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005570 TorchModeStatus newTorchStatus =
5571 status == StatusInternal::PRESENT ?
5572 TorchModeStatus::AVAILABLE_OFF :
5573 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005574 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005575 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005576 }
5577 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005578 }
5579
5580 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005581 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005582 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005583
Ruben Brunkcc776712015-02-17 20:18:47 -08005584 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005585 bool isVendorListener = listener->isVendorListener();
5586 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
Kwangkyu Park01f84432023-09-15 17:08:17 +09005587 listener->getListenerPid(), listener->getListenerUid())) {
Shuzhen Wangb8259792021-05-27 09:27:06 -07005588 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005589 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005590 continue;
5591 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005592 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005593 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005594 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005595 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005596 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5597 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005598 // Also trigger the callbacks for cameras that were remapped to the current
5599 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005600 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005601 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5602 for (auto& remappedCameraId : remappedCameraIds) {
5603 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005604 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005605 listener->handleBinderStatus(ret,
5606 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5607 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5608 ret.exceptionCode());
5609 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005610 }
5611 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005612}
5613
Austin Borgered99f642023-06-01 16:51:35 -07005614void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5615 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005616 auto state = getCameraState(cameraId);
5617 if (state == nullptr) {
5618 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005619 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005620 return;
5621 }
5622 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005623 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005624 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005625 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005626 }
5627
Shuzhen Wang695044d2020-03-06 09:02:23 -08005628 Mutex::Autolock lock(mStatusListenerLock);
5629
5630 for (const auto& it : mListenerList) {
5631 if (!it->isOpenCloseCallbackAllowed()) {
5632 continue;
5633 }
5634
5635 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005636 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005637 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005638 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005639 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005640 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005641
5642 it->handleBinderStatus(ret,
5643 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5644 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005645 }
5646}
5647
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005648template<class Func>
5649void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005650 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005651 std::initializer_list<StatusInternal> rejectSourceStates,
5652 Func onStatusUpdatedLocked) {
5653 Mutex::Autolock lock(mStatusLock);
5654 StatusInternal oldStatus = mStatus;
5655 mStatus = status;
5656
5657 if (oldStatus == status) {
5658 return;
5659 }
5660
5661 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005662 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005663
5664 if (oldStatus == StatusInternal::NOT_PRESENT &&
5665 (status != StatusInternal::PRESENT &&
5666 status != StatusInternal::ENUMERATING)) {
5667
5668 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5669 __FUNCTION__);
5670 mStatus = oldStatus;
5671 return;
5672 }
5673
5674 /**
5675 * Sometimes we want to conditionally do a transition.
5676 * For example if a client disconnects, we want to go to PRESENT
5677 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5678 */
5679 for (auto& rejectStatus : rejectSourceStates) {
5680 if (oldStatus == rejectStatus) {
5681 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005682 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005683 mStatus = oldStatus;
5684 return;
5685 }
5686 }
5687
5688 onStatusUpdatedLocked(cameraId, status);
5689}
5690
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005691status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005692 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005693 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005694 if (!status) {
5695 return BAD_VALUE;
5696 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005697 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5698 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005699 // invalid camera ID or the camera doesn't have a flash unit
5700 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005701 }
5702
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005703 *status = mTorchStatusMap.valueAt(index);
5704 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005705}
5706
Austin Borgered99f642023-06-01 16:51:35 -07005707status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005708 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005709 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5710 if (index == NAME_NOT_FOUND) {
5711 return BAD_VALUE;
5712 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005713 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005714
5715 return OK;
5716}
5717
Austin Borgered99f642023-06-01 16:51:35 -07005718std::list<std::string> CameraService::getLogicalCameras(
5719 const std::string& physicalCameraId) {
5720 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005721 Mutex::Autolock lock(mCameraStatesLock);
5722 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005723 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5724 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005725 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005726 }
5727 return retList;
5728}
5729
5730void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005731 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005732 SystemCameraKind deviceKind) {
5733 // mStatusListenerLock is expected to be locked
5734 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005735 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005736 // Note: we check only the deviceKind of the physical camera id
5737 // since, logical camera ids and their physical camera ids are
5738 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005739 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5740 listener->getListenerPid(), listener->getListenerUid())) {
5741 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005742 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005743 continue;
5744 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005745 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005746 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005747 listener->handleBinderStatus(ret,
5748 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5749 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5750 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005751 }
5752 }
5753}
5754
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005755
Svet Ganova453d0d2018-01-11 15:37:58 -08005756void CameraService::blockClientsForUid(uid_t uid) {
5757 const auto clients = mActiveClientManager.getAll();
5758 for (auto& current : clients) {
5759 if (current != nullptr) {
5760 const auto basicClient = current->getValue();
5761 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5762 basicClient->block();
5763 }
5764 }
5765 }
5766}
5767
Michael Grooverd1d435a2018-12-18 17:39:42 -08005768void CameraService::blockAllClients() {
5769 const auto clients = mActiveClientManager.getAll();
5770 for (auto& current : clients) {
5771 if (current != nullptr) {
5772 const auto basicClient = current->getValue();
5773 if (basicClient.get() != nullptr) {
5774 basicClient->block();
5775 }
5776 }
5777 }
5778}
5779
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005780void CameraService::blockPrivacyEnabledClients() {
5781 const auto clients = mActiveClientManager.getAll();
5782 for (auto& current : clients) {
5783 if (current != nullptr) {
5784 const auto basicClient = current->getValue();
5785 if (basicClient.get() != nullptr) {
5786 std::string pkgName = basicClient->getPackageName();
5787 bool cameraPrivacyEnabled =
5788 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5789 if (cameraPrivacyEnabled) {
5790 basicClient->block();
5791 }
5792 }
5793 }
5794 }
5795}
5796
Svet Ganova453d0d2018-01-11 15:37:58 -08005797// NOTE: This is a remote API - make sure all args are validated
5798status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005799 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005800 return PERMISSION_DENIED;
5801 }
5802 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5803 return BAD_VALUE;
5804 }
Austin Borgered99f642023-06-01 16:51:35 -07005805 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005806 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005807 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005808 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005809 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005810 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005811 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005812 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005813 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005814 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005815 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005816 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005817 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005818 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005819 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005820 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005821 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005822 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005823 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005824 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005825 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005826 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005827 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005828 handleClearStreamUseCaseOverrides();
5829 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005830 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005831 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005832 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005833 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005834 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005835 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005836 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005837 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005838 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005839 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005840 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005841 }
5842 printHelp(err);
5843 return BAD_VALUE;
5844}
5845
malikakash82ed4352023-07-21 22:44:34 +00005846status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5847 uid_t uid = IPCThreadState::self()->getCallingUid();
5848 if (uid != AID_ROOT) {
5849 dprintf(err, "Must be adb root\n");
5850 return PERMISSION_DENIED;
5851 }
5852 if (args.size() != 4) {
5853 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5854 return BAD_VALUE;
5855 }
Austin Borgered99f642023-06-01 16:51:35 -07005856 std::string packageName = toStdString(args[1]);
5857 std::string cameraIdToReplace = toStdString(args[2]);
5858 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005859 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5860 return OK;
5861}
5862
Svet Ganova453d0d2018-01-11 15:37:58 -08005863status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005864 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005865
Svet Ganova453d0d2018-01-11 15:37:58 -08005866 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005867 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005868 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005869 } else if ((args[2] != toString16("idle"))) {
5870 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005871 return BAD_VALUE;
5872 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005873
5874 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005875 if (args.size() >= 5 && args[3] == toString16("--user")) {
5876 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005877 }
5878
5879 uid_t uid;
5880 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5881 return BAD_VALUE;
5882 }
5883
5884 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005885 return NO_ERROR;
5886}
5887
5888status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005889 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005890
5891 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005892 if (args.size() >= 4 && args[2] == toString16("--user")) {
5893 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005894 }
5895
5896 uid_t uid;
5897 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005898 return BAD_VALUE;
5899 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005900
5901 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005902 return NO_ERROR;
5903}
5904
5905status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005906 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005907
5908 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005909 if (args.size() >= 4 && args[2] == toString16("--user")) {
5910 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005911 }
5912
5913 uid_t uid;
5914 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005915 return BAD_VALUE;
5916 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005917
5918 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005919 return dprintf(out, "active\n");
5920 } else {
5921 return dprintf(out, "idle\n");
5922 }
5923}
5924
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005925status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005926 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005927 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5928 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5929 Mutex::Autolock lock(mServiceLock);
5930
5931 mOverrideRotateAndCropMode = rotateValue;
5932
5933 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5934
5935 const auto clients = mActiveClientManager.getAll();
5936 for (auto& current : clients) {
5937 if (current != nullptr) {
5938 const auto basicClient = current->getValue();
5939 if (basicClient.get() != nullptr) {
5940 basicClient->setRotateAndCropOverride(rotateValue);
5941 }
5942 }
5943 }
5944
5945 return OK;
5946}
5947
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005948status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5949 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005950 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005951 if ((*end != '\0') ||
5952 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5953 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5954 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5955 return BAD_VALUE;
5956 }
5957
5958 Mutex::Autolock lock(mServiceLock);
5959 mOverrideAutoframingMode = autoframingValue;
5960
5961 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5962
5963 const auto clients = mActiveClientManager.getAll();
5964 for (auto& current : clients) {
5965 if (current != nullptr) {
5966 const auto basicClient = current->getValue();
5967 if (basicClient.get() != nullptr) {
5968 basicClient->setAutoframingOverride(autoframingValue);
5969 }
5970 }
5971 }
5972
5973 return OK;
5974}
5975
Ravneetaeb20dc2022-03-30 05:33:03 +00005976status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005977 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005978
5979 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5980
5981 Mutex::Autolock lock(mServiceLock);
5982
5983 mCameraServiceWatchdogEnabled = enableWatchdog;
5984
5985 const auto clients = mActiveClientManager.getAll();
5986 for (auto& current : clients) {
5987 if (current != nullptr) {
5988 const auto basicClient = current->getValue();
5989 if (basicClient.get() != nullptr) {
5990 basicClient->setCameraServiceWatchdog(enableWatchdog);
5991 }
5992 }
5993 }
5994
5995 return OK;
5996}
5997
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005998status_t CameraService::handleGetRotateAndCrop(int out) {
5999 Mutex::Autolock lock(mServiceLock);
6000
6001 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6002}
6003
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006004status_t CameraService::handleGetAutoframing(int out) {
6005 Mutex::Autolock lock(mServiceLock);
6006
6007 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6008}
6009
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006010status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6011 char *endPtr;
6012 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006013 std::string maskString = toStdString(args[1]);
6014 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006015
6016 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006017 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006018 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6019
6020 Mutex::Autolock lock(mServiceLock);
6021
6022 mImageDumpMask = maskValue;
6023
6024 return OK;
6025}
6026
6027status_t CameraService::handleGetImageDumpMask(int out) {
6028 Mutex::Autolock lock(mServiceLock);
6029
6030 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6031}
6032
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006033status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006034 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006035 if (errno != 0) return BAD_VALUE;
6036
6037 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6038 Mutex::Autolock lock(mServiceLock);
6039
6040 mOverrideCameraMuteMode = (muteValue == 1);
6041
6042 const auto clients = mActiveClientManager.getAll();
6043 for (auto& current : clients) {
6044 if (current != nullptr) {
6045 const auto basicClient = current->getValue();
6046 if (basicClient.get() != nullptr) {
6047 if (basicClient->supportsCameraMute()) {
6048 basicClient->setCameraMute(mOverrideCameraMuteMode);
6049 }
6050 }
6051 }
6052 }
6053
6054 return OK;
6055}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006056
Shuzhen Wang16610a62022-12-15 22:38:07 -08006057status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6058 std::vector<int64_t> useCasesOverride;
6059 for (size_t i = 1; i < args.size(); i++) {
6060 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006061 std::string arg = toStdString(args[i]);
6062 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006063 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006064 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006065 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006066 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006067 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006068 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006069 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006070 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006071 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006072 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006073 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006074 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006075 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6076 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006077 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006078 return BAD_VALUE;
6079 }
6080 useCasesOverride.push_back(useCase);
6081 }
6082
6083 Mutex::Autolock lock(mServiceLock);
6084 mStreamUseCaseOverrides = std::move(useCasesOverride);
6085
6086 return OK;
6087}
6088
6089void CameraService::handleClearStreamUseCaseOverrides() {
6090 Mutex::Autolock lock(mServiceLock);
6091 mStreamUseCaseOverrides.clear();
6092}
6093
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006094status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6095 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006096 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006097 if ((*end != '\0') ||
6098 (zoomOverrideValue != -1 &&
6099 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6100 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6101 return BAD_VALUE;
6102 }
6103
6104 Mutex::Autolock lock(mServiceLock);
6105 mZoomOverrideValue = zoomOverrideValue;
6106
6107 const auto clients = mActiveClientManager.getAll();
6108 for (auto& current : clients) {
6109 if (current != nullptr) {
6110 const auto basicClient = current->getValue();
6111 if (basicClient.get() != nullptr) {
6112 if (basicClient->supportsZoomOverride()) {
6113 basicClient->setZoomOverride(mZoomOverrideValue);
6114 }
6115 }
6116 }
6117 }
6118
6119 return OK;
6120}
6121
Avichal Rakesh84147132021-11-11 17:47:11 -08006122status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006123 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006124 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006125 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006126 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006127 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006128 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006129 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006130 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006131 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006132 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006133 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006134 dprintf(outFd, "Camera service watch commands:\n"
6135 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6136 " starts watching the provided tags for clients with provided package\n"
6137 " recognizes tag shorthands like '3a'\n"
6138 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006139 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006140 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006141 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006142 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006143 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006144 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006145 return BAD_VALUE;
6146}
6147
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006148status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6149 Mutex::Autolock lock(mLogLock);
6150 size_t tagsIdx; // index of '-m'
6151 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006152 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006153 if (tagsIdx < args.size() - 1) {
6154 tags = args[tagsIdx + 1];
6155 } else {
6156 dprintf(outFd, "No tags provided.\n");
6157 return BAD_VALUE;
6158 }
6159
6160 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006161 // watch all clients if no clients are provided
6162 String16 clients = toString16(kWatchAllClientsFlag);
6163 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006164 clientsIdx++);
6165 if (clientsIdx < args.size() - 1) {
6166 clients = args[clientsIdx + 1];
6167 }
Austin Borgered99f642023-06-01 16:51:35 -07006168 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006169
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006170 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006171 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006172
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006173 bool serviceLock = tryLock(mServiceLock);
6174 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006175 auto cameraClients = mActiveClientManager.getAll();
6176 for (const auto &clientDescriptor: cameraClients) {
6177 if (clientDescriptor == nullptr) { continue; }
6178 sp<BasicClient> client = clientDescriptor->getValue();
6179 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006180
6181 if (isClientWatchedLocked(client.get())) {
6182 client->startWatchingTags(mMonitorTags, outFd);
6183 numWatchedClients++;
6184 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006185 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006186 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6187
6188 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006189 return OK;
6190}
6191
6192status_t CameraService::stopWatchingTags(int outFd) {
6193 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006194 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006195 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006196
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006197 mWatchedClientPackages.clear();
6198 mWatchedClientsDumpCache.clear();
6199
6200 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006201 auto cameraClients = mActiveClientManager.getAll();
6202 for (const auto &clientDescriptor : cameraClients) {
6203 if (clientDescriptor == nullptr) { continue; }
6204 sp<BasicClient> client = clientDescriptor->getValue();
6205 if (client.get() == nullptr) { continue; }
6206 client->stopWatchingTags(outFd);
6207 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006208 dprintf(outFd, "Stopped watching all clients.\n");
6209 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006210 return OK;
6211}
6212
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006213status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6214 Mutex::Autolock lock(mLogLock);
6215 size_t clearedSize = mWatchedClientsDumpCache.size();
6216 mWatchedClientsDumpCache.clear();
6217 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6218 return OK;
6219}
6220
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006221status_t CameraService::printWatchedTags(int outFd) {
6222 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006223 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006224
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006225 bool printedSomething = false; // tracks if any monitoring information was printed
6226 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006227
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006228 bool serviceLock = tryLock(mServiceLock);
6229 // get all watched clients that are currently connected
6230 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6231 if (clientDescriptor == nullptr) { continue; }
6232
6233 sp<BasicClient> client = clientDescriptor->getValue();
6234 if (client.get() == nullptr) { continue; }
6235 if (!isClientWatchedLocked(client.get())) { continue; }
6236
6237 std::vector<std::string> dumpVector;
6238 client->dumpWatchedEventsToVector(dumpVector);
6239
6240 size_t printIdx = dumpVector.size();
6241 if (printIdx == 0) {
6242 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006243 }
6244
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006245 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006246 const std::string &cameraId = clientDescriptor->getKey();
6247 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006248 while(printIdx > 0) {
6249 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006250 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006251 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006252 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006253 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006254 printedSomething = true;
6255
6256 connectedMonitoredClients.emplace(client->getPackageName());
6257 }
6258 if (serviceLock) { mServiceLock.unlock(); }
6259
6260 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6261 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006262 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006263 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6264 continue;
6265 }
6266
Austin Borgered99f642023-06-01 16:51:35 -07006267 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006268 dprintf(outFd, "%s\n", kv.second.c_str());
6269 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006270 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006271
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006272 if (!printedSomething) {
6273 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006274 }
6275
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006276 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006277}
6278
Avichal Rakesh84147132021-11-11 17:47:11 -08006279// Print all events in vector `events' that came after lastPrintedEvent
6280void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006281 const std::string &cameraId,
6282 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006283 const std::vector<std::string> &events,
6284 const std::string &lastPrintedEvent) {
6285 if (events.empty()) { return; }
6286
6287 // index of lastPrintedEvent in events.
6288 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6289 size_t lastPrintedIdx;
6290 for (lastPrintedIdx = 0;
6291 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6292 lastPrintedIdx++);
6293
6294 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6295
Avichal Rakesh84147132021-11-11 17:47:11 -08006296 // print events in chronological order (latest event last)
6297 size_t idxToPrint = lastPrintedIdx;
6298 do {
6299 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006300 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6301 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006302 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006303}
6304
6305// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6306// command should be interrupted if the user presses the return key, or if user loses any way to
6307// signal interrupt.
6308// If timeoutMs == 0, this function will always return false
6309bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6310 struct timeval startTime;
6311 int startTimeError = gettimeofday(&startTime, nullptr);
6312 if (startTimeError) {
6313 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6314 return true;
6315 }
6316
6317 const nfds_t numFds = 1;
6318 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6319
6320 struct timeval currTime;
6321 char buffer[2];
6322 while(true) {
6323 int currTimeError = gettimeofday(&currTime, nullptr);
6324 if (currTimeError) {
6325 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6326 return true;
6327 }
6328
6329 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6330 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6331 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6332
6333 if (remainingTimeMs <= 0) {
6334 // No user interrupt within timeoutMs, don't interrupt watch command
6335 return false;
6336 }
6337
6338 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6339 if (numFdsUpdated < 0) {
6340 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6341 return true;
6342 }
6343
6344 if (numFdsUpdated == 0) {
6345 // No user input within timeoutMs, don't interrupt watch command
6346 return false;
6347 }
6348
6349 if (!(pollFd.revents & POLLIN)) {
6350 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6351 return true;
6352 }
6353
6354 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6355 if (sizeRead < 0) {
6356 dprintf(outFd, "Error reading user input. Exiting.\n");
6357 return true;
6358 }
6359
6360 if (sizeRead == 0) {
6361 // Reached end of input fd (can happen if input is piped)
6362 // User has no way to signal an interrupt, so interrupt here
6363 return true;
6364 }
6365
6366 if (buffer[0] == '\n') {
6367 // User pressed return, interrupt watch command.
6368 return true;
6369 }
6370 }
6371}
6372
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006373status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6374 int inFd, int outFd) {
6375 // Figure out refresh interval, if present in args
6376 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006377 if (args.size() > 2) {
6378 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006379 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006380 intervalIdx++);
6381
6382 size_t intervalValIdx = intervalIdx + 1;
6383 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006384 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006385 if (errno) { return BAD_VALUE; }
6386 }
6387 }
6388
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006389 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6390 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006391
Avichal Rakesh84147132021-11-11 17:47:11 -08006392 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006393 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006394
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006395 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006396 bool serviceLock = tryLock(mServiceLock);
6397 auto cameraClients = mActiveClientManager.getAll();
6398 if (serviceLock) { mServiceLock.unlock(); }
6399
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006400 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006401 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006402 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006403
6404 sp<BasicClient> client = clientDescriptor->getValue();
6405 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006406 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006407
Austin Borgered99f642023-06-01 16:51:35 -07006408 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006409 // This also initializes the map entries with an empty string
6410 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6411
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006412 std::vector<std::string> latestEvents;
6413 client->dumpWatchedEventsToVector(latestEvents);
6414
6415 if (!latestEvents.empty()) {
6416 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006417 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006418 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006419 latestEvents,
6420 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006421 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006422 }
6423 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006424 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006425 break;
6426 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006427 }
6428 return OK;
6429}
6430
Austin Borgered99f642023-06-01 16:51:35 -07006431void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006432 mWatchedClientPackages.clear();
6433
Austin Borgered99f642023-06-01 16:51:35 -07006434 std::istringstream iss(clients);
6435 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006436
Austin Borgered99f642023-06-01 16:51:35 -07006437 while (std::getline(iss, nextClient, ',')) {
6438 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006439 // Don't need to track any other package if 'all' is present
6440 mWatchedClientPackages.clear();
6441 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6442 break;
6443 }
6444
6445 // track package names
6446 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006447 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006448}
6449
Svet Ganova453d0d2018-01-11 15:37:58 -08006450status_t CameraService::printHelp(int out) {
6451 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006452 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6453 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6454 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006455 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6456 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6457 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006458 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6459 " Valid values 0=false, 1=true, 2=auto\n"
6460 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006461 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6462 " Valid values 0=OFF, 1=ON for JPEG\n"
6463 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006464 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006465 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6466 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6467 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6468 " on. In case the number of usecases is smaller than the number of streams, the\n"
6469 " last use case is assigned to all the remaining streams. In case of multiple\n"
6470 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6471 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6472 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6473 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006474 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6475 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006476 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6477 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006478 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006479 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006480 " help print this message\n");
6481}
6482
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006483bool CameraService::isClientWatched(const BasicClient *client) {
6484 Mutex::Autolock lock(mLogLock);
6485 return isClientWatchedLocked(client);
6486}
6487
6488bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6489 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6490 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6491}
6492
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006493int32_t CameraService::updateAudioRestriction() {
6494 Mutex::Autolock lock(mServiceLock);
6495 return updateAudioRestrictionLocked();
6496}
6497
6498int32_t CameraService::updateAudioRestrictionLocked() {
6499 int32_t mode = 0;
6500 // iterate through all active client
6501 for (const auto& i : mActiveClientManager.getAll()) {
6502 const auto clientSp = i->getValue();
6503 mode |= clientSp->getAudioRestriction();
6504 }
6505
6506 bool modeChanged = (mAudioRestriction != mode);
6507 mAudioRestriction = mode;
6508 if (modeChanged) {
6509 mAppOps.setCameraAudioRestriction(mode);
6510 }
6511 return mode;
6512}
6513
Austin Borgered99f642023-06-01 16:51:35 -07006514status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006515 sp<BasicClient> clientSp) {
6516 std::unique_ptr<AutoConditionLock> lock =
6517 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6518 status_t res = NO_ERROR;
6519 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006520 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006521 mInjectionStatusListener->notifyInjectionError(
6522 externalCamId, UNKNOWN_TRANSACTION);
6523 clientSp->notifyError(
6524 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6525 CaptureResultExtras());
6526
6527 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6528 // other clients from connecting in mServiceLockWrapper if held
6529 mServiceLock.unlock();
6530
6531 // Clear caller identity temporarily so client disconnect PID checks work correctly
6532 int64_t token = CameraThreadState::clearCallingIdentity();
6533 clientSp->disconnect();
6534 CameraThreadState::restoreCallingIdentity(token);
6535
6536 // Reacquire mServiceLock
6537 mServiceLock.lock();
6538 }
6539
6540 return res;
6541}
6542
Cliff Wud3a05312021-04-26 23:07:31 +08006543void CameraService::clearInjectionParameters() {
6544 {
6545 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006546 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006547 mInjectionInternalCamId = "";
6548 }
6549 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006550 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006551}
6552
Mathias Agopian65ab4712010-07-14 17:59:35 -07006553}; // namespace android