blob: e30775dcbcb33de7b7a6c9632cb0978855609ea2 [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"
Shuzhen Wang316781a2020-08-18 18:11:01 -070084#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070085#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070086
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080087namespace {
88 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080089 const char* kActivityServiceName = "activity";
90 const char* kSensorPrivacyServiceName = "sensor_privacy";
91 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070092 const char* kProcessInfoServiceName = "processinfo";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080093}; // namespace anonymous
94
Mathias Agopian65ab4712010-07-14 17:59:35 -070095namespace android {
96
Austin Borgerea931242021-12-13 23:10:41 +000097using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -070098using namespace camera3::SessionConfigurationUtils;
99
100using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700101using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700102using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800103using hardware::ICamera;
104using hardware::ICameraClient;
105using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800106using hardware::camera2::ICameraInjectionCallback;
107using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800108using hardware::camera2::utils::CameraIdAndSessionConfiguration;
109using hardware::camera2::utils::ConcurrentCameraIdCombination;
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700110namespace flags = com::android::internal::camera::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800111
Mathias Agopian65ab4712010-07-14 17:59:35 -0700112// ----------------------------------------------------------------------------
113// Logging support -- this is for debugging only
114// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700115volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700116
Steve Blockb8a80522011-12-20 16:23:08 +0000117#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
118#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700119
120static void setLogLevel(int level) {
121 android_atomic_write(level, &gLogLevel);
122}
123
Henri Chataingbcb99452023-11-01 17:40:30 +0000124int32_t format_as(CameraService::StatusInternal s) {
125 return fmt::underlying(s);
126}
127
Mathias Agopian65ab4712010-07-14 17:59:35 -0700128// ----------------------------------------------------------------------------
129
Austin Borger249e6592024-03-10 22:28:11 -0700130// Permission strings (references to AttributionAndPermissionUtils for brevity)
131static const std::string &sDumpPermission =
132 AttributionAndPermissionUtils::sDumpPermission;
133static const std::string &sManageCameraPermission =
134 AttributionAndPermissionUtils::sManageCameraPermission;
135static const std::string &sCameraSendSystemEventsPermission =
136 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
137static const std::string &sCameraInjectExternalCameraPermission =
138 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
139
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000140// Constant integer for FGS Logging, used to denote the API type for logger
141static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700142const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800143static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
144static constexpr int32_t kSystemNativeClientState =
145 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700146static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700147
Austin Borgered99f642023-06-01 16:51:35 -0700148const std::string CameraService::kOfflineDevice("offline-");
149const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700150
Rucha Katakward9ea6452021-05-06 11:57:16 -0700151// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700152static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700153
Austin Borger74fca042022-05-23 12:41:21 -0700154CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700155 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
156 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
157 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
158 std::make_shared<AttributionAndPermissionUtils>()\
159 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700160 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
161 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800162 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800163 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700164 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700165 mSoundRef(0), mInitialized(false),
166 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000167 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700168 mAttributionAndPermissionUtils->setCameraService(this);
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
Charles Chena7b613c2023-01-24 21:57:33 +0000176// Enable processes with isolated AID to request the binder
177void CameraService::instantiate() {
178 CameraService::publish(true);
179}
180
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800181void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700182 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800183 return;
184 }
185
186 ALOGV("appops service registered. setting camera audio restriction");
187 mAppOps.setCameraAudioRestriction(mAudioRestriction);
188}
189
Iliyan Malchev8951a972011-04-14 16:55:59 -0700190void CameraService::onFirstRef()
191{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700192
Ruben Brunkcc776712015-02-17 20:18:47 -0800193 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800194
Iliyan Malchev8951a972011-04-14 16:55:59 -0700195 BnCameraService::onFirstRef();
196
Ruben Brunk99e69712015-05-26 17:25:07 -0700197 // Update battery life tracking if service is restarting
198 BatteryNotifier& notifier(BatteryNotifier::getInstance());
199 notifier.noteResetCamera();
200 notifier.noteResetFlashlight();
201
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800202 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800203
Emilian Peevf53f66e2017-04-11 14:29:43 +0100204 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800205 if (res == OK) {
206 mInitialized = true;
207 }
208
Svet Ganova453d0d2018-01-11 15:37:58 -0800209 mUidPolicy = new UidPolicy(this);
210 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700211 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800212 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800213 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800214
215 // appops function setCamerAudioRestriction uses getService which
216 // is blocking till the appops service is ready. To enable early
217 // boot availability for cameraservice, use checkService which is
218 // non blocking and register for notifications
219 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700220 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800221 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700222 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800223 } else {
224 mAppOps.setCameraAudioRestriction(mAudioRestriction);
225 }
226
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700227 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
228 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000229 // Deprecated, so it will fail to register on newer devices
230 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700231 __FUNCTION__);
232 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700233
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700234 if (!AidlCameraService::registerService(this)) {
235 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
236 }
237
Shuzhen Wang24b44152019-09-20 10:38:11 -0700238 // This needs to be last call in this function, so that it's as close to
239 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700240 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700241 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800242}
243
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800244status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800245 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100246
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800247 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000248 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800249 {
250 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800251
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800252 if (nullptr == mCameraProviderManager.get()) {
253 mCameraProviderManager = new CameraProviderManager();
254 res = mCameraProviderManager->initialize(this);
255 if (res != OK) {
256 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
257 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700258 logServiceError("Unable to initialize camera provider manager",
259 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800260 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100261 }
262 }
263
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800264
265 // Setup vendor tags before we call get_camera_info the first time
266 // because HAL might need to setup static vendor keys in get_camera_info
267 // TODO: maybe put this into CameraProviderManager::initialize()?
268 mCameraProviderManager->setUpVendorTags();
269
270 if (nullptr == mFlashlight.get()) {
271 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700272 }
273
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800274 res = mFlashlight->findFlashUnits();
275 if (res != OK) {
276 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
277 }
278
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000279 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800280 }
281
282
283 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700284 if (getCameraState(cameraId) == nullptr) {
285 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800286 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000287 if (unavailPhysicalIds.count(cameraId) > 0) {
288 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700289 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000290 }
291 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800292 }
293
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700294 // Derive primary rear/front cameras, and filter their charactierstics.
295 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700296 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700297 // Assume internal cameras are advertised from the same
298 // provider. If multiple providers are registered at different time,
299 // and each provider contains multiple internal color cameras, the current
300 // logic may filter the characteristics of more than one front/rear color
301 // cameras.
302 Mutex::Autolock l(mServiceLock);
303 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700304 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700305
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800306 return OK;
307}
308
Austin Borgered99f642023-06-01 16:51:35 -0700309void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700310 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800311 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800312 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700313 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
314 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000315 ALOGV("%s: Skipping torch callback for system-only camera device %s",
316 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700317 continue;
318 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700319 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700320 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700321 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
322 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000323 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
324 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700325 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000326 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
327 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700328 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000329 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
330 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
331 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 }
333}
334
Mathias Agopian65ab4712010-07-14 17:59:35 -0700335CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800336 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800337 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800338 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800339 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340}
341
Emilian Peevaee727d2017-05-04 16:35:48 +0100342void CameraService::onNewProviderRegistered() {
343 enumerateProviders();
344}
345
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700346void CameraService::filterAPI1SystemCameraLocked(
347 const std::vector<std::string> &normalDeviceIds) {
348 mNormalDeviceIdsWithoutSystemCamera.clear();
349 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700350 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700351 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700352 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
353 continue;
354 }
355 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700356 // All system camera ids will necessarily come after public camera
357 // device ids as per the HAL interface contract.
358 break;
359 }
360 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
361 }
362 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
363 mNormalDeviceIdsWithoutSystemCamera.size());
364}
365
Austin Borgered99f642023-06-01 16:51:35 -0700366status_t CameraService::getSystemCameraKind(const std::string& cameraId,
367 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700368 auto state = getCameraState(cameraId);
369 if (state != nullptr) {
370 *kind = state->getSystemCameraKind();
371 return OK;
372 }
373 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700374 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700375}
376
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800377void CameraService::updateCameraNumAndIds() {
378 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700379 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
380 // Excludes hidden secure cameras
381 mNumberOfCameras =
382 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
383 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800384 mNormalDeviceIds =
385 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700386 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800387}
388
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700389void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700390 // To claim to be S Performance primary cameras, the cameras must be
391 // backward compatible. So performance class primary camera Ids must be API1
392 // compatible.
393 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
394 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
395 int facing = -1;
396 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800397 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700398 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800399 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700400 if (facing == -1) {
401 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
402 return;
403 }
404
405 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
406 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700407 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
408 if (res == OK) {
409 mPerfClassPrimaryCameraIds.insert(cameraId);
410 } else {
411 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
412 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
413 break;
414 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700415
416 if (facing == hardware::CAMERA_FACING_BACK) {
417 firstRearCameraSeen = true;
418 }
419 if (facing == hardware::CAMERA_FACING_FRONT) {
420 firstFrontCameraSeen = true;
421 }
422 }
423
424 if (firstRearCameraSeen && firstFrontCameraSeen) {
425 break;
426 }
427 }
428}
429
Austin Borgered99f642023-06-01 16:51:35 -0700430void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700431 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100432 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
433 if (res != OK) {
434 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
435 return;
436 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000437 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700438 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
439 if (res != OK) {
440 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
441 return;
442 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000443 std::vector<std::string> physicalCameraIds;
444 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700445 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100446 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700447 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100448 }
449
450 {
451 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700452 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000453 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100454 }
455
Austin Borgered99f642023-06-01 16:51:35 -0700456 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100457 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700458 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800459
Austin Borgered99f642023-06-01 16:51:35 -0700460 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100461 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800462
463 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700464 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100465}
466
Austin Borgered99f642023-06-01 16:51:35 -0700467void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800468 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700469 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100470 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700471 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100472 }
473
474 {
475 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700476 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100477 }
478}
479
Austin Borgered99f642023-06-01 16:51:35 -0700480void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800481 CameraDeviceStatus newHalStatus) {
482 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700483 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700484
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800485 StatusInternal newStatus = mapToInternal(newHalStatus);
486
Austin Borgered99f642023-06-01 16:51:35 -0700487 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800488
489 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700490 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100491 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700492 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493
494 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700495 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100496
Austin Borgered99f642023-06-01 16:51:35 -0700497 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700498 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700499 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700500 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700501 return;
502 }
503
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800504 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800505
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800506 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800507 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700508 return;
509 }
510
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800511 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000512 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
513 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800514
515 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
516 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700517 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800518
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800519 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700520 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800521 // Don't do this in updateStatus to avoid deadlock over mServiceLock
522 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700523
Ruben Brunkcc776712015-02-17 20:18:47 -0800524 // Remove cached shim parameters
525 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700526
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800527 // Remove online as well as offline client from the list of active clients,
528 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700529 clientToDisconnectOnline = removeClientLocked(cameraId);
530 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700531 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800532
Austin Borgered99f642023-06-01 16:51:35 -0700533 disconnectClient(cameraId, clientToDisconnectOnline);
534 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700535
Austin Borgered99f642023-06-01 16:51:35 -0700536 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800537 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800538 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000539 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
540 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700541 }
Austin Borgered99f642023-06-01 16:51:35 -0700542 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700543 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800544}
Igor Murashkincba2c162013-03-20 15:56:31 -0700545
Austin Borgered99f642023-06-01 16:51:35 -0700546void CameraService::onDeviceStatusChanged(const std::string& id,
547 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800548 CameraDeviceStatus newHalStatus) {
549 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700550 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800551
552 StatusInternal newStatus = mapToInternal(newHalStatus);
553
554 std::shared_ptr<CameraState> state = getCameraState(id);
555
556 if (state == nullptr) {
557 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700558 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800559 return;
560 }
561
562 StatusInternal logicalCameraStatus = state->getStatus();
563 if (logicalCameraStatus != StatusInternal::PRESENT &&
564 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
565 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700566 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800567 return;
568 }
569
570 bool updated = false;
571 if (newStatus == StatusInternal::PRESENT) {
572 updated = state->removeUnavailablePhysicalId(physicalId);
573 } else {
574 updated = state->addUnavailablePhysicalId(physicalId);
575 }
576
577 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700578 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800579 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000580 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800581 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000582 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800583 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700584 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
585 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
586 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700587 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700588 return;
589 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800590 Mutex::Autolock lock(mStatusListenerLock);
591 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700592 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
593 listener->getListenerPid(), listener->getListenerUid())) {
594 ALOGV("Skipping discovery callback for system-only camera device %s",
595 id.c_str());
596 continue;
597 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700598 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700599 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700600 listener->handleBinderStatus(ret,
601 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
602 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
603 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800604 }
605 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700606}
607
Austin Borgered99f642023-06-01 16:51:35 -0700608void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800609 if (clientToDisconnect.get() != nullptr) {
610 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700611 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800612 // Notify the client of disconnection
613 clientToDisconnect->notifyError(
614 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
615 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800616 clientToDisconnect->disconnect();
617 }
618}
619
Austin Borgered99f642023-06-01 16:51:35 -0700620void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800621 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700622 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
623 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
624 if (res != OK) {
625 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700626 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700627 return;
628 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800629 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700630 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800631}
632
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700633
Austin Borgered99f642023-06-01 16:51:35 -0700634void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700635 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
636 Mutex::Autolock al(mTorchStatusMutex);
637 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
638}
639
Austin Borgered99f642023-06-01 16:51:35 -0700640void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800641 int32_t newStrengthLevel) {
642 Mutex::Autolock lock(mStatusListenerLock);
643 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700644 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700645 i->handleBinderStatus(ret,
646 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
647 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800648 }
649}
650
Austin Borgered99f642023-06-01 16:51:35 -0700651void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700652 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800653 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700654 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800655
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800656 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800657 status_t res = getTorchStatusLocked(cameraId, &status);
658 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700659 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700660 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800661 return;
662 }
663 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664 return;
665 }
666
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800667 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800668 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800669 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
670 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800671 return;
672 }
673
Ruben Brunkcc776712015-02-17 20:18:47 -0800674 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700675 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700676 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700677 auto iter = mTorchUidMap.find(cameraId);
678 if (iter != mTorchUidMap.end()) {
679 int oldUid = iter->second.second;
680 int newUid = iter->second.first;
681 BatteryNotifier& notifier(BatteryNotifier::getInstance());
682 if (oldUid != newUid) {
683 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800684 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700685 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700686 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800687 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700688 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700689 }
690 iter->second.second = newUid;
691 } else {
692 // If the UID has not changed, log the status
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), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700695 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700696 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700697 }
698 }
699 }
700 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700701 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800702}
703
Austin Borger249e6592024-03-10 22:28:11 -0700704bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700705 // Returns false if this is not an automotive device type.
706 if (!isAutomotiveDevice())
707 return false;
708
709 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700710 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700711 return false;
712
713 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
714 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
715 // This isn't a known camera ID, so it's not a system camera.
716 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
717 return false;
718 }
719
720 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
721 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
722 return false;
723 }
724
725 CameraMetadata cameraInfo;
726 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700727 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700728 if (res != OK){
729 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
730 cam_id.c_str());
731 return false;
732 }
733
734 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
735 if (auto_location.count != 1)
736 return false;
737
738 uint8_t location = auto_location.data.u8[0];
739 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
740 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
741 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
742 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
743 return false;
744 }
745
746 return true;
747}
748
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800749Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700750 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100751 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700752 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800753 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
754 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700755 switch (type) {
756 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700757 if (hasSystemCameraPermissions) {
758 *numCameras = static_cast<int>(mNormalDeviceIds.size());
759 } else {
760 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
761 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800762 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700763 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700764 if (hasSystemCameraPermissions) {
765 *numCameras = mNumberOfCameras;
766 } else {
767 *numCameras = mNumberOfCamerasWithoutSystemCamera;
768 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800769 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700770 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800771 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700772 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800773 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
774 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700775 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700777}
778
malikakash73125c62023-07-21 22:44:34 +0000779Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700780 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800781 const int pid = getCallingPid();
782 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000783 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
784 __FUNCTION__, pid, uid);
785 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
786 "Permission Denial: no permission to configure camera id mapping");
787 }
788 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000789 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000790 if (!parseStatus.isOk()) {
791 return parseStatus;
792 }
793 remapCameraIds(cameraIdRemappingMap);
794 return Status::ok();
795}
796
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700797Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
798 /* out */
799 hardware::camera2::impl::CameraMetadataNative* request) {
800 ATRACE_CALL();
801
802 if (!flags::feature_combination_query()) {
803 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
804 "Camera subsystem doesn't support this method!");
805 }
806 if (!mInitialized) {
807 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
808 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
809 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
810 }
811
812 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -0800813 getCallingUid());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700814
815 binder::Status res;
816 if (request == nullptr) {
817 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
818 "Camera %s: Error creating default request", cameraId.c_str());
819 return res;
820 }
821 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
822 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
823 cameraId, templateId, &tempId);
824 if (!res.isOk()) {
825 ALOGE("%s: Camera %s: failed to map request Template %d",
826 __FUNCTION__, cameraId.c_str(), templateId);
827 return res;
828 }
829
830 if (shouldRejectSystemCameraConnection(cameraId)) {
831 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
832 "request for system only device %s: ", cameraId.c_str());
833 }
834
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700835 CameraMetadata metadata;
836 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
837 if (err == OK) {
838 request->swap(metadata);
839 } else if (err == BAD_VALUE) {
840 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
841 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
842 cameraId.c_str(), templateId, strerror(-err), err);
843 } else {
844 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
845 "Camera %s: Error creating default request for template %d: %s (%d)",
846 cameraId.c_str(), templateId, strerror(-err), err);
847 }
848 return res;
849}
850
851Status CameraService::isSessionConfigurationWithParametersSupported(
852 const std::string& unresolvedCameraId,
853 const SessionConfiguration& sessionConfiguration,
854 /*out*/
855 bool* supported) {
856 ATRACE_CALL();
857
858 if (!flags::feature_combination_query()) {
859 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
860 "Camera subsystem doesn't support this method!");
861 }
862 if (!mInitialized) {
863 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
864 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
865 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
866 }
867
868 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -0800869 getCallingUid());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700870 if (supported == nullptr) {
871 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
872 unresolvedCameraId.c_str());
873 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
874 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
875 }
876
877 if (shouldRejectSystemCameraConnection(cameraId)) {
878 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
879 "session configuration with parameters support for system only device %s: ",
880 cameraId.c_str());
881 }
882
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700883 *supported = false;
884 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
885 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
886 supported);
887 binder::Status res;
888 switch (ret) {
889 case OK:
890 // Expected, do nothing.
891 break;
892 case INVALID_OPERATION: {
893 std::string msg = fmt::sprintf(
894 "Camera %s: Session configuration query not supported!",
895 cameraId.c_str());
896 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
897 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
898 }
899
900 break;
901 default: {
902 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
903 strerror(-ret), ret);
904 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
905 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
906 msg.c_str());
907 }
908 }
909
910 return res;
911}
912
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800913Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
914 int targetSdkVersion, bool overrideToPortrait,
915 const SessionConfiguration& sessionConfiguration,
916 /*out*/ CameraMetadata* outMetadata) {
917 ATRACE_CALL();
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 =
Austin Borger22c5c852024-03-08 13:31:36 -0800926 resolveCameraId(unresolvedCameraId, getCallingUid());
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800927
928 if (outMetadata == nullptr) {
929 std::string msg =
930 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
931 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
932 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
933 }
934
935 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
936 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
937
938 status_t ret = mCameraProviderManager->getSessionCharacteristics(
939 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
940
941 // TODO(b/303645857): Remove fingerprintable metadata if the caller process does not have
942 // camera access permission.
943
944 Status res = Status::ok();
945 switch (ret) {
946 case OK:
947 // Expected, no handling needed.
948 break;
949 case INVALID_OPERATION: {
950 std::string msg = fmt::sprintf(
951 "Camera %s: Session characteristics 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 break;
957 default: {
958 std::string msg = fmt::sprintf("Camera %s: Error: %s (%d)", cameraId.c_str(),
959 strerror(-ret), ret);
960 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
961 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
962 }
963 }
964
965 return res;
966}
967
malikakash82ed4352023-07-21 22:44:34 +0000968Status CameraService::parseCameraIdRemapping(
969 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +0000970 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700971 std::string packageName;
972 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +0000973 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +0000974 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +0000975 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +0000976 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
977 "CameraIdRemapping: Package name cannot be empty");
978 }
malikakash214f6e62023-08-10 23:50:56 +0000979 if (packageIdRemapping.cameraIdsToReplace.size()
980 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +0000981 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
982 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +0000983 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +0000984 }
malikakash214f6e62023-08-10 23:50:56 +0000985 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700986 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
987 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +0000988 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +0000989 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
990 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700991 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000992 }
993 if (cameraIdToReplace == updatedCameraId) {
994 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
995 "CameraIdRemapping: CameraIdToReplace cannot be the same"
996 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -0700997 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000998 }
999 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001000 }
1001 }
1002 return Status::ok();
1003}
1004
1005void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1006 // Acquire mServiceLock and prevent other clients from connecting
1007 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1008 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1009
malikakashedb38962023-09-06 00:03:35 +00001010 // Collect all existing clients for camera Ids that are being
1011 // remapped in the new cameraIdRemapping, but only if they were being used by a
1012 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001013 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001014 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001015 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1016 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001017 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001018 id0.c_str(), id1.c_str());
1019 auto clientDescriptor = mActiveClientManager.get(id0);
1020 if (clientDescriptor != nullptr) {
1021 sp<BasicClient> clientSp = clientDescriptor->getValue();
1022 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001023 // This camera is being used by a targeted packageName and
1024 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001025 clientsToDisconnect.push_back(clientSp);
1026 cameraIdsToUpdate.push_back(id0);
1027 }
1028 }
1029 }
1030 }
1031
malikakashedb38962023-09-06 00:03:35 +00001032 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001033 // Notify the clients about the disconnection.
1034 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001035 CaptureResultExtras{});
1036 }
malikakash82ed4352023-07-21 22:44:34 +00001037
1038 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1039 // blocking other clients from connecting in mServiceLockWrapper if held.
1040 mServiceLock.unlock();
1041
malikakashedb38962023-09-06 00:03:35 +00001042 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001043 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001044
malikakash82ed4352023-07-21 22:44:34 +00001045 // Disconnect clients.
1046 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001047 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1048 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001049 clientSp->disconnect();
1050 }
1051
malikakashedb38962023-09-06 00:03:35 +00001052 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1053 clientsToDisconnect.clear();
1054
Austin Borger22c5c852024-03-08 13:31:36 -08001055 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001056 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001057
1058 {
1059 Mutex::Autolock lock(mCameraIdRemappingLock);
1060 // Update mCameraIdRemapping.
1061 mCameraIdRemapping.clear();
1062 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1063 }
malikakash82ed4352023-07-21 22:44:34 +00001064}
1065
malikakash22af94c2023-12-04 18:13:14 +00001066Status CameraService::injectSessionParams(
1067 const std::string& cameraId,
1068 const CameraMetadata& sessionParams) {
1069 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001070 const int pid = getCallingPid();
1071 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001072 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1073 __FUNCTION__, pid, uid);
1074 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1075 "Permission Denial: no permission to inject session params");
1076 }
1077
1078 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1079 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1080
1081 auto clientDescriptor = mActiveClientManager.get(cameraId);
1082 if (clientDescriptor == nullptr) {
1083 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1084 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1085 "No active client for camera id %s", cameraId.c_str());
1086 }
1087
1088 sp<BasicClient> clientSp = clientDescriptor->getValue();
1089 status_t res = clientSp->injectSessionParams(sessionParams);
1090
1091 if (res != OK) {
1092 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1093 "Error injecting session params into camera \"%s\": %s (%d)",
1094 cameraId.c_str(), strerror(-res), res);
1095 }
1096 return Status::ok();
1097}
1098
Austin Borgered99f642023-06-01 16:51:35 -07001099std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1100 const std::string& inputCameraId, int clientUid) {
1101 std::string packageName = getPackageNameFromUid(clientUid);
1102 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001103 Mutex::Autolock lock(mCameraIdRemappingLock);
1104 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1105 packageMapIter != mCameraIdRemapping.end()) {
1106 for (auto& [id0, id1]: packageMapIter->second) {
1107 if (id1 == inputCameraId) {
1108 cameraIds.push_back(id0);
1109 }
1110 }
1111 }
1112 return cameraIds;
1113}
1114
Austin Borgered99f642023-06-01 16:51:35 -07001115std::string CameraService::resolveCameraId(
1116 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001117 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001118 const std::string& packageName) {
1119 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001120 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001121 packageNameVal = getPackageNameFromUid(clientUid);
1122 }
malikakash65d20692023-09-07 01:06:33 +00001123 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001124 // We shouldn't remap cameras for processes with system/vendor UIDs.
1125 return inputCameraId;
1126 }
malikakash82ed4352023-07-21 22:44:34 +00001127 Mutex::Autolock lock(mCameraIdRemappingLock);
1128 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1129 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001130 auto packageMap = packageMapIter->second;
1131 if (auto replacementIdIter = packageMap.find(inputCameraId);
1132 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001133 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001134 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001135 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001136 replacementIdIter->second.c_str());
1137 return replacementIdIter->second;
1138 }
1139 }
1140 return inputCameraId;
1141}
1142
Austin Borger18b30a72022-10-27 12:20:29 -07001143Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001144 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001145 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001146 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001147 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
1148 std::string cameraIdStr = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08001149 unresolvedCameraId, getCallingUid());
malikakashedb38962023-09-06 00:03:35 +00001150
Austin Borgered99f642023-06-01 16:51:35 -07001151 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001152 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1153 "characteristics for system only device %s: ", cameraIdStr.c_str());
1154 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001155
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001156 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001157 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001158 return STATUS_ERROR(ERROR_DISCONNECTED,
1159 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001160 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001161 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001162 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001163 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1164 if (hasSystemCameraPermissions) {
1165 cameraIdBound = mNumberOfCameras;
1166 }
1167 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001168 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1169 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001170 }
1171
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001172 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001173 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001174 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001175 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001176 if (err != OK) {
1177 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1178 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1179 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001180 logServiceError(std::string("Error retrieving camera info from device ")
1181 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001182 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001183
Ruben Brunkcc776712015-02-17 20:18:47 -08001184 return ret;
1185}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001186
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001187std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001188 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001189 auto callingPid = getCallingPid();
1190 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001191 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1192 callingPid, callingUid, /* checkCameraPermissions= */ false);
1193 if (systemCameraPermissions || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001194 deviceIds = &mNormalDeviceIds;
1195 }
1196 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001197 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001198 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001199 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001200 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001201
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001202 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001203}
1204
Austin Borgered99f642023-06-01 16:51:35 -07001205std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001206 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001207 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001208}
1209
Austin Borgered99f642023-06-01 16:51:35 -07001210Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001211 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001212 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001213
malikakashedb38962023-09-06 00:03:35 +00001214 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001215 getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -07001216
Zhijun He2b59be82013-09-25 10:14:30 -07001217 if (!cameraInfo) {
1218 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001219 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001220 }
1221
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001222 if (!mInitialized) {
1223 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001224 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001225 return STATUS_ERROR(ERROR_DISCONNECTED,
1226 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001227 }
1228
Austin Borgered99f642023-06-01 16:51:35 -07001229 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001230 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001231 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001232 }
1233
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001234 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001235
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001236 bool overrideForPerfClass =
1237 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001238 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001239 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001240 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001241 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001242 if (res == NAME_NOT_FOUND) {
1243 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001244 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001245 strerror(-res), res);
1246 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001247 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1248 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001249 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001250 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001251 strerror(-res), res);
1252 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001253 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001254 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001255 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1256 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001257 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001258 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001259 }
Austin Borger22c5c852024-03-08 13:31:36 -08001260 int callingPid = getCallingPid();
1261 int callingUid = getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001262 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001263 // If it's not calling from cameraserver, check the permission only if
1264 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1265 // it would've already been checked in shouldRejectSystemCameraConnection.
Austin Borger249e6592024-03-10 22:28:11 -07001266 bool checkPermissionForCamera = hasPermissionsForCamera(cameraId, callingPid, callingUid);
Emilian Peeve20c6372018-08-14 18:45:53 +01001267 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001268 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001269 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001270 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001271 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001272 &tagsRemoved);
1273 if (res != OK) {
1274 cameraInfo->clear();
1275 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1276 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001277 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001278 }
1279 }
1280
1281 if (!tagsRemoved.empty()) {
1282 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1283 tagsRemoved.data(), tagsRemoved.size());
1284 if (res != OK) {
1285 cameraInfo->clear();
1286 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001287 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001288 strerror(-res), res);
1289 }
1290 }
1291
Zhijun He2b59be82013-09-25 10:14:30 -07001292 return ret;
1293}
1294
malikakashedb38962023-09-06 00:03:35 +00001295Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001296 int32_t* torchStrength) {
1297 ATRACE_CALL();
1298 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001299
malikakashedb38962023-09-06 00:03:35 +00001300 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08001301 unresolvedCameraId, getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001302 if (!mInitialized) {
1303 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1304 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1305 }
1306
1307 if(torchStrength == NULL) {
1308 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1309 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1310 }
1311
Austin Borgered99f642023-06-01 16:51:35 -07001312 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001313 if (res != OK) {
1314 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001315 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001316 strerror(-res), res);
1317 }
1318 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1319 return Status::ok();
1320}
1321
Austin Borgered99f642023-06-01 16:51:35 -07001322std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001323 time_t now = time(nullptr);
1324 char formattedTime[64];
1325 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001326 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001327}
1328
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001329Status CameraService::getCameraVendorTagDescriptor(
1330 /*out*/
1331 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001332 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001333 if (!mInitialized) {
1334 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001335 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001336 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001337 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1338 if (globalDescriptor != nullptr) {
1339 *desc = *(globalDescriptor.get());
1340 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001341 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001342}
1343
Emilian Peev71c73a22017-03-21 16:35:51 +00001344Status CameraService::getCameraVendorTagCache(
1345 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1346 ATRACE_CALL();
1347 if (!mInitialized) {
1348 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1349 return STATUS_ERROR(ERROR_DISCONNECTED,
1350 "Camera subsystem not available");
1351 }
1352 sp<VendorTagDescriptorCache> globalCache =
1353 VendorTagDescriptorCache::getGlobalVendorTagCache();
1354 if (globalCache != nullptr) {
1355 *cache = *(globalCache.get());
1356 }
1357 return Status::ok();
1358}
1359
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001360void CameraService::clearCachedVariables() {
1361 BasicClient::BasicClient::sCameraService = nullptr;
1362}
1363
Austin Borgered99f642023-06-01 16:51:35 -07001364std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001365 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001366 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001367
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001368 int deviceVersion = 0;
1369
Emilian Peevf53f66e2017-04-11 14:29:43 +01001370 status_t res;
1371 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001372 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001373 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001374 if (res != OK || transport == IPCTransport::INVALID) {
1375 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001376 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001377 return std::make_pair(-1, IPCTransport::INVALID) ;
1378 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001379 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001380
Emilian Peevf53f66e2017-04-11 14:29:43 +01001381 hardware::CameraInfo info;
1382 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001383 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001384 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001385 if (res != OK) {
1386 return std::make_pair(-1, IPCTransport::INVALID);
1387 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001388 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001389 if (orientation) {
1390 *orientation = info.orientation;
1391 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001392 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001393
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001394 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001395}
1396
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001397Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001398 switch(err) {
1399 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001400 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001401 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001402 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1403 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001404 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001405 return STATUS_ERROR(ERROR_DISCONNECTED,
1406 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001407 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001408 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1409 "Camera HAL encountered error %d: %s",
1410 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001411 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001412}
1413
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001414Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001415 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1416 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001417 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001418 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001419 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001420 bool forceSlowJpegMode, const std::string& originalCameraId,
1421 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001422 // For HIDL devices
1423 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1424 // Create CameraClient based on device version reported by the HAL.
1425 int deviceVersion = deviceVersionAndTransport.first;
1426 switch(deviceVersion) {
1427 case CAMERA_DEVICE_API_VERSION_1_0:
1428 ALOGE("Camera using old HAL version: %d", deviceVersion);
1429 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1430 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001431 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001432 break;
1433 case CAMERA_DEVICE_API_VERSION_3_0:
1434 case CAMERA_DEVICE_API_VERSION_3_1:
1435 case CAMERA_DEVICE_API_VERSION_3_2:
1436 case CAMERA_DEVICE_API_VERSION_3_3:
1437 case CAMERA_DEVICE_API_VERSION_3_4:
1438 case CAMERA_DEVICE_API_VERSION_3_5:
1439 case CAMERA_DEVICE_API_VERSION_3_6:
1440 case CAMERA_DEVICE_API_VERSION_3_7:
1441 break;
1442 default:
1443 // Should not be reachable
1444 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1445 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1446 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001447 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001448 }
1449 }
1450 if (effectiveApiLevel == API_1) { // Camera1 API route
1451 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001452 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001453 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001454 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001455 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1456 forceSlowJpegMode);
1457 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1458 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001459 } else { // Camera2 API route
1460 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1461 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001462 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001463 cameraService->mCameraServiceProxyWrapper,
1464 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001465 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001466 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001467 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001468 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001470}
1471
Austin Borgered99f642023-06-01 16:51:35 -07001472std::string CameraService::toString(std::set<userid_t> intSet) {
1473 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001474 bool first = true;
1475 for (userid_t i : intSet) {
1476 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001477 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001478 first = false;
1479 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001480 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001481 }
1482 }
Austin Borgered99f642023-06-01 16:51:35 -07001483 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001484}
1485
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001486int32_t CameraService::mapToInterface(TorchModeStatus status) {
1487 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1488 switch (status) {
1489 case TorchModeStatus::NOT_AVAILABLE:
1490 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1491 break;
1492 case TorchModeStatus::AVAILABLE_OFF:
1493 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1494 break;
1495 case TorchModeStatus::AVAILABLE_ON:
1496 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1497 break;
1498 default:
1499 ALOGW("Unknown new flash status: %d", status);
1500 }
1501 return serviceStatus;
1502}
1503
1504CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1505 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1506 switch (status) {
1507 case CameraDeviceStatus::NOT_PRESENT:
1508 serviceStatus = StatusInternal::NOT_PRESENT;
1509 break;
1510 case CameraDeviceStatus::PRESENT:
1511 serviceStatus = StatusInternal::PRESENT;
1512 break;
1513 case CameraDeviceStatus::ENUMERATING:
1514 serviceStatus = StatusInternal::ENUMERATING;
1515 break;
1516 default:
1517 ALOGW("Unknown new HAL device status: %d", status);
1518 }
1519 return serviceStatus;
1520}
1521
1522int32_t CameraService::mapToInterface(StatusInternal status) {
1523 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1524 switch (status) {
1525 case StatusInternal::NOT_PRESENT:
1526 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1527 break;
1528 case StatusInternal::PRESENT:
1529 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1530 break;
1531 case StatusInternal::ENUMERATING:
1532 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1533 break;
1534 case StatusInternal::NOT_AVAILABLE:
1535 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1536 break;
1537 case StatusInternal::UNKNOWN:
1538 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1539 break;
1540 default:
1541 ALOGW("Unknown new internal device status: %d", status);
1542 }
1543 return serviceStatus;
1544}
1545
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001546Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001547 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001548
Austin Borgered99f642023-06-01 16:51:35 -07001549 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001550 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001551 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001552 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001553 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1554 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001555 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001556 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001557 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001558 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001559 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001560 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001561 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001562}
1563
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001564Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001565 /*out*/
1566 CameraParameters* parameters) {
1567
1568 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1569
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001570 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001571
1572 if (parameters == NULL) {
1573 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001574 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001575 }
1576
malikakashedb38962023-09-06 00:03:35 +00001577 std::string unresolvedCameraId = std::to_string(cameraId);
1578 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001579 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001580
1581 // Check if we already have parameters
1582 {
1583 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001584 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001585 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001586 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001587 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001588 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001589 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001590 }
1591 CameraParameters p = cameraState->getShimParams();
1592 if (!p.isEmpty()) {
1593 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001594 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001595 }
1596 }
1597
Austin Borger22c5c852024-03-08 13:31:36 -08001598 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001599 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001600 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001601 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001602 // Error already logged by callee
1603 return ret;
1604 }
1605
1606 // Check for parameters again
1607 {
1608 // Scope for service lock
1609 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001610 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001611 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001612 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001613 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001614 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001615 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001616 CameraParameters p = cameraState->getShimParams();
1617 if (!p.isEmpty()) {
1618 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001620 }
1621 }
1622
Ruben Brunkcc776712015-02-17 20:18:47 -08001623 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1624 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001625 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001626}
1627
Austin Borgered99f642023-06-01 16:51:35 -07001628Status CameraService::validateConnectLocked(const std::string& cameraId,
1629 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001630 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001631
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001632#ifdef __BRILLO__
1633 UNUSED(clientName8);
1634 UNUSED(clientUid);
1635 UNUSED(clientPid);
1636 UNUSED(originalClientPid);
1637#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001638 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1639 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001640 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001641 return allowed;
1642 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001643#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001644
Austin Borger22c5c852024-03-08 13:31:36 -08001645 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001646
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001647 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001648 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1649 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001650 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001651 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001652 }
1653
Ruben Brunkcc776712015-02-17 20:18:47 -08001654 if (getCameraState(cameraId) == nullptr) {
1655 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001656 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001657 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001658 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001659 }
1660
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001661 status_t err = checkIfDeviceIsUsable(cameraId);
1662 if (err != NO_ERROR) {
1663 switch(err) {
1664 case -ENODEV:
1665 case -EBUSY:
1666 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001667 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001668 default:
1669 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001670 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001671 }
1672 }
1673 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001674}
1675
Austin Borgered99f642023-06-01 16:51:35 -07001676Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1677 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001678 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001679 int callingPid = getCallingPid();
1680 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001681
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001682 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001683 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001684 clientUid = callingUid;
1685 } else if (!isTrustedCallingUid(callingUid)) {
1686 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1687 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001688 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1689 "Untrusted caller (calling PID %d, UID %d) trying to "
1690 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001691 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001692 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001693 }
1694
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001695 // Check if we can trust clientPid
1696 if (clientPid == USE_CALLING_PID) {
1697 clientPid = callingPid;
1698 } else if (!isTrustedCallingUid(callingUid)) {
1699 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1700 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001701 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1702 "Untrusted caller (calling PID %d, UID %d) trying to "
1703 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001704 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001705 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001706 }
1707
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001708 if (shouldRejectSystemCameraConnection(cameraId)) {
1709 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1710 cameraId.c_str());
1711 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001712 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001713 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001714 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1715 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001716 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001717 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001718 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001719
1720 }
1721
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001722 // If it's not calling from cameraserver, check the permission if the
1723 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1724 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001725 bool checkPermissionForCamera =
1726 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001727 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001728 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001729 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001730 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1731 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001732 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001733 }
1734
Svet Ganova453d0d2018-01-11 15:37:58 -08001735 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001736 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001737 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001738 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1739 clientPid, clientUid);
1740 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001741 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1742 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001743 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001744 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001745 }
1746
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001747 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1748 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1749 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1750 if ((!isAutomotivePrivilegedClient(callingUid) ||
1751 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1752 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001753 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1754 return STATUS_ERROR_FMT(ERROR_DISABLED,
1755 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001756 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001757 }
1758
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001759 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1760 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001761 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001762 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001763
Ruben Brunk6267b532015-04-30 17:44:07 -07001764 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001765
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001766 // For non-system clients : Only allow clients who are being used by the current foreground
1767 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001768 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001769 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001770 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1771 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001772 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001773 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1774 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001775 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001776 }
1777
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001778 if (flags::camera_hsum_permission()) {
1779 // If the System User tries to access the camera when the device is running in
1780 // headless system user mode, ensure that client has the required permission
1781 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001782 if (isHeadlessSystemUserMode()
1783 && (clientUserId == USER_SYSTEM)
1784 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001785 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1786 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1787 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1788 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001789 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001790 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001791 }
1792
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001793 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001794}
1795
Austin Borgered99f642023-06-01 16:51:35 -07001796status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001797 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001798 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001799 if (cameraState == nullptr) {
1800 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001801 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001802 return -ENODEV;
1803 }
1804
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001805 StatusInternal currentStatus = cameraState->getStatus();
1806 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001807 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001808 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001809 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001810 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001811 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001812 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001813 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001814 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001815
Ruben Brunkcc776712015-02-17 20:18:47 -08001816 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001817}
1818
Ruben Brunkcc776712015-02-17 20:18:47 -08001819void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001820 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001821
Ruben Brunkcc776712015-02-17 20:18:47 -08001822 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001823 auto clientDescriptor =
1824 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001825 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001826 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1827
1828 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001829 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001830
1831 if (evicted.size() > 0) {
1832 // This should never happen - clients should already have been removed in disconnect
1833 for (auto& i : evicted) {
1834 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001835 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001836 }
1837
1838 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1839 __FUNCTION__);
1840 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001841
1842 // And register a death notification for the client callback. Do
1843 // this last to avoid Binder policy where a nested Binder
1844 // transaction might be pre-empted to service the client death
1845 // notification if the client process dies before linkToDeath is
1846 // invoked.
1847 sp<IBinder> remoteCallback = client->getRemote();
1848 if (remoteCallback != nullptr) {
1849 remoteCallback->linkToDeath(this);
1850 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001851}
1852
Austin Borgered99f642023-06-01 16:51:35 -07001853status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1854 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1855 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 /*out*/
1857 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001858 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001859 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001860 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001861 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 DescriptorPtr clientDescriptor;
1863 {
1864 if (effectiveApiLevel == API_1) {
1865 // If we are using API1, any existing client for this camera ID with the same remote
1866 // should be returned rather than evicted to allow MediaRecorder to work properly.
1867
1868 auto current = mActiveClientManager.get(cameraId);
1869 if (current != nullptr) {
1870 auto clientSp = current->getValue();
1871 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001872 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001873 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001874 " API level, evicting prior client...");
1875 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001877 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001878 *client = clientSp;
1879 return NO_ERROR;
1880 }
1881 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001882 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001883 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001884
Ruben Brunkcc776712015-02-17 20:18:47 -08001885 // Get state for the given cameraId
1886 auto state = getCameraState(cameraId);
1887 if (state == nullptr) {
1888 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001889 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001890 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001891 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001892 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001893
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001894 sp<IServiceManager> sm = defaultServiceManager();
1895 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001896 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001897 // If processinfo service is not available and the client is automotive privileged
1898 // client used for safety critical uses cases such as rear-view and surround-view which
1899 // needs to be available before android boot completes, then use the hardcoded values
1900 // for the process state and priority score. As this scenario is before android system
1901 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1902 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1903 // visible on the top.
1904 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1905 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1906 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1907 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1908 } else {
1909 // Get current active client PIDs
1910 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1911 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001912
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001913 std::vector<int> priorityScores(ownerPids.size());
1914 std::vector<int> states(ownerPids.size());
1915
1916 // Get priority scores of all active PIDs
1917 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1918 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1919 if (err != OK) {
1920 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1921 return err;
1922 }
1923
1924 // Update all active clients' priorities
1925 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1926 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1927 pidToPriorityMap.emplace(ownerPids[i],
1928 resource_policy::ClientPriority(priorityScores[i], states[i],
1929 /* isVendorClient won't get copied over*/ false,
1930 /* oomScoreOffset won't get copied over*/ 0));
1931 }
1932 mActiveClientManager.updatePriorities(pidToPriorityMap);
1933
1934 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1935 int32_t actualState = states[states.size() - 1];
1936
1937 // Make descriptor for incoming client. We store the oomScoreOffset
1938 // since we might need it later on new handleEvictionsLocked and
1939 // ProcessInfoService would not take that into account.
1940 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1941 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1942 state->getConflicting(), actualScore, clientPid, actualState,
1943 oomScoreOffset, systemNativeClient);
1944 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001945
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001946 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1947
Ruben Brunkcc776712015-02-17 20:18:47 -08001948 // Find clients that would be evicted
1949 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1950
1951 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1952 // background, so we cannot do evictions
1953 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1954 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1955 " priority).", clientPid);
1956
1957 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001958 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001959 auto incompatibleClients =
1960 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1961
Austin Borgered99f642023-06-01 16:51:35 -07001962 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1963 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1964 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001965 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001966
1967 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001968 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001969 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001970 i->getKey().c_str(),
1971 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001972 i->getOwnerId(), i->getPriority().getScore(),
1973 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001974 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07001975 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
1976 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001977 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001978 }
1979
1980 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001981 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001982 mEventLog.add(msg);
1983
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001984 auto current = mActiveClientManager.get(cameraId);
1985 if (current != nullptr) {
1986 return -EBUSY; // CAMERA_IN_USE
1987 } else {
1988 return -EUSERS; // MAX_CAMERAS_IN_USE
1989 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001990 }
1991
1992 for (auto& i : evicted) {
1993 sp<BasicClient> clientSp = i->getValue();
1994 if (clientSp.get() == nullptr) {
1995 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
1996
1997 // TODO: Remove this
1998 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
1999 __FUNCTION__);
2000 mActiveClientManager.remove(i);
2001 continue;
2002 }
2003
2004 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002005 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002006 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002007
Ruben Brunkcc776712015-02-17 20:18:47 -08002008 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002009 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002010 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2011 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002012 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002013 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002014 i->getPriority().getState(), cameraId.c_str(),
2015 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002016 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002017
2018 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002019 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002020 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002021 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002022 }
2023
Ruben Brunkcc776712015-02-17 20:18:47 -08002024 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2025 // other clients from connecting in mServiceLockWrapper if held
2026 mServiceLock.unlock();
2027
2028 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002029 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002030
2031 // Destroy evicted clients
2032 for (auto& i : evictedClients) {
2033 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002034 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002035 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002036
Austin Borger22c5c852024-03-08 13:31:36 -08002037 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002038
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002039 for (const auto& i : evictedClients) {
2040 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002041 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002042 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2043 if (ret == TIMED_OUT) {
2044 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002045 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2046 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002047 return -EBUSY;
2048 }
2049 if (ret != NO_ERROR) {
2050 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002051 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2052 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002053 return ret;
2054 }
2055 }
2056
2057 evictedClients.clear();
2058
Ruben Brunkcc776712015-02-17 20:18:47 -08002059 // Once clients have been disconnected, relock
2060 mServiceLock.lock();
2061
2062 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2063 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2064 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002065 }
2066
Ruben Brunkcc776712015-02-17 20:18:47 -08002067 *partial = clientDescriptor;
2068 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002069}
2070
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002071Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002072 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002073 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002074 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002075 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002076 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002077 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002078 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002079 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002080 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002081 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002082
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002083 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002084 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002085
malikakashedb38962023-09-06 00:03:35 +00002086 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
2087 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08002088 getCallingUid());
malikakashedb38962023-09-06 00:03:35 +00002089
Ruben Brunkcc776712015-02-17 20:18:47 -08002090 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002091 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2092 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002093 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002094 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002095
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002096 if(!ret.isOk()) {
Austin Borger22c5c852024-03-08 13:31:36 -08002097 logRejected(cameraIdStr, getCallingPid(), clientPackageName,
Austin Borgered99f642023-06-01 16:51:35 -07002098 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002099 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002100 }
2101
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002102 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002103
2104 const sp<IServiceManager> sm(defaultServiceManager());
2105 const auto& mActivityManager = getActivityManager();
2106 if (mActivityManager) {
2107 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002108 getCallingUid(),
2109 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002110 }
2111
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002112 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002113}
2114
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002115bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2116 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002117 // If the client is not a vendor client, don't add listener if
2118 // a) the camera is a publicly hidden secure camera OR
2119 // b) the camera is a system only camera and the client doesn't
2120 // have android.permission.SYSTEM_CAMERA permissions.
2121 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2122 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002123 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002124 return true;
2125 }
2126 return false;
2127}
2128
Austin Borgered99f642023-06-01 16:51:35 -07002129bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002130 // Rules for rejection:
2131 // 1) If cameraserver tries to access this camera device, accept the
2132 // connection.
2133 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002134 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002135 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2136 // and the serving thread is a non hwbinder thread, the client must have
2137 // android.permission.SYSTEM_CAMERA permissions to connect.
2138
Austin Borger22c5c852024-03-08 13:31:36 -08002139 int cPid = getCallingPid();
2140 int cUid = getCallingUid();
2141 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002142 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2143 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002144 // This isn't a known camera ID, so it's not a system camera
2145 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2146 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002147 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002148
2149 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002150 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002151 return false;
2152 }
2153 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002154 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002155 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2156 return true;
2157 }
2158 // (3) Here we only check for permissions if it is a system only camera device. This is since
2159 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2160 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2161 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002162 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002163 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002164 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2165 cameraId.c_str());
2166 return true;
2167 }
2168
2169 return false;
2170}
2171
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002172Status CameraService::connectDevice(
2173 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002174 const std::string& unresolvedCameraId,
2175 const std::string& clientPackageName,
2176 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002177 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002178 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08002179 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002180 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002181
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002182 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002183 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002184 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002185 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002186 int callingPid = getCallingPid();
2187 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002188 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002189 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002190 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002191 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002192 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002193 }
Austin Borger249e6592024-03-10 22:28:11 -07002194
malikakashedb38962023-09-06 00:03:35 +00002195 const std::string cameraId = resolveCameraId(
2196 unresolvedCameraId,
Austin Borger249e6592024-03-10 22:28:11 -07002197 callingUid,
malikakashedb38962023-09-06 00:03:35 +00002198 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002199
2200 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002201 std::string msg =
2202 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2203 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2204 cameraId.c_str());
2205 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2206 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002207 }
2208
Austin Borger9bfa0a72022-08-03 17:50:40 -07002209 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002210 if (clientUid == USE_CALLING_UID) {
2211 clientUserId = multiuser_get_user_id(callingUid);
2212 }
2213
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002214 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2215 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002216 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2217 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002218 std::string msg = "Camera disabled by device policy";
2219 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2220 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002221 }
2222
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002223 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002224 if (oomScoreOffset > 0
2225 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002226 callingUid)
2227 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002228 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002229 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002230 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2231 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2232 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002233 }
2234
Austin Borgered99f642023-06-01 16:51:35 -07002235 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2236 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002237 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002238 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002239 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002240
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002241 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002242 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002243 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002244 }
2245
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002247 Mutex::Autolock lock(mServiceLock);
2248
2249 // Clear the previous cached logs and reposition the
2250 // file offset to beginning of the file to log new data.
2251 // If either truncate or lseek fails, close the previous file and create a new one.
2252 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2253 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2254 // Close the previous memfd.
2255 close(mMemFd);
2256 // If failure to wipe the data, then create a new file and
2257 // assign the new value to mMemFd.
2258 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2259 if (mMemFd == -1) {
2260 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2261 }
2262 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002263 const sp<IServiceManager> sm(defaultServiceManager());
2264 const auto& mActivityManager = getActivityManager();
2265 if (mActivityManager) {
2266 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002267 callingUid,
2268 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002269 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002270 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002271}
2272
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002273bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2274 int callingPid, int callingUid) {
2275 if (!isAutomotiveDevice()) {
2276 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2277 }
2278
2279 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2280 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2281 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2282 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2283 "using camera %s", callingUid, cam_id.c_str());
2284 return false;
2285 }
2286
2287 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2288 return true;
2289 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2290 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002291 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2292 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002293 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2294 return false;
2295 } else {
2296 return true;
2297 }
2298 }
2299 return false;
2300}
2301
Austin Borgered99f642023-06-01 16:51:35 -07002302std::string CameraService::getPackageNameFromUid(int clientUid) {
2303 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002304
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002305 sp<IPermissionController> permCtrl;
2306 if (flags::cache_permission_services()) {
2307 permCtrl = getPermissionController();
2308 } else {
2309 sp<IServiceManager> sm = defaultServiceManager();
2310#pragma clang diagnostic push
2311#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2312 // Using deprecated function to preserve functionality until the
2313 // cache_permission_services flag is removed.
2314 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2315#pragma clang diagnostic pop
2316 if (binder == 0) {
2317 ALOGE("Cannot get permission service");
2318 permCtrl = nullptr;
2319 } else {
2320 permCtrl = interface_cast<IPermissionController>(binder);
2321 }
2322 }
2323
2324 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002325 // Return empty package name and the further interaction
2326 // with camera will likely fail
2327 return packageName;
2328 }
2329
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002330 Vector<String16> packages;
2331
2332 permCtrl->getPackagesForUid(clientUid, packages);
2333
2334 if (packages.isEmpty()) {
2335 ALOGE("No packages for calling UID %d", clientUid);
2336 // Return empty package name and the further interaction
2337 // with camera will likely fail
2338 return packageName;
2339 }
2340
2341 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002342 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002343
2344 return packageName;
2345}
2346
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002347template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002348Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2349 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2350 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002351 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002352 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002353 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002354 binder::Status ret = binder::Status::ok();
2355
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002356 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002357 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002358 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002359 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002360 if (clientPackageNameMaybe.size() <= 0) {
2361 // NDK calls don't come with package names, but we need one for various cases.
2362 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2363 // do exist. For all authentication cases, all packages under the same UID get the
2364 // same permissions, so picking any associated package name is sufficient. For some
2365 // other cases, this may give inaccurate names for clients in logs.
2366 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002367 clientPackageName = getPackageNameFromUid(packageUid);
2368 } else {
2369 clientPackageName = clientPackageNameMaybe;
2370 }
2371
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002372 int originalClientPid = 0;
2373
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002374 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002375 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002376 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002377 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002378 static_cast<int>(effectiveApiLevel));
2379
Shuzhen Wang316781a2020-08-18 18:11:01 -07002380 nsecs_t openTimeNs = systemTime();
2381
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002382 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002383 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002384 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002385
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002386 {
2387 // Acquire mServiceLock and prevent other clients from connecting
2388 std::unique_ptr<AutoConditionLock> lock =
2389 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2390
2391 if (lock == nullptr) {
2392 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2393 , clientPid);
2394 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2395 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002396 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002397 }
2398
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002399 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002400 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002401 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2402 return ret;
2403 }
2404
2405 // Check the shim parameters after acquiring lock, if they have already been updated and
2406 // we were doing a shim update, return immediately
2407 if (shimUpdateOnly) {
2408 auto cameraState = getCameraState(cameraId);
2409 if (cameraState != nullptr) {
2410 if (!cameraState->getShimParams().isEmpty()) return ret;
2411 }
2412 }
2413
2414 status_t err;
2415
2416 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002417 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002418 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002419 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2420 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002421 switch (err) {
2422 case -ENODEV:
2423 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2424 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002425 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002426 case -EBUSY:
2427 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2428 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002429 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002430 case -EUSERS:
2431 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2432 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002433 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002434 default:
2435 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2436 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002437 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002438 }
2439 }
2440
2441 if (clientTmp.get() != nullptr) {
2442 // Handle special case for API1 MediaRecorder where the existing client is returned
2443 device = static_cast<CLIENT*>(clientTmp.get());
2444 return ret;
2445 }
2446
2447 // give flashlight a chance to close devices if necessary.
2448 mFlashlight->prepareDeviceOpen(cameraId);
2449
Austin Borger18b30a72022-10-27 12:20:29 -07002450 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002451 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002452 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2453 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002454 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002455 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002456 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002457 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002458 }
2459
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002460 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002461 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002462 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002463 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002464 clientFeatureId, cameraId, api1CameraId, facing,
2465 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002466 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002467 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002468 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002469 return ret;
2470 }
2471 client = static_cast<CLIENT*>(tmp.get());
2472
2473 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2474 __FUNCTION__);
2475
Austin Borgered99f642023-06-01 16:51:35 -07002476 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002477 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002478 if (err != OK) {
2479 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002480 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002481 mServiceLock.unlock();
2482 client->disconnect();
2483 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002484 switch(err) {
2485 case BAD_VALUE:
2486 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002487 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002488 case -EBUSY:
2489 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002490 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002491 case -EUSERS:
2492 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2493 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002494 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002495 case PERMISSION_DENIED:
2496 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002497 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002498 case -EACCES:
2499 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002500 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002501 case -ENODEV:
2502 default:
2503 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002504 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002505 strerror(-err), err);
2506 }
2507 }
2508
2509 // Update shim paremeters for legacy clients
2510 if (effectiveApiLevel == API_1) {
2511 // Assume we have always received a Client subclass for API1
2512 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2513 String8 rawParams = shimClient->getParameters();
2514 CameraParameters params(rawParams);
2515
2516 auto cameraState = getCameraState(cameraId);
2517 if (cameraState != nullptr) {
2518 cameraState->setShimParams(params);
2519 } else {
2520 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002521 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002522 }
2523 }
2524
Ravneetaeb20dc2022-03-30 05:33:03 +00002525 // Enable/disable camera service watchdog
2526 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2527
Emilian Peev6d45db82024-01-18 20:11:54 +00002528 CameraMetadata chars;
2529 bool rotateAndCropSupported = true;
2530 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2531 &chars, overrideToPortrait);
2532 if (err == OK) {
2533 auto availableRotateCropEntry = chars.find(
2534 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2535 if (availableRotateCropEntry.count <= 1) {
2536 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002537 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002538 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002539 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2540 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002541 }
2542
Emilian Peev6d45db82024-01-18 20:11:54 +00002543 if (rotateAndCropSupported) {
2544 // Set rotate-and-crop override behavior
2545 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2546 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2547 } else if (overrideToPortrait && portraitRotation != 0) {
2548 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2549 switch (portraitRotation) {
2550 case 90:
2551 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2552 break;
2553 case 180:
2554 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2555 break;
2556 case 270:
2557 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2558 break;
2559 default:
2560 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2561 break;
2562 }
2563 client->setRotateAndCropOverride(rotateAndCropMode);
2564 } else {
2565 client->setRotateAndCropOverride(
2566 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2567 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2568 }
2569 }
2570
2571 bool autoframingSupported = true;
2572 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2573 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2574 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2575 autoframingSupported = false;
2576 }
2577
2578 if (autoframingSupported) {
2579 // Set autoframing override behaviour
2580 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2581 client->setAutoframingOverride(mOverrideAutoframingMode);
2582 } else {
2583 client->setAutoframingOverride(
2584 mCameraServiceProxyWrapper->getAutoframingOverride(
2585 clientPackageName));
2586 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002587 }
2588
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002589 bool isCameraPrivacyEnabled;
2590 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002591 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002592 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2593 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2594 } else {
2595 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002596 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002597 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002598
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002599 if (client->supportsCameraMute()) {
2600 client->setCameraMute(
2601 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2602 } else if (isCameraPrivacyEnabled) {
2603 // no camera mute supported, but privacy is on! => disconnect
2604 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2605 client->getPackageName().c_str(), cameraId.c_str());
2606 // Do not hold mServiceLock while disconnecting clients, but
2607 // retain the condition blocking other clients from connecting
2608 // in mServiceLockWrapper if held.
2609 mServiceLock.unlock();
2610 // Clear caller identity temporarily so client disconnect PID
2611 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002612 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002613 // Note AppOp to trigger the "Unblock" dialog
2614 client->noteAppOp();
2615 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002616 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002617 // Reacquire mServiceLock
2618 mServiceLock.lock();
2619
2620 return STATUS_ERROR_FMT(ERROR_DISABLED,
2621 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002622 }
2623
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002624 if (shimUpdateOnly) {
2625 // If only updating legacy shim parameters, immediately disconnect client
2626 mServiceLock.unlock();
2627 client->disconnect();
2628 mServiceLock.lock();
2629 } else {
2630 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002631 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002632 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002633
2634 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002635 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002636 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002637 } // lock is destroyed, allow further connect calls
2638
2639 // Important: release the mutex here so the client can call back into the service from its
2640 // destructor (can be at the end of the call)
2641 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002642
2643 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002644 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002645 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002646
Cliff Wud3a05312021-04-26 23:07:31 +08002647 {
2648 Mutex::Autolock lock(mInjectionParametersLock);
2649 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2650 mInjectionInitPending = false;
2651 status_t res = NO_ERROR;
2652 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2653 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002654 sp<BasicClient> clientSp = clientDescriptor->getValue();
2655 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2656 if(res != OK) {
2657 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2658 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002659 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002660 }
2661 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002662 if (res != OK) {
2663 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2664 }
2665 } else {
2666 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002667 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002668 res = NO_INIT;
2669 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2670 }
2671 }
2672 }
2673
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002674 return ret;
2675}
2676
Austin Borgered99f642023-06-01 16:51:35 -07002677status_t CameraService::addOfflineClient(const std::string &cameraId,
2678 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002679 if (offlineClient.get() == nullptr) {
2680 return BAD_VALUE;
2681 }
2682
2683 {
2684 // Acquire mServiceLock and prevent other clients from connecting
2685 std::unique_ptr<AutoConditionLock> lock =
2686 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2687
2688 if (lock == nullptr) {
2689 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2690 , __FUNCTION__, offlineClient->getClientPid());
2691 return TIMED_OUT;
2692 }
2693
2694 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2695 if (onlineClientDesc.get() == nullptr) {
2696 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2697 cameraId.c_str());
2698 return BAD_VALUE;
2699 }
2700
2701 // Offline clients do not evict or conflict with other online devices. Resource sharing
2702 // conflicts are handled by the camera provider which will either succeed or fail before
2703 // reaching this method.
2704 const auto& onlinePriority = onlineClientDesc->getPriority();
2705 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2706 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002707 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002708 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002709 // native clients don't have offline processing support.
2710 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002711 if (offlineClientDesc == nullptr) {
2712 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2713 return BAD_VALUE;
2714 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002715
2716 // Allow only one offline device per camera
2717 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2718 if (!incompatibleClients.empty()) {
2719 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2720 return BAD_VALUE;
2721 }
2722
Austin Borgered99f642023-06-01 16:51:35 -07002723 std::string monitorTags = isClientWatched(offlineClient.get())
2724 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002725 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002726 if (err != OK) {
2727 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2728 return err;
2729 }
2730
2731 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2732 if (evicted.size() > 0) {
2733 for (auto& i : evicted) {
2734 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002735 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002736 }
2737
2738 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2739 "properly", __FUNCTION__);
2740
2741 return BAD_VALUE;
2742 }
2743
2744 logConnectedOffline(offlineClientDesc->getKey(),
2745 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002746 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002747
2748 sp<IBinder> remoteCallback = offlineClient->getRemote();
2749 if (remoteCallback != nullptr) {
2750 remoteCallback->linkToDeath(this);
2751 }
2752 } // lock is destroyed, allow further connect calls
2753
2754 return OK;
2755}
2756
Austin Borgered99f642023-06-01 16:51:35 -07002757Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger1c1bee02023-06-01 16:51:35 -07002758 int32_t torchStrength, const sp<IBinder>& clientBinder) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002759 Mutex::Autolock lock(mServiceLock);
2760
2761 ATRACE_CALL();
2762 if (clientBinder == nullptr) {
2763 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2764 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2765 "Torch client binder in null.");
2766 }
2767
Austin Borger22c5c852024-03-08 13:31:36 -08002768 int uid = getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002769 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002770 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002771 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002772 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002773 }
2774
2775 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002776 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002777 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002778 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002779 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002780 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002781 }
2782
2783 StatusInternal cameraStatus = state->getStatus();
2784 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2785 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002786 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002787 (int)cameraStatus);
2788 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002789 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002790 }
2791
2792 {
2793 Mutex::Autolock al(mTorchStatusMutex);
2794 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002795 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002796 if (err != OK) {
2797 if (err == NAME_NOT_FOUND) {
2798 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002799 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002800 }
2801 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002802 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002803 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2804 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002805 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002806 }
2807
2808 if (status == TorchModeStatus::NOT_AVAILABLE) {
2809 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2810 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002811 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002812 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2813 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002814 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002815 } else {
2816 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002817 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002818 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2819 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002820 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002821 }
2822 }
2823 }
2824
2825 {
2826 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002827 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002828 }
2829 // Check if the current torch strength level is same as the new one.
2830 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002831 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002832
Austin Borgered99f642023-06-01 16:51:35 -07002833 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002834
2835 if (err != OK) {
2836 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002837 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002838 switch (err) {
2839 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002840 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2841 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002842 errorCode = ERROR_ILLEGAL_ARGUMENT;
2843 break;
2844 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002845 msg = fmt::sprintf("Camera \"%s\" is in use",
2846 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002847 errorCode = ERROR_CAMERA_IN_USE;
2848 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002849 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002850 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002851 "valid range.", torchStrength);
2852 errorCode = ERROR_ILLEGAL_ARGUMENT;
2853 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002854 default:
Austin Borgered99f642023-06-01 16:51:35 -07002855 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002856 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002857 }
Austin Borgered99f642023-06-01 16:51:35 -07002858 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2859 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002860 }
2861
2862 {
2863 // update the link to client's death
2864 // Store the last client that turns on each camera's torch mode.
2865 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002866 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002867 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002868 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002869 } else {
2870 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2871 mTorchClientMap.replaceValueAt(index, clientBinder);
2872 }
2873 clientBinder->linkToDeath(this);
2874 }
2875
Austin Borger22c5c852024-03-08 13:31:36 -08002876 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002878 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002879 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002880 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002881 }
2882 return Status::ok();
2883}
2884
malikakash73125c62023-07-21 22:44:34 +00002885Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002886 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002887 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002888
2889 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002890 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002891 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002892 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2893 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002894 }
2895
Austin Borger22c5c852024-03-08 13:31:36 -08002896 int uid = getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002897 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002898
Austin Borgered99f642023-06-01 16:51:35 -07002899 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002900 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002901 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002902 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002903 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002904 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002905 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002906 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002907 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002908 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002909 }
2910
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002911 StatusInternal cameraStatus = state->getStatus();
2912 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002913 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002914 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2915 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002916 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002917 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002918 }
2919
2920 {
2921 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002922 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002923 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002924 if (err != OK) {
2925 if (err == NAME_NOT_FOUND) {
2926 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002927 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002928 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002929 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002930 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002931 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002932 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002933 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002934 }
2935
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002936 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002937 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002938 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002939 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002940 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2941 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002942 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002943 } else {
2944 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002945 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002946 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2947 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002948 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002949 }
2950 }
2951 }
2952
Ruben Brunk99e69712015-05-26 17:25:07 -07002953 {
2954 // Update UID map - this is used in the torch status changed callbacks, so must be done
2955 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002956 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002957 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002958 }
2959
Austin Borgered99f642023-06-01 16:51:35 -07002960 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002961
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002962 if (err != OK) {
2963 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002964 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002965 switch (err) {
2966 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002967 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2968 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002969 errorCode = ERROR_ILLEGAL_ARGUMENT;
2970 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002971 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002972 msg = fmt::sprintf("Camera \"%s\" is in use",
2973 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002974 errorCode = ERROR_CAMERA_IN_USE;
2975 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002976 default:
Austin Borgered99f642023-06-01 16:51:35 -07002977 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002978 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002979 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002980 errorCode = ERROR_INVALID_OPERATION;
2981 }
Austin Borgered99f642023-06-01 16:51:35 -07002982 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2983 logServiceError(msg, errorCode);
2984 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002985 }
2986
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002987 {
2988 // update the link to client's death
2989 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002990 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002991 if (enabled) {
2992 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002993 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002994 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07002995 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002996 mTorchClientMap.replaceValueAt(index, clientBinder);
2997 }
2998 clientBinder->linkToDeath(this);
2999 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003000 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003001 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003002 }
3003
Austin Borger22c5c852024-03-08 13:31:36 -08003004 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003005 std::string torchState = enabled ? "on" : "off";
3006 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3007 torchState.c_str(), clientPid);
3008 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003009 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003010}
3011
Austin Borgered99f642023-06-01 16:51:35 -07003012void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3013 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3014 mTorchUidMap[cameraId].first = uid;
3015 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003016 } else {
3017 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003018 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003019 }
3020}
3021
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003022Status CameraService::notifySystemEvent(int32_t eventId,
3023 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003024 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003025 const int selfPid = getpid();
3026
3027 // Permission checks
3028 if (pid != selfPid) {
3029 // Ensure we're being called by system_server, or similar process with
3030 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003031 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003032 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003033 ALOGE("Permission Denial: cannot send updates to camera service about system"
3034 " events from pid=%d, uid=%d", pid, uid);
3035 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003036 "No permission to send updates to camera service about system events"
3037 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003038 }
3039 }
3040
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003041 ATRACE_CALL();
3042
Ruben Brunk36597b22015-03-20 22:15:57 -07003043 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003044 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003045 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003046 // from a system server crash
3047 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003048 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003049 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003050 break;
3051 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003052 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3053 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003054 if (args.size() != 1) {
3055 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3056 "USB Device Event requires 1 argument");
3057 }
3058
Valentin Iftime29e2e152021-08-13 15:17:33 +02003059 // Notify CameraProviderManager for lazy HALs
3060 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3061 std::to_string(args[0]));
3062 break;
3063 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003064 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003065 default: {
3066 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3067 eventId);
3068 break;
3069 }
3070 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003072}
3073
Emilian Peev53722fa2019-02-22 17:47:20 -08003074void CameraService::notifyMonitoredUids() {
3075 Mutex::Autolock lock(mStatusListenerLock);
3076
3077 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003078 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003079 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3080 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003081 }
3082}
3083
Austin Borgerdddb7552023-03-30 17:53:01 -07003084void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3085 Mutex::Autolock lock(mStatusListenerLock);
3086
3087 for (const auto& it : mListenerList) {
3088 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3089 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3090 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3091 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3092 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3093 }
3094 }
3095}
3096
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003097Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003098 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003099 const int selfPid = getpid();
3100
3101 // Permission checks
3102 if (pid != selfPid) {
3103 // Ensure we're being called by system_server, or similar process with
3104 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003105 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003106 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003107 ALOGE("Permission Denial: cannot send updates to camera service about device"
3108 " state changes from pid=%d, uid=%d", pid, uid);
3109 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3110 "No permission to send updates to camera service about device state"
3111 " changes from pid=%d, uid=%d", pid, uid);
3112 }
3113 }
3114
3115 ATRACE_CALL();
3116
Austin Borger18b30a72022-10-27 12:20:29 -07003117 {
3118 Mutex::Autolock lock(mServiceLock);
3119 mDeviceState = newState;
3120 }
3121
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003122 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003123
3124 return Status::ok();
3125}
3126
Emilian Peev8b64f282021-03-25 16:49:57 -07003127Status CameraService::notifyDisplayConfigurationChange() {
3128 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003129 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003130 const int selfPid = getpid();
3131
3132 // Permission checks
3133 if (callingPid != selfPid) {
3134 // Ensure we're being called by system_server, or similar process with
3135 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003136 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003137 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003138 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3139 " changes from pid=%d, uid=%d", callingPid, uid);
3140 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3141 "No permission to send updates to camera service about orientation"
3142 " changes from pid=%d, uid=%d", callingPid, uid);
3143 }
3144 }
3145
3146 Mutex::Autolock lock(mServiceLock);
3147
3148 // Don't do anything if rotate-and-crop override via cmd is active
3149 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3150
3151 const auto clients = mActiveClientManager.getAll();
3152 for (auto& current : clients) {
3153 if (current != nullptr) {
3154 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003155 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3156 basicClient->setRotateAndCropOverride(
3157 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3158 basicClient->getPackageName(),
3159 basicClient->getCameraFacing(),
3160 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003161 }
3162 }
3163 }
3164
3165 return Status::ok();
3166}
3167
3168Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003169 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3170 ATRACE_CALL();
3171 if (!concurrentCameraIds) {
3172 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3173 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3174 }
3175
3176 if (!mInitialized) {
3177 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003178 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003179 return STATUS_ERROR(ERROR_DISCONNECTED,
3180 "Camera subsystem is not available");
3181 }
3182 // First call into the provider and get the set of concurrent camera
3183 // combinations
3184 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003185 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003186 for (auto &combination : concurrentCameraCombinations) {
3187 std::vector<std::string> validCombination;
3188 for (auto &cameraId : combination) {
3189 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003190 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003191 if (state == nullptr) {
3192 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3193 continue;
3194 }
3195 StatusInternal status = state->getStatus();
3196 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3197 continue;
3198 }
Austin Borgered99f642023-06-01 16:51:35 -07003199 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003200 continue;
3201 }
3202 validCombination.push_back(cameraId);
3203 }
3204 if (validCombination.size() != 0) {
3205 concurrentCameraIds->push_back(std::move(validCombination));
3206 }
3207 }
3208 return Status::ok();
3209}
3210
3211Status CameraService::isConcurrentSessionConfigurationSupported(
3212 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003213 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003214 if (!isSupported) {
3215 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3216 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3217 }
3218
3219 if (!mInitialized) {
3220 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3221 return STATUS_ERROR(ERROR_DISCONNECTED,
3222 "Camera subsystem is not available");
3223 }
3224
3225 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003226 int callingPid = getCallingPid();
3227 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003228 bool hasCameraPermission = ((callingPid == getpid()) ||
3229 hasPermissionsForCamera(callingPid, callingUid));
3230 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003231 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3232 "android.permission.CAMERA needed to call"
3233 "isConcurrentSessionConfigurationSupported");
3234 }
3235
3236 status_t res =
3237 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003238 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3239 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003240 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003241 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003242 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003243 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3244 "support %s (%d)", strerror(-res), res);
3245 }
3246 return Status::ok();
3247}
3248
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003249Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3250 /*out*/
3251 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003252 return addListenerHelper(listener, cameraStatuses);
3253}
3254
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003255binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3256 std::vector<hardware::CameraStatus>* cameraStatuses) {
3257 return addListenerHelper(listener, cameraStatuses, false, true);
3258}
3259
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003260Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3261 /*out*/
3262 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003263 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003264
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003265 ATRACE_CALL();
3266
Igor Murashkinbfc99152013-02-27 12:55:20 -08003267 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003268
Ruben Brunk3450ba72015-06-16 11:00:37 -07003269 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003270 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003271 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003272 }
3273
Austin Borger22c5c852024-03-08 13:31:36 -08003274 auto clientPid = getCallingPid();
3275 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003276 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003277
Igor Murashkinbfc99152013-02-27 12:55:20 -08003278 Mutex::Autolock lock(mServiceLock);
3279
Ruben Brunkcc776712015-02-17 20:18:47 -08003280 {
3281 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003282 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003283 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003284 ALOGW("%s: Tried to add listener %p which was already subscribed",
3285 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003286 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003287 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003288 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003289
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003290 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003291 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3292 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003293 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003294 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003295 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003296 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003297 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3298 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3299 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003300 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003301 // The listener still needs to be added to the list of listeners, regardless of what
3302 // permissions the listener process has / whether it is a vendor listener. Since it might be
3303 // eligible to listen to other camera ids.
3304 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003305 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003306 }
3307
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003308 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003309 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003310 Mutex::Autolock lock(mCameraStatesLock);
3311 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003312 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003313 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003314 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003315 }
3316 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003317 // Remove the camera statuses that should be hidden from the client, we do
3318 // this after collecting the states in order to avoid holding
3319 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3320 // the same time.
3321 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3322 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3323 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3324 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3325 ALOGE("%s: Invalid camera id %s, skipping status update",
3326 __FUNCTION__, s.cameraId.c_str());
3327 return true;
3328 }
3329 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3330 clientUid);}), cameraStatuses->end());
3331
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003332 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003333 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003334 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003335 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003336 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003337
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003338 /*
3339 * Immediately signal current torch status to this listener only
3340 * This may be a subset of all the devices, so don't include it in the response directly
3341 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003342 {
3343 Mutex::Autolock al(mTorchStatusMutex);
3344 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003345 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003346 // The camera id is visible to the client. Fine to send torch
3347 // callback.
3348 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3349 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3350 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003351 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003352 }
3353
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003354 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003355}
Ruben Brunkcc776712015-02-17 20:18:47 -08003356
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003357Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003358 ATRACE_CALL();
3359
Igor Murashkinbfc99152013-02-27 12:55:20 -08003360 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3361
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003362 if (listener == 0) {
3363 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003364 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003365 }
3366
Igor Murashkinbfc99152013-02-27 12:55:20 -08003367 Mutex::Autolock lock(mServiceLock);
3368
Ruben Brunkcc776712015-02-17 20:18:47 -08003369 {
3370 Mutex::Autolock lock(mStatusListenerLock);
3371 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003372 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003373 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003374 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003375 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003376 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003377 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003378 }
3379 }
3380
3381 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3382 __FUNCTION__, listener.get());
3383
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003384 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003385}
3386
Austin Borgered99f642023-06-01 16:51:35 -07003387Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003388
3389 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003390 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3391
3392 if (parameters == NULL) {
3393 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003394 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003395 }
3396
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003397 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003398
3399 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003400 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003401 // Error logged by caller
3402 return ret;
3403 }
3404
3405 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003406
Austin Borgered99f642023-06-01 16:51:35 -07003407 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003408
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003409 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003410}
3411
Austin Borgered99f642023-06-01 16:51:35 -07003412Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003413 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003414 ATRACE_CALL();
3415
malikakashedb38962023-09-06 00:03:35 +00003416 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003417 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003418
Austin Borgered99f642023-06-01 16:51:35 -07003419 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003420
3421 switch (apiVersion) {
3422 case API_VERSION_1:
3423 case API_VERSION_2:
3424 break;
3425 default:
Austin Borgered99f642023-06-01 16:51:35 -07003426 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3427 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3428 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003429 }
3430
Austin Borger18b30a72022-10-27 12:20:29 -07003431 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003432 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003433 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003434 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3435 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3436 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003437 }
3438 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3439 int deviceVersion = deviceVersionAndTransport.first;
3440 switch (deviceVersion) {
3441 case CAMERA_DEVICE_API_VERSION_1_0:
3442 case CAMERA_DEVICE_API_VERSION_3_0:
3443 case CAMERA_DEVICE_API_VERSION_3_1:
3444 if (apiVersion == API_VERSION_2) {
3445 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003446 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003447 *isSupported = false;
3448 } else { // if (apiVersion == API_VERSION_1) {
3449 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003450 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003451 *isSupported = true;
3452 }
3453 break;
3454 case CAMERA_DEVICE_API_VERSION_3_2:
3455 case CAMERA_DEVICE_API_VERSION_3_3:
3456 case CAMERA_DEVICE_API_VERSION_3_4:
3457 case CAMERA_DEVICE_API_VERSION_3_5:
3458 case CAMERA_DEVICE_API_VERSION_3_6:
3459 case CAMERA_DEVICE_API_VERSION_3_7:
3460 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003461 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003462 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003463 break;
3464 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003465 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3466 deviceVersion, cameraId.c_str());
3467 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3468 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003469 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003470 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003471 } else {
3472 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003473 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003474 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003475}
3476
Austin Borgered99f642023-06-01 16:51:35 -07003477Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003478 /*out*/ bool *isSupported) {
3479 ATRACE_CALL();
3480
malikakashedb38962023-09-06 00:03:35 +00003481 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003482 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003483
Austin Borgered99f642023-06-01 16:51:35 -07003484 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3485 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003486
3487 return Status::ok();
3488}
3489
Cliff Wud8cae102021-03-11 01:37:42 +08003490Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003491 const std::string& packageName, const std::string& internalCamId,
3492 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003493 const sp<ICameraInjectionCallback>& callback,
3494 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003495 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003496 ATRACE_CALL();
3497
Austin Borgered99f642023-06-01 16:51:35 -07003498 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003499 const int pid = getCallingPid();
3500 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003501 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3502 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3503 "Permission Denial: no permission to inject camera");
3504 }
3505
3506 ALOGV(
3507 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3508 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003509 __FUNCTION__, packageName.c_str(),
3510 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003511
Cliff Wud3a05312021-04-26 23:07:31 +08003512 {
3513 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003514 mInjectionInternalCamId = internalCamId;
3515 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003516 mInjectionStatusListener->addListener(callback);
3517 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003518 status_t res = NO_ERROR;
3519 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3520 // If the client already exists, we can directly connect to the camera device through the
3521 // client's injectCamera(), otherwise we need to wait until the client is established
3522 // (execute connectHelper()) before injecting the camera to the camera device.
3523 if (clientDescriptor != nullptr) {
3524 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003525 sp<BasicClient> clientSp = clientDescriptor->getValue();
3526 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3527 if(res != OK) {
3528 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3529 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003530 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003531 }
3532 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003533 if(res != OK) {
3534 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3535 }
3536 } else {
3537 mInjectionInitPending = true;
3538 }
3539 }
Cliff Wud8cae102021-03-11 01:37:42 +08003540
Cliff Wud3a05312021-04-26 23:07:31 +08003541 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003542}
3543
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003544Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003545 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003546 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3547 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3548 return Status::ok();
3549}
3550
Ruben Brunkcc776712015-02-17 20:18:47 -08003551void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003552 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003553 for (auto& i : mActiveClientManager.getAll()) {
3554 auto clientSp = i->getValue();
3555 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003556 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003557 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003558 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003559 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003560 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003561}
3562
Ruben Brunkcc776712015-02-17 20:18:47 -08003563bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003564 bool ret = false;
3565 {
3566 // Acquire mServiceLock and prevent other clients from connecting
3567 std::unique_ptr<AutoConditionLock> lock =
3568 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003569
Igor Murashkin634a5152013-02-20 17:15:11 -08003570
Ruben Brunkcc776712015-02-17 20:18:47 -08003571 std::vector<sp<BasicClient>> evicted;
3572 for (auto& i : mActiveClientManager.getAll()) {
3573 auto clientSp = i->getValue();
3574 if (clientSp.get() == nullptr) {
3575 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3576 mActiveClientManager.remove(i);
3577 continue;
3578 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003579 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003580 mActiveClientManager.remove(i);
3581 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003582
Ruben Brunkcc776712015-02-17 20:18:47 -08003583 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003584 clientSp->notifyError(
3585 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003586 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003587 }
3588 }
3589
Ruben Brunkcc776712015-02-17 20:18:47 -08003590 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3591 // other clients from connecting in mServiceLockWrapper if held
3592 mServiceLock.unlock();
3593
Ruben Brunk36597b22015-03-20 22:15:57 -07003594 // Do not clear caller identity, remote caller should be client proccess
3595
Ruben Brunkcc776712015-02-17 20:18:47 -08003596 for (auto& i : evicted) {
3597 if (i.get() != nullptr) {
3598 i->disconnect();
3599 ret = true;
3600 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003601 }
3602
Ruben Brunkcc776712015-02-17 20:18:47 -08003603 // Reacquire mServiceLock
3604 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003605
Ruben Brunkcc776712015-02-17 20:18:47 -08003606 } // lock is destroyed, allow further connect calls
3607
3608 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003609}
3610
Ruben Brunkcc776712015-02-17 20:18:47 -08003611std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003612 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003613 std::shared_ptr<CameraState> state;
3614 {
3615 Mutex::Autolock lock(mCameraStatesLock);
3616 auto iter = mCameraStates.find(cameraId);
3617 if (iter != mCameraStates.end()) {
3618 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003619 }
3620 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003621 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003622}
3623
Austin Borgered99f642023-06-01 16:51:35 -07003624sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003625 // Remove from active clients list
3626 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3627 if (clientDescriptorPtr == nullptr) {
3628 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003629 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003630 return sp<BasicClient>{nullptr};
3631 }
3632
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003633 sp<BasicClient> client = clientDescriptorPtr->getValue();
3634 if (client.get() != nullptr) {
3635 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3636 }
3637 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003638}
3639
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003640void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003641 // Acquire mServiceLock and prevent other clients from connecting
3642 std::unique_ptr<AutoConditionLock> lock =
3643 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3644
Ruben Brunk6267b532015-04-30 17:44:07 -07003645 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003646 for (size_t i = 0; i < newUserIds.size(); i++) {
3647 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003648 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003649 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003650 return;
3651 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003652 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003653 }
3654
Ruben Brunka8ca9152015-04-07 14:23:40 -07003655
Ruben Brunk6267b532015-04-30 17:44:07 -07003656 if (newAllowedUsers == mAllowedUsers) {
3657 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3658 return;
3659 }
3660
3661 logUserSwitch(mAllowedUsers, newAllowedUsers);
3662
3663 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003664
3665 // Current user has switched, evict all current clients.
3666 std::vector<sp<BasicClient>> evicted;
3667 for (auto& i : mActiveClientManager.getAll()) {
3668 auto clientSp = i->getValue();
3669
3670 if (clientSp.get() == nullptr) {
3671 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3672 continue;
3673 }
3674
Ruben Brunk6267b532015-04-30 17:44:07 -07003675 // Don't evict clients that are still allowed.
3676 uid_t clientUid = clientSp->getClientUid();
3677 userid_t clientUserId = multiuser_get_user_id(clientUid);
3678 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3679 continue;
3680 }
3681
Ruben Brunk36597b22015-03-20 22:15:57 -07003682 evicted.push_back(clientSp);
3683
Ruben Brunk36597b22015-03-20 22:15:57 -07003684 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003685 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003686
Ruben Brunk36597b22015-03-20 22:15:57 -07003687 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003688 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003689 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003690 " to user switch.", i->getKey().c_str(),
3691 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003692 i->getOwnerId(), i->getPriority().getScore(),
3693 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003694
3695 }
3696
3697 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3698 // blocking other clients from connecting in mServiceLockWrapper if held.
3699 mServiceLock.unlock();
3700
3701 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003702 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003703
3704 for (auto& i : evicted) {
3705 i->disconnect();
3706 }
3707
Austin Borger22c5c852024-03-08 13:31:36 -08003708 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003709
3710 // Reacquire mServiceLock
3711 mServiceLock.lock();
3712}
Ruben Brunkcc776712015-02-17 20:18:47 -08003713
Austin Borgered99f642023-06-01 16:51:35 -07003714void CameraService::logEvent(const std::string &event) {
3715 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003716 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003717 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003718 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003719 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003720 mEventLog.add(msg);
3721 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3722 // Error event not added to the dumpsys log before
3723 mEventLog.add(msg);
3724 sServiceErrorEventSet.insert(msg);
3725 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003726}
3727
Austin Borgered99f642023-06-01 16:51:35 -07003728void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3729 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003730 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003731 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3732 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003733}
3734
Austin Borgered99f642023-06-01 16:51:35 -07003735void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3736 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003737 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003738 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3739 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003740}
3741
Austin Borgered99f642023-06-01 16:51:35 -07003742void CameraService::logConnected(const std::string &cameraId, int clientPid,
3743 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003744 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003745 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3746 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003747}
3748
Austin Borgered99f642023-06-01 16:51:35 -07003749void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3750 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003751 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003752 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3753 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003754}
3755
Austin Borgered99f642023-06-01 16:51:35 -07003756void CameraService::logRejected(const std::string &cameraId, int clientPid,
3757 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003758 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003759 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3760 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003761}
3762
Austin Borgered99f642023-06-01 16:51:35 -07003763void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3764 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003765 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003766 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3767 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003768}
3769
Ruben Brunk6267b532015-04-30 17:44:07 -07003770void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3771 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003772 std::string newUsers = toString(newUserIds);
3773 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003774 if (oldUsers.size() == 0) {
3775 oldUsers = "<None>";
3776 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003777 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003778 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3779 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003780}
3781
Austin Borgered99f642023-06-01 16:51:35 -07003782void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003783 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003784 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003785}
3786
Austin Borgered99f642023-06-01 16:51:35 -07003787void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003788 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003789 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003790}
3791
Austin Borgered99f642023-06-01 16:51:35 -07003792void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003793 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003794 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003795}
3796
Austin Borgered99f642023-06-01 16:51:35 -07003797void CameraService::logServiceError(const std::string &msg, int errorCode) {
3798 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3799 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003800}
3801
Ruben Brunk36597b22015-03-20 22:15:57 -07003802status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3803 uint32_t flags) {
3804
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805 // Permission checks
3806 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003807 case SHELL_COMMAND_TRANSACTION: {
3808 int in = data.readFileDescriptor();
3809 int out = data.readFileDescriptor();
3810 int err = data.readFileDescriptor();
3811 int argc = data.readInt32();
3812 Vector<String16> args;
3813 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3814 args.add(data.readString16());
3815 }
3816 sp<IBinder> unusedCallback;
3817 sp<IResultReceiver> resultReceiver;
3818 status_t status;
3819 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3820 return status;
3821 }
3822 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3823 return status;
3824 }
3825 status = shellCommand(in, out, err, args);
3826 if (resultReceiver != nullptr) {
3827 resultReceiver->send(status);
3828 }
3829 return NO_ERROR;
3830 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003831 }
3832
3833 return BnCameraService::onTransact(code, data, reply, flags);
3834}
3835
Mathias Agopian65ab4712010-07-14 17:59:35 -07003836// We share the media players for shutter and recording sound for all clients.
3837// A reference count is kept to determine when we will actually release the
3838// media players.
3839
Jaekyun Seokef498052018-03-23 13:09:44 +09003840sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3841 sp<MediaPlayer> mp = new MediaPlayer();
3842 status_t error;
3843 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003844 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003845 error = mp->prepare();
3846 }
3847 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003848 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003849 mp->disconnect();
3850 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003851 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003852 }
3853 return mp;
3854}
3855
username5755fea2018-12-27 09:48:08 +08003856void CameraService::increaseSoundRef() {
3857 Mutex::Autolock lock(mSoundLock);
3858 mSoundRef++;
3859}
3860
3861void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003862 ATRACE_CALL();
3863
username5755fea2018-12-27 09:48:08 +08003864 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3865 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3866 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3867 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3868 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3869 }
3870 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3871 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3872 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3873 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003874 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003875 }
3876 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3877 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3878 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3879 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3880 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003881 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003882}
3883
username5755fea2018-12-27 09:48:08 +08003884void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003885 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003886 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003887 if (--mSoundRef) return;
3888
3889 for (int i = 0; i < NUM_SOUNDS; i++) {
3890 if (mSoundPlayer[i] != 0) {
3891 mSoundPlayer[i]->disconnect();
3892 mSoundPlayer[i].clear();
3893 }
3894 }
3895}
3896
3897void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003898 ATRACE_CALL();
3899
Mathias Agopian65ab4712010-07-14 17:59:35 -07003900 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003901 if (kind < 0 || kind >= NUM_SOUNDS) {
3902 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3903 return;
3904 }
3905
Mathias Agopian65ab4712010-07-14 17:59:35 -07003906 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003907 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003908 sp<MediaPlayer> player = mSoundPlayer[kind];
3909 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003910 player->seekTo(0);
3911 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003912 }
3913}
3914
3915// ----------------------------------------------------------------------------
3916
3917CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003918 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07003919 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07003920 const std::string& clientPackageName, bool systemNativeClient,
3921 const std::optional<std::string>& clientFeatureId,
3922 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003923 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003924 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003925 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003926 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003927 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07003928 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003929 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003930 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003931 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003932 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003933 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003934{
Austin Borger22c5c852024-03-08 13:31:36 -08003935 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003936 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003938 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939
username5755fea2018-12-27 09:48:08 +08003940 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003941
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003942 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003943}
3944
Mathias Agopian65ab4712010-07-14 17:59:35 -07003945// tear down the client
3946CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003947 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003948 mDestructionStarted = true;
3949
username5755fea2018-12-27 09:48:08 +08003950 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003951 // unconditionally disconnect. function is idempotent
3952 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953}
3954
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003955sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3956
Igor Murashkin634a5152013-02-20 17:15:11 -08003957CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003958 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07003959 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07003960 const std::string& clientPackageName, bool nativeClient,
3961 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003962 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003963 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07003964 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003965 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003966 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003967 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3968 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003969 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003970 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003971 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003972 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003973 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003974 mRemoteBinder(remoteCallback),
3975 mOpsActive(false),
3976 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003977{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003978 if (sCameraService == nullptr) {
3979 sCameraService = cameraService;
3980 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003981
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003982 // There are 2 scenarios in which a client won't have AppOps operations
3983 // (both scenarios : native clients)
3984 // 1) It's an system native client*, the package name will be empty
3985 // and it will return from this function in the previous if condition
3986 // (This is the same as the previously existing behavior).
3987 // 2) It is a system native client, but its package name has been
3988 // modified for debugging, however it still must not use AppOps since
3989 // the package name is not a real one.
3990 //
3991 // * system native client - native client with UID < AID_APP_START. It
3992 // doesn't exclude clients not on the system partition.
3993 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07003994 mAppOpsManager = std::make_unique<AppOpsManager>();
3995 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07003996
Charles Chenf075f082024-03-04 23:32:55 +00003997 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08003998}
3999
4000CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004001 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004002 mDestructionStarted = true;
4003}
4004
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004005binder::Status CameraService::BasicClient::disconnect() {
4006 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004007 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004008 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004009 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004010 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004011
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004012 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004013 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004014 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004015 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004016
4017 sp<IBinder> remote = getRemote();
4018 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004019 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004020 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004021
4022 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004023 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004024 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004025 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004026 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004027
Igor Murashkincba2c162013-03-20 15:56:31 -07004028 // client shouldn't be able to call into us anymore
4029 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004030
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004031 const auto& mActivityManager = getActivityManager();
4032 if (mActivityManager) {
4033 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004034 getCallingUid(),
4035 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004036 }
4037
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004038 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004039}
4040
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004041status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4042 // No dumping of clients directly over Binder,
4043 // must go through CameraService::dump
4044 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004045 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004046 return OK;
4047}
4048
Austin Borgered99f642023-06-01 16:51:35 -07004049status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004050 // Can't watch tags directly, must go through CameraService::startWatchingTags
4051 return OK;
4052}
4053
4054status_t CameraService::BasicClient::stopWatchingTags(int) {
4055 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4056 return OK;
4057}
4058
4059status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4060 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4061 return OK;
4062}
4063
Austin Borgered99f642023-06-01 16:51:35 -07004064std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004065 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004066}
4067
Emilian Peev8b64f282021-03-25 16:49:57 -07004068int CameraService::BasicClient::getCameraFacing() const {
4069 return mCameraFacing;
4070}
4071
4072int CameraService::BasicClient::getCameraOrientation() const {
4073 return mOrientation;
4074}
Ruben Brunkcc776712015-02-17 20:18:47 -08004075
4076int CameraService::BasicClient::getClientPid() const {
4077 return mClientPid;
4078}
4079
Ruben Brunk6267b532015-04-30 17:44:07 -07004080uid_t CameraService::BasicClient::getClientUid() const {
4081 return mClientUid;
4082}
4083
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004084bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4085 // Defaults to API2.
4086 return level == API_2;
4087}
4088
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004089status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004090 {
4091 Mutex::Autolock l(mAudioRestrictionLock);
4092 mAudioRestriction = mode;
4093 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004094 sCameraService->updateAudioRestriction();
4095 return OK;
4096}
4097
4098int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004099 return sCameraService->updateAudioRestriction();
4100}
4101
4102int32_t CameraService::BasicClient::getAudioRestriction() const {
4103 Mutex::Autolock l(mAudioRestrictionLock);
4104 return mAudioRestriction;
4105}
4106
4107bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4108 switch (mode) {
4109 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4110 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4111 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4112 return true;
4113 default:
4114 return false;
4115 }
4116}
4117
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004118status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4119 if (mode == AppOpsManager::MODE_ERRORED) {
4120 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004121 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004122 return PERMISSION_DENIED;
4123 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4124 // If the calling Uid is trusted (a native service), the AppOpsManager could
4125 // return MODE_IGNORED. Do not treat such case as error.
4126 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4127 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004128
4129 bool isCameraPrivacyEnabled;
4130 if (flags::camera_privacy_allowlist()) {
4131 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4132 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4133 } else {
4134 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004135 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004136 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004137 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4138 // We prefer to successfully open the camera and perform camera muting
4139 // or blocking in connectHelper as handleAppOpMode can be called before the
4140 // connection has been fully established and at that time camera muting
4141 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004142 if (!isUidActive || !isCameraPrivacyEnabled) {
4143 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004144 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004145 // Return the same error as for device policy manager rejection
4146 return -EACCES;
4147 }
4148 }
4149 return OK;
4150}
4151
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004152status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004153 ATRACE_CALL();
4154
Igor Murashkine6800ce2013-03-04 17:25:57 -08004155 {
4156 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004157 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004158 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004159 if (mAppOpsManager != nullptr) {
4160 // Notify app ops that the camera is not available
4161 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004162
4163 if (flags::watch_foreground_changes()) {
4164 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4165 toString16(mClientPackageName),
4166 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4167 } else {
4168 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004169 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004170 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004171
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004172 // Just check for camera acccess here on open - delay startOp until
4173 // camera frames start streaming in startCameraStreamingOps
4174 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004175 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004176 status_t res = handleAppOpMode(mode);
4177 if (res != OK) {
4178 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004179 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004180 }
4181
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004182 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004183
4184 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004185 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004186
Austin Borgerdddb7552023-03-30 17:53:01 -07004187 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004188
Shuzhen Wang695044d2020-03-06 09:02:23 -08004189 // Notify listeners of camera open/close status
4190 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4191
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004192 return OK;
4193}
4194
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004195status_t CameraService::BasicClient::startCameraStreamingOps() {
4196 ATRACE_CALL();
4197
4198 if (!mOpsActive) {
4199 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4200 return INVALID_OPERATION;
4201 }
4202 if (mOpsStreaming) {
4203 ALOGV("%s: Streaming already active!", __FUNCTION__);
4204 return OK;
4205 }
4206
4207 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004208 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004209
4210 if (mAppOpsManager != nullptr) {
4211 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004212 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4213 toString16(mClientFeatureId),
4214 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004215 status_t res = handleAppOpMode(mode);
4216 if (res != OK) {
4217 return res;
4218 }
4219 }
4220
4221 mOpsStreaming = true;
4222
4223 return OK;
4224}
4225
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004226status_t CameraService::BasicClient::noteAppOp() {
4227 ATRACE_CALL();
4228
4229 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004230 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004231
4232 // noteAppOp is only used for when camera mute is not supported, in order
4233 // to trigger the sensor privacy "Unblock" dialog
4234 if (mAppOpsManager != nullptr) {
4235 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004236 toString16(mClientPackageName), toString16(mClientFeatureId),
4237 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004238 status_t res = handleAppOpMode(mode);
4239 if (res != OK) {
4240 return res;
4241 }
4242 }
4243
4244 return OK;
4245}
4246
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004247status_t CameraService::BasicClient::finishCameraStreamingOps() {
4248 ATRACE_CALL();
4249
4250 if (!mOpsActive) {
4251 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4252 return INVALID_OPERATION;
4253 }
4254 if (!mOpsStreaming) {
4255 ALOGV("%s: Streaming not active!", __FUNCTION__);
4256 return OK;
4257 }
4258
4259 if (mAppOpsManager != nullptr) {
4260 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004261 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004262 mOpsStreaming = false;
4263 }
4264
4265 return OK;
4266}
4267
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004268status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004269 ATRACE_CALL();
4270
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004271 if (mOpsStreaming) {
4272 // Make sure we've notified everyone about camera stopping
4273 finishCameraStreamingOps();
4274 }
4275
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004276 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004277 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004278 mOpsActive = false;
4279
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004280 // This function is called when a client disconnects. This should
4281 // release the camera, but actually only if it was in a proper
4282 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004283 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004284 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004285
Ruben Brunkcc776712015-02-17 20:18:47 -08004286 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004287 sCameraService->updateStatus(StatusInternal::PRESENT,
4288 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004289 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004290 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004291 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4292 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004293 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004294 mOpsCallback.clear();
4295
Austin Borgerdddb7552023-03-30 17:53:01 -07004296 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004297
Shuzhen Wang695044d2020-03-06 09:02:23 -08004298 // Notify listeners of camera open/close status
4299 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4300
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004301 return OK;
4302}
4303
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004304void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004305 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004306 if (mAppOpsManager == nullptr) {
4307 return;
4308 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004309 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004310 if (op != AppOpsManager::OP_CAMERA) {
4311 ALOGW("Unexpected app ops notification received: %d", op);
4312 return;
4313 }
4314
4315 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004316 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004317 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004318 ALOGV("checkOp returns: %d, %s ", res,
4319 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4320 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4321 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4322 "UNKNOWN");
4323
Shuzhen Wang64900852021-02-05 09:03:29 -08004324 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004325 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4326 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004327 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004328 } else if (res == AppOpsManager::MODE_IGNORED) {
4329 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004330
Austin Borgerca1e0062023-06-28 11:32:55 -07004331 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4332 // If not visible, but still active, then we want to block instead of muting the camera.
4333 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4334 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4335
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004336 bool isCameraPrivacyEnabled;
4337 if (flags::camera_privacy_allowlist()) {
4338 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4339 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4340 } else {
4341 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004342 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004343 }
4344
4345 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004346 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4347 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4348 isCameraPrivacyEnabled);
4349 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4350 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4351 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004352 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004353 if (flags::watch_foreground_changes()) {
4354 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4355 setCameraMute(true);
4356 } else {
4357 block();
4358 }
4359 } else {
4360 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4361 setCameraMute(true);
4362 } else if (!isUidActive
4363 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4364 block();
4365 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004366 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004367 }
Evan Severson09ab4002021-02-10 14:15:19 -08004368 } else if (res == AppOpsManager::MODE_ALLOWED) {
4369 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004370 }
4371}
4372
Svet Ganova453d0d2018-01-11 15:37:58 -08004373void CameraService::BasicClient::block() {
4374 ATRACE_CALL();
4375
4376 // Reset the client PID to allow server-initiated disconnect,
4377 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004378 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004379 CaptureResultExtras resultExtras; // a dummy result (invalid)
4380 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4381 disconnect();
4382}
4383
Mathias Agopian65ab4712010-07-14 17:59:35 -07004384// ----------------------------------------------------------------------------
4385
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004386void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004387 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004388 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004389 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4390 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4391 api1ErrorCode = CAMERA_ERROR_DISABLED;
4392 }
4393 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004394 } else {
4395 ALOGE("mRemoteCallback is NULL!!");
4396 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004397}
4398
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004399// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004400binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004401 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004402 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004403}
4404
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004405bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4406 return level == API_1;
4407}
4408
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004409CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4410 mClient(client) {
4411}
4412
4413void CameraService::Client::OpsCallback::opChanged(int32_t op,
4414 const String16& packageName) {
4415 sp<BasicClient> client = mClient.promote();
4416 if (client != NULL) {
4417 client->opChanged(op, packageName);
4418 }
4419}
4420
Mathias Agopian65ab4712010-07-14 17:59:35 -07004421// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004422// UidPolicy
4423// ----------------------------------------------------------------------------
4424
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004425void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004426 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004427 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004428
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004429 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004430 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004431 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004432 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004433 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4434 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004435 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004436 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004437 if (res == OK) {
4438 mRegistered = true;
4439 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004440 } else {
4441 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004442 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004443}
4444
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004445void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004446 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004447 return;
4448 }
4449
4450 registerWithActivityManager();
4451}
4452
4453void CameraService::UidPolicy::registerSelf() {
4454 // Use check service to see if the activity service is available
4455 // If not available then register for notifications, instead of blocking
4456 // till the service is ready
4457 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004458 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004459 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004460 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004461 } else {
4462 registerWithActivityManager();
4463 }
4464}
4465
Svet Ganova453d0d2018-01-11 15:37:58 -08004466void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004467 Mutex::Autolock _l(mUidLock);
4468
Steven Moreland2f348142019-07-02 15:59:07 -07004469 mAm.unregisterUidObserver(this);
4470 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004471 mRegistered = false;
4472 mActiveUids.clear();
4473 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004474}
4475
4476void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4477 onUidIdle(uid, disabled);
4478}
4479
4480void CameraService::UidPolicy::onUidActive(uid_t uid) {
4481 Mutex::Autolock _l(mUidLock);
4482 mActiveUids.insert(uid);
4483}
4484
4485void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4486 bool deleted = false;
4487 {
4488 Mutex::Autolock _l(mUidLock);
4489 if (mActiveUids.erase(uid) > 0) {
4490 deleted = true;
4491 }
4492 }
4493 if (deleted) {
4494 sp<CameraService> service = mService.promote();
4495 if (service != nullptr) {
4496 service->blockClientsForUid(uid);
4497 }
4498 }
4499}
4500
Emilian Peev53722fa2019-02-22 17:47:20 -08004501void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004502 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004503 bool procStateChange = false;
4504 {
4505 Mutex::Autolock _l(mUidLock);
4506 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4507 mMonitoredUids[uid].procState != procState) {
4508 mMonitoredUids[uid].procState = procState;
4509 procStateChange = true;
4510 }
4511 }
4512
4513 if (procStateChange) {
4514 sp<CameraService> service = mService.promote();
4515 if (service != nullptr) {
4516 service->notifyMonitoredUids();
4517 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004518 }
4519}
4520
Austin Borgerdddb7552023-03-30 17:53:01 -07004521/**
4522 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4523 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4524 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4525 * monitoredUids. If it is revised above some other monitoredUid, signal
4526 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4527 * foreground apps in split screen - state changes will capture all other cases.
4528 */
4529void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4530 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004531 {
4532 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004533 auto it = mMonitoredUids.find(uid);
4534
4535 if (it != mMonitoredUids.end()) {
4536 if (it->second.hasCamera) {
4537 for (auto &monitoredUid : mMonitoredUids) {
4538 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004539 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004540 notifyUidSet.emplace(monitoredUid.first);
4541 }
4542 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004543 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004544 notifyUidSet.emplace(uid);
4545 } else {
4546 for (auto &monitoredUid : mMonitoredUids) {
4547 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004548 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004549 notifyUidSet.emplace(uid);
4550 }
4551 }
4552 }
4553 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004554 }
4555 }
4556
Austin Borgerdddb7552023-03-30 17:53:01 -07004557 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004558 sp<CameraService> service = mService.promote();
4559 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004560 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004561 }
4562 }
4563}
4564
Austin Borgerdddb7552023-03-30 17:53:01 -07004565/**
4566 * Register a uid for monitoring, and note whether it owns a camera.
4567 */
4568void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004569 Mutex::Autolock _l(mUidLock);
4570 auto it = mMonitoredUids.find(uid);
4571 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004572 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004573 } else {
Austin Borger65577682022-02-17 00:25:43 +00004574 MonitoredUid monitoredUid;
4575 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004576 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004577 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004578 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004579 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004580 if (res != OK) {
4581 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4582 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004583 }
4584
4585 if (openCamera) {
4586 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004587 }
4588}
4589
Austin Borgerdddb7552023-03-30 17:53:01 -07004590/**
4591 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4592 */
4593void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004594 Mutex::Autolock _l(mUidLock);
4595 auto it = mMonitoredUids.find(uid);
4596 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004597 it->second.refCount--;
4598 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004599 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004600 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004601 if (res != OK) {
4602 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4603 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004604 } else if (closeCamera) {
4605 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004606 }
4607 } else {
4608 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4609 }
4610}
4611
Austin Borgered99f642023-06-01 16:51:35 -07004612bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004613 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004614 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004615}
4616
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004617static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4618static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004619
Austin Borgered99f642023-06-01 16:51:35 -07004620bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004621 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004622 // If activity manager is unreachable, assume everything is active
4623 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004624 return true;
4625 }
4626 auto it = mOverrideUids.find(uid);
4627 if (it != mOverrideUids.end()) {
4628 return it->second;
4629 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004630 bool active = mActiveUids.find(uid) != mActiveUids.end();
4631 if (!active) {
4632 // We want active UIDs to always access camera with their first attempt since
4633 // there is no guarantee the app is robustly written and would retry getting
4634 // the camera on failure. The inverse case is not a problem as we would take
4635 // camera away soon once we get the callback that the uid is no longer active.
4636 ActivityManager am;
4637 // Okay to access with a lock held as UID changes are dispatched without
4638 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004639 int64_t startTimeMillis = 0;
4640 do {
4641 // TODO: Fix this b/109950150!
4642 // Okay this is a hack. There is a race between the UID turning active and
4643 // activity being resumed. The proper fix is very risky, so we temporary add
4644 // some polling which should happen pretty rarely anyway as the race is hard
4645 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004646 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004647 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004648 if (active) {
4649 break;
4650 }
4651 if (startTimeMillis <= 0) {
4652 startTimeMillis = uptimeMillis();
4653 }
4654 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004655 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004656 if (remainingTimeMillis <= 0) {
4657 break;
4658 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004659 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4660
4661 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004662 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004663 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004664 } while (true);
4665
Svet Ganov7b4ab782018-03-25 12:48:10 -07004666 if (active) {
4667 // Now that we found out the UID is actually active, cache that
4668 mActiveUids.insert(uid);
4669 }
4670 }
4671 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004672}
4673
Varun Shahb42f1eb2019-04-16 14:45:13 -07004674int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4675 Mutex::Autolock _l(mUidLock);
4676 return getProcStateLocked(uid);
4677}
4678
4679int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4680 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4681 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004682 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004683 }
4684 return procState;
4685}
4686
Austin Borgered99f642023-06-01 16:51:35 -07004687void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4688 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004689 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004690}
4691
Austin Borgered99f642023-06-01 16:51:35 -07004692void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004693 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004694}
4695
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004696void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4697 Mutex::Autolock _l(mUidLock);
4698 ALOGV("UidPolicy: ActivityManager has died");
4699 mRegistered = false;
4700 mActiveUids.clear();
4701}
4702
Austin Borgered99f642023-06-01 16:51:35 -07004703void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004704 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004705 bool wasActive = false;
4706 bool isActive = false;
4707 {
4708 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004709 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004710 mOverrideUids.erase(uid);
4711 if (insert) {
4712 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4713 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004714 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004715 }
4716 if (wasActive != isActive && !isActive) {
4717 sp<CameraService> service = mService.promote();
4718 if (service != nullptr) {
4719 service->blockClientsForUid(uid);
4720 }
4721 }
4722}
4723
4724// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004725// SensorPrivacyPolicy
4726// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004727
4728void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4729{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004730 Mutex::Autolock _l(mSensorPrivacyLock);
4731 if (mRegistered) {
4732 return;
4733 }
Evan Severson09ab4002021-02-10 14:15:19 -08004734 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004735 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004736 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004737 mSpm.addToggleSensorPrivacyListener(this);
4738 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004739 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004740 if (flags::camera_privacy_allowlist()) {
4741 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4742 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4743 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4744 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004745 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004746 if (res == OK) {
4747 mRegistered = true;
4748 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4749 }
4750}
4751
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004752void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4753 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004754 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004755 return;
4756 }
4757
4758 registerWithSensorPrivacyManager();
4759}
4760
4761void CameraService::SensorPrivacyPolicy::registerSelf() {
4762 // Use checkservice to see if the sensor_privacy service is available
4763 // If service is not available then register for notification
4764 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004765 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004766 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004767 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004768 } else {
4769 registerWithSensorPrivacyManager();
4770 }
4771}
4772
Michael Grooverd1d435a2018-12-18 17:39:42 -08004773void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4774 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004775 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004776 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004777 mSpm.removeToggleSensorPrivacyListener(this);
4778 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004779 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004780 mRegistered = false;
4781 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4782}
4783
4784bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004785 if (!mRegistered) {
4786 registerWithSensorPrivacyManager();
4787 }
4788
Michael Grooverd1d435a2018-12-18 17:39:42 -08004789 Mutex::Autolock _l(mSensorPrivacyLock);
4790 return mSensorPrivacyEnabled;
4791}
4792
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004793int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4794 if (!mRegistered) {
4795 registerWithSensorPrivacyManager();
4796 }
4797
4798 Mutex::Autolock _l(mSensorPrivacyLock);
4799 return mCameraPrivacyState;
4800}
4801
Evan Seversond0b69922022-01-27 10:47:34 -08004802bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004803 if (!hasCameraPrivacyFeature()) {
4804 return false;
4805 }
Evan Seversond0b69922022-01-27 10:47:34 -08004806 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004807}
4808
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004809bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4810 if (!hasCameraPrivacyFeature()) {
4811 return SensorPrivacyManager::DISABLED;
4812 }
4813 return mSpm.isCameraPrivacyEnabled(packageName);
4814}
4815
Evan Seversond0b69922022-01-27 10:47:34 -08004816binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004817 int toggleType, int sensor, bool enabled) {
4818 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4819 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4820 {
4821 Mutex::Autolock _l(mSensorPrivacyLock);
4822 mSensorPrivacyEnabled = enabled;
4823 }
4824 // if sensor privacy is enabled then block all clients from accessing the camera
4825 if (enabled) {
4826 sp<CameraService> service = mService.promote();
4827 if (service != nullptr) {
4828 service->blockAllClients();
4829 }
4830 }
4831 }
4832 return binder::Status::ok();
4833}
4834
4835binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4836 int, int sensor, int state) {
4837 if (!flags::camera_privacy_allowlist()
4838 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4839 return binder::Status::ok();
4840 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004841 {
4842 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004843 mCameraPrivacyState = state;
4844 }
4845 sp<CameraService> service = mService.promote();
4846 if (!service) {
4847 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004848 }
4849 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004850 if (state == SensorPrivacyManager::ENABLED) {
4851 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004852 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004853 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004854 }
4855 return binder::Status::ok();
4856}
4857
4858void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4859 Mutex::Autolock _l(mSensorPrivacyLock);
4860 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4861 mRegistered = false;
4862}
4863
Evan Severson09ab4002021-02-10 14:15:19 -08004864bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004865 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4866 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4867 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4868 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4869 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004870}
4871
Michael Grooverd1d435a2018-12-18 17:39:42 -08004872// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004873// CameraState
4874// ----------------------------------------------------------------------------
4875
Austin Borgered99f642023-06-01 16:51:35 -07004876CameraService::CameraState::CameraState(const std::string& id, int cost,
4877 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004878 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004879 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004880 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004881
4882CameraService::CameraState::~CameraState() {}
4883
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004884CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004885 Mutex::Autolock lock(mStatusLock);
4886 return mStatus;
4887}
4888
Austin Borgered99f642023-06-01 16:51:35 -07004889std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004890 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004891 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004892 return res;
4893}
4894
Ruben Brunkcc776712015-02-17 20:18:47 -08004895CameraParameters CameraService::CameraState::getShimParams() const {
4896 return mShimParams;
4897}
4898
4899void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4900 mShimParams = params;
4901}
4902
4903int CameraService::CameraState::getCost() const {
4904 return mCost;
4905}
4906
Austin Borgered99f642023-06-01 16:51:35 -07004907std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004908 return mConflicting;
4909}
4910
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004911SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4912 return mSystemCameraKind;
4913}
4914
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004915bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4916 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4917 != mPhysicalCameras.end();
4918}
4919
Austin Borgered99f642023-06-01 16:51:35 -07004920bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004921 Mutex::Autolock lock(mStatusLock);
4922 auto result = mUnavailablePhysicalIds.insert(physicalId);
4923 return result.second;
4924}
4925
Austin Borgered99f642023-06-01 16:51:35 -07004926bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004927 Mutex::Autolock lock(mStatusLock);
4928 auto count = mUnavailablePhysicalIds.erase(physicalId);
4929 return count > 0;
4930}
4931
Austin Borgered99f642023-06-01 16:51:35 -07004932void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004933 Mutex::Autolock lock(mStatusLock);
4934 mClientPackage = clientPackage;
4935}
4936
Austin Borgered99f642023-06-01 16:51:35 -07004937std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004938 Mutex::Autolock lock(mStatusLock);
4939 return mClientPackage;
4940}
4941
Ruben Brunkcc776712015-02-17 20:18:47 -08004942// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004943// ClientEventListener
4944// ----------------------------------------------------------------------------
4945
4946void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004947 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004948 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004949 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004950 if (basicClient.get() != nullptr) {
4951 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004952 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004953 static_cast<int>(basicClient->getClientUid()));
4954 }
4955}
4956
4957void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004958 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004959 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004960 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004961 if (basicClient.get() != nullptr) {
4962 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004963 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004964 static_cast<int>(basicClient->getClientUid()));
4965 }
4966}
4967
4968
4969// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004970// CameraClientManager
4971// ----------------------------------------------------------------------------
4972
Ruben Brunk99e69712015-05-26 17:25:07 -07004973CameraService::CameraClientManager::CameraClientManager() {
4974 setListener(std::make_shared<ClientEventListener>());
4975}
4976
Ruben Brunkcc776712015-02-17 20:18:47 -08004977CameraService::CameraClientManager::~CameraClientManager() {}
4978
4979sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004980 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004981 auto descriptor = get(id);
4982 if (descriptor == nullptr) {
4983 return sp<BasicClient>{nullptr};
4984 }
4985 return descriptor->getValue();
4986}
4987
Austin Borgered99f642023-06-01 16:51:35 -07004988std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004989 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004990 std::ostringstream ret;
4991 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004992 bool hasAny = false;
4993 for (auto& i : all) {
4994 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004995 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004996 int32_t cost = i->getCost();
4997 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004998 int32_t score = i->getPriority().getScore();
4999 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005000 auto conflicting = i->getConflicting();
5001 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005002 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005003 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005004 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005005 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005006 uid_t clientUid = clientSp->getClientUid();
5007 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005008 }
Austin Borgered99f642023-06-01 16:51:35 -07005009 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5010 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005011
Ruben Brunk6267b532015-04-30 17:44:07 -07005012 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005013 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005014 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005015 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005016 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005017 }
5018
Austin Borgered99f642023-06-01 16:51:35 -07005019 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005020 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005021 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005022 }
Austin Borgered99f642023-06-01 16:51:35 -07005023 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005024 }
Austin Borgered99f642023-06-01 16:51:35 -07005025 if (hasAny) ret << "\n";
5026 ret << "]\n";
5027 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005028}
5029
5030CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005031 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5032 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005033 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005034
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005035 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005036 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005037
Austin Borgered99f642023-06-01 16:51:35 -07005038 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005039 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5040 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005041}
5042
5043CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005044 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005045 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005046 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005047 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005048 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5049 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005050}
5051
5052// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005053// InjectionStatusListener
5054// ----------------------------------------------------------------------------
5055
5056void CameraService::InjectionStatusListener::addListener(
5057 const sp<ICameraInjectionCallback>& callback) {
5058 Mutex::Autolock lock(mListenerLock);
5059 if (mCameraInjectionCallback) return;
5060 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5061 if (res == OK) {
5062 mCameraInjectionCallback = callback;
5063 }
5064}
5065
5066void CameraService::InjectionStatusListener::removeListener() {
5067 Mutex::Autolock lock(mListenerLock);
5068 if (mCameraInjectionCallback == nullptr) {
5069 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5070 return;
5071 }
5072 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5073 mCameraInjectionCallback = nullptr;
5074}
5075
5076void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005077 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005078 if (mCameraInjectionCallback == nullptr) {
5079 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5080 return;
5081 }
Cliff Wud3a05312021-04-26 23:07:31 +08005082
5083 switch (err) {
5084 case -ENODEV:
5085 mCameraInjectionCallback->onInjectionError(
5086 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5087 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005088 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005089 break;
5090 case -EBUSY:
5091 mCameraInjectionCallback->onInjectionError(
5092 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5093 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005094 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005095 break;
5096 case DEAD_OBJECT:
5097 mCameraInjectionCallback->onInjectionError(
5098 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5099 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005100 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005101 break;
5102 case INVALID_OPERATION:
5103 mCameraInjectionCallback->onInjectionError(
5104 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5105 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005106 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005107 break;
5108 case UNKNOWN_TRANSACTION:
5109 mCameraInjectionCallback->onInjectionError(
5110 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5111 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005112 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005113 break;
5114 default:
5115 mCameraInjectionCallback->onInjectionError(
5116 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5117 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005118 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005119 }
Cliff Wud8cae102021-03-11 01:37:42 +08005120}
5121
5122void CameraService::InjectionStatusListener::binderDied(
5123 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005124 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5125 auto parent = mParent.promote();
5126 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005127 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5128 if (clientDescriptor != nullptr) {
5129 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5130 baseClientPtr->stopInjection();
5131 }
Cliff Wu3b268182021-07-06 15:44:43 +08005132 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005133 }
5134}
5135
5136// ----------------------------------------------------------------------------
5137// CameraInjectionSession
5138// ----------------------------------------------------------------------------
5139
5140binder::Status CameraService::CameraInjectionSession::stopInjection() {
5141 Mutex::Autolock lock(mInjectionSessionLock);
5142 auto parent = mParent.promote();
5143 if (parent == nullptr) {
5144 ALOGE("CameraInjectionSession: Parent is gone");
5145 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5146 "Camera service encountered error");
5147 }
Cliff Wud3a05312021-04-26 23:07:31 +08005148
5149 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005150 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5151 if (clientDescriptor != nullptr) {
5152 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5153 res = baseClientPtr->stopInjection();
5154 if (res != OK) {
5155 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5156 " ret != NO_ERROR: %d", res);
5157 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5158 "Camera session encountered error");
5159 }
5160 }
Cliff Wu3b268182021-07-06 15:44:43 +08005161 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005162 return binder::Status::ok();
5163}
5164
5165// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005166
5167static const int kDumpLockRetries = 50;
5168static const int kDumpLockSleep = 60000;
5169
5170static bool tryLock(Mutex& mutex)
5171{
5172 bool locked = false;
5173 for (int i = 0; i < kDumpLockRetries; ++i) {
5174 if (mutex.tryLock() == NO_ERROR) {
5175 locked = true;
5176 break;
5177 }
5178 usleep(kDumpLockSleep);
5179 }
5180 return locked;
5181}
5182
Rucha Katakwardf223072021-06-15 10:21:00 -07005183void CameraService::cacheDump() {
5184 if (mMemFd != -1) {
5185 const Vector<String16> args;
5186 ATRACE_CALL();
5187 // Acquiring service lock here will avoid the deadlock since
5188 // cacheDump will not be called during the second disconnect.
5189 Mutex::Autolock lock(mServiceLock);
5190
5191 Mutex::Autolock l(mCameraStatesLock);
5192 // Start collecting the info for open sessions and store it in temp file.
5193 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005194 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005195 auto clientDescriptor = mActiveClientManager.get(cameraId);
5196 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005197 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005198 // Log the current open session info before device is disconnected.
5199 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5200 }
5201 }
5202 }
5203}
5204
Mathias Agopian65ab4712010-07-14 17:59:35 -07005205status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005206 ATRACE_CALL();
5207
Austin Borgered99f642023-06-01 16:51:35 -07005208 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005209 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005210 getCallingPid(),
5211 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005212 return NO_ERROR;
5213 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005214 bool locked = tryLock(mServiceLock);
5215 // failed to lock - CameraService is probably deadlocked
5216 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005217 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005218 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005219
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005220 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005221 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005222
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005223 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005224 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005225
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005226 if (locked) mServiceLock.unlock();
5227 return NO_ERROR;
5228 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005229 dprintf(fd, "\n== Service global info: ==\n\n");
5230 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005231 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005232 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5233 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005234 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5235 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5236 }
Austin Borgered99f642023-06-01 16:51:35 -07005237 std::string activeClientString = mActiveClientManager.toString();
5238 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5239 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005240 if (mStreamUseCaseOverrides.size() > 0) {
5241 dprintf(fd, "Active stream use case overrides:");
5242 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5243 dprintf(fd, " %" PRId64, useCaseOverride);
5244 }
5245 dprintf(fd, "\n");
5246 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005247
5248 dumpEventLog(fd);
5249
5250 bool stateLocked = tryLock(mCameraStatesLock);
5251 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005252 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005253 }
5254
Emilian Peevbd8c5032018-02-14 23:05:40 +00005255 int argSize = args.size();
5256 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005257 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005258 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005259 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005260 }
5261 break;
5262 }
5263 }
5264
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005265 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005266 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005267
Austin Borgered99f642023-06-01 16:51:35 -07005268 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005269
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005270 CameraParameters p = state.second->getShimParams();
5271 if (!p.isEmpty()) {
5272 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5273 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005274 }
5275
5276 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005277 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005278 // log the current open session info
5279 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005280 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005281 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005282 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005283
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005284 }
5285
5286 if (stateLocked) mCameraStatesLock.unlock();
5287
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005288 if (locked) mServiceLock.unlock();
5289
Emilian Peevf53f66e2017-04-11 14:29:43 +01005290 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005291
5292 dprintf(fd, "\n== Vendor tags: ==\n\n");
5293
5294 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5295 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005296 sp<VendorTagDescriptorCache> cache =
5297 VendorTagDescriptorCache::getGlobalVendorTagCache();
5298 if (cache == NULL) {
5299 dprintf(fd, "No vendor tags.\n");
5300 } else {
5301 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5302 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005303 } else {
5304 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5305 }
5306
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005307 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005308 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005309 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005310
5311 // Process dump arguments, if any
5312 int n = args.size();
5313 String16 verboseOption("-v");
5314 String16 unreachableOption("--unreachable");
5315 for (int i = 0; i < n; i++) {
5316 if (args[i] == verboseOption) {
5317 // change logging level
5318 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005319 std::string levelStr = toStdString(args[i+1]);
5320 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005321 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005322 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005323 } else if (args[i] == unreachableOption) {
5324 // Dump memory analysis
5325 // TODO - should limit be an argument parameter?
5326 UnreachableMemoryInfo info;
5327 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5328 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005329 dprintf(fd, "\n== Unable to dump unreachable memory. "
5330 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005331 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005332 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005333 std::string s = info.ToString(/*log_contents*/ true);
5334 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005335 }
5336 }
5337 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005338
5339 bool serviceLocked = tryLock(mServiceLock);
5340
5341 // Dump info from previous open sessions.
5342 // Reposition the offset to beginning of the file before reading
5343
5344 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5345 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5346 ssize_t size_read;
5347 char buf[4096];
5348 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5349 // Read data from file to a small buffer and write it to fd.
5350 write(fd, buf, size_read);
5351 if (size_read == -1) {
5352 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5353 break;
5354 }
5355 }
5356 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5357 } else {
5358 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5359 }
5360
5361 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005362 return NO_ERROR;
5363}
5364
Rucha Katakwardf223072021-06-15 10:21:00 -07005365void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005366 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005367 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005368 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005369 getFormattedCurrentTime().c_str(),
5370 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005371 dprintf(fd, " Client priority score: %d state: %d\n",
5372 clientDescriptor->getPriority().getScore(),
5373 clientDescriptor->getPriority().getState());
5374 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5375
5376 auto client = clientDescriptor->getValue();
5377 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005378 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005379
5380 client->dumpClient(fd, args);
5381}
5382
Austin Borgered99f642023-06-01 16:51:35 -07005383void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005384 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005385 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005386}
5387
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005388void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005389 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005390
5391 Mutex::Autolock l(mLogLock);
5392 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005393 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005394 }
5395
5396 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005397 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005398 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005399 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005400 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005401 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005402}
5403
Austin Borgered99f642023-06-01 16:51:35 -07005404void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005405 Mutex::Autolock lock(mLogLock);
5406 if (!isClientWatchedLocked(client)) { return; }
5407
5408 std::vector<std::string> dumpVector;
5409 client->dumpWatchedEventsToVector(dumpVector);
5410
5411 if (dumpVector.empty()) { return; }
5412
Austin Borgered99f642023-06-01 16:51:35 -07005413 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005414
Austin Borgered99f642023-06-01 16:51:35 -07005415 std::string currentTime = getFormattedCurrentTime();
5416 dumpString << "Cached @ ";
5417 dumpString << currentTime;
5418 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005419
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005420 size_t i = dumpVector.size();
5421
5422 // Store the string in reverse order (latest last)
5423 while (i > 0) {
5424 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005425 dumpString << cameraId;
5426 dumpString << ":";
5427 dumpString << client->getPackageName();
5428 dumpString << " ";
5429 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005430 }
5431
Austin Borgered99f642023-06-01 16:51:35 -07005432 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005433}
5434
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005435void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005436 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005437 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5438 if (mTorchClientMap[i] == who) {
5439 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005440 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005441 status_t res = mFlashlight->setTorchMode(cameraId, false);
5442 if (res) {
5443 ALOGE("%s: torch client died but couldn't turn off torch: "
5444 "%s (%d)", __FUNCTION__, strerror(-res), res);
5445 return;
5446 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005447 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005448 break;
5449 }
5450 }
5451}
5452
Ruben Brunkcc776712015-02-17 20:18:47 -08005453/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005454
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005455 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005456 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5457 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005458 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005459 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005460 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005461
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005462 // check torch client
5463 handleTorchClientBinderDied(who);
5464
5465 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005466 if(!evictClientIdByRemote(who)) {
5467 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005468 return;
5469 }
5470
Ruben Brunkcc776712015-02-17 20:18:47 -08005471 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5472 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005473}
5474
Austin Borgered99f642023-06-01 16:51:35 -07005475void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005476 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005477}
5478
Austin Borgered99f642023-06-01 16:51:35 -07005479void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005480 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005481 // Do not lock mServiceLock here or can get into a deadlock from
5482 // connect() -> disconnect -> updateStatus
5483
5484 auto state = getCameraState(cameraId);
5485
5486 if (state == nullptr) {
5487 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005488 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005489 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005490 }
5491
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005492 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5493 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5494 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005495 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005496 return;
5497 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005498
5499 // Collect the logical cameras without holding mStatusLock in updateStatus
5500 // as that can lead to a deadlock(b/162192331).
5501 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005502 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005503 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005504 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005505 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005506 (const std::string& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005507
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005508 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005509 // Update torch status if it has a flash unit.
5510 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005511 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005512 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5513 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005514 TorchModeStatus newTorchStatus =
5515 status == StatusInternal::PRESENT ?
5516 TorchModeStatus::AVAILABLE_OFF :
5517 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005518 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005519 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005520 }
5521 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005522 }
5523
5524 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005525 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005526 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005527
Ruben Brunkcc776712015-02-17 20:18:47 -08005528 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005529 bool isVendorListener = listener->isVendorListener();
5530 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
Kwangkyu Park01f84432023-09-15 17:08:17 +09005531 listener->getListenerPid(), listener->getListenerUid())) {
Shuzhen Wangb8259792021-05-27 09:27:06 -07005532 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005533 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005534 continue;
5535 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005536 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005537 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005538 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005539 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005540 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5541 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005542 // Also trigger the callbacks for cameras that were remapped to the current
5543 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005544 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005545 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5546 for (auto& remappedCameraId : remappedCameraIds) {
5547 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005548 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005549 listener->handleBinderStatus(ret,
5550 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5551 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5552 ret.exceptionCode());
5553 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005554 }
5555 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005556}
5557
Austin Borgered99f642023-06-01 16:51:35 -07005558void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5559 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005560 auto state = getCameraState(cameraId);
5561 if (state == nullptr) {
5562 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005563 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005564 return;
5565 }
5566 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005567 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005568 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005569 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005570 }
5571
Shuzhen Wang695044d2020-03-06 09:02:23 -08005572 Mutex::Autolock lock(mStatusListenerLock);
5573
5574 for (const auto& it : mListenerList) {
5575 if (!it->isOpenCloseCallbackAllowed()) {
5576 continue;
5577 }
5578
5579 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005580 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005581 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005582 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005583 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005584 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005585
5586 it->handleBinderStatus(ret,
5587 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5588 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005589 }
5590}
5591
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005592template<class Func>
5593void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005594 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005595 std::initializer_list<StatusInternal> rejectSourceStates,
5596 Func onStatusUpdatedLocked) {
5597 Mutex::Autolock lock(mStatusLock);
5598 StatusInternal oldStatus = mStatus;
5599 mStatus = status;
5600
5601 if (oldStatus == status) {
5602 return;
5603 }
5604
5605 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005606 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005607
5608 if (oldStatus == StatusInternal::NOT_PRESENT &&
5609 (status != StatusInternal::PRESENT &&
5610 status != StatusInternal::ENUMERATING)) {
5611
5612 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5613 __FUNCTION__);
5614 mStatus = oldStatus;
5615 return;
5616 }
5617
5618 /**
5619 * Sometimes we want to conditionally do a transition.
5620 * For example if a client disconnects, we want to go to PRESENT
5621 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5622 */
5623 for (auto& rejectStatus : rejectSourceStates) {
5624 if (oldStatus == rejectStatus) {
5625 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005626 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005627 mStatus = oldStatus;
5628 return;
5629 }
5630 }
5631
5632 onStatusUpdatedLocked(cameraId, status);
5633}
5634
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005635status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005636 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005637 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005638 if (!status) {
5639 return BAD_VALUE;
5640 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005641 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5642 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005643 // invalid camera ID or the camera doesn't have a flash unit
5644 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005645 }
5646
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005647 *status = mTorchStatusMap.valueAt(index);
5648 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005649}
5650
Austin Borgered99f642023-06-01 16:51:35 -07005651status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005652 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005653 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5654 if (index == NAME_NOT_FOUND) {
5655 return BAD_VALUE;
5656 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005657 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005658
5659 return OK;
5660}
5661
Austin Borgered99f642023-06-01 16:51:35 -07005662std::list<std::string> CameraService::getLogicalCameras(
5663 const std::string& physicalCameraId) {
5664 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005665 Mutex::Autolock lock(mCameraStatesLock);
5666 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005667 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5668 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005669 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005670 }
5671 return retList;
5672}
5673
5674void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005675 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005676 SystemCameraKind deviceKind) {
5677 // mStatusListenerLock is expected to be locked
5678 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005679 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005680 // Note: we check only the deviceKind of the physical camera id
5681 // since, logical camera ids and their physical camera ids are
5682 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005683 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5684 listener->getListenerPid(), listener->getListenerUid())) {
5685 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005686 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005687 continue;
5688 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005689 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005690 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005691 listener->handleBinderStatus(ret,
5692 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5693 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5694 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005695 }
5696 }
5697}
5698
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005699
Svet Ganova453d0d2018-01-11 15:37:58 -08005700void CameraService::blockClientsForUid(uid_t uid) {
5701 const auto clients = mActiveClientManager.getAll();
5702 for (auto& current : clients) {
5703 if (current != nullptr) {
5704 const auto basicClient = current->getValue();
5705 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5706 basicClient->block();
5707 }
5708 }
5709 }
5710}
5711
Michael Grooverd1d435a2018-12-18 17:39:42 -08005712void CameraService::blockAllClients() {
5713 const auto clients = mActiveClientManager.getAll();
5714 for (auto& current : clients) {
5715 if (current != nullptr) {
5716 const auto basicClient = current->getValue();
5717 if (basicClient.get() != nullptr) {
5718 basicClient->block();
5719 }
5720 }
5721 }
5722}
5723
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005724void CameraService::blockPrivacyEnabledClients() {
5725 const auto clients = mActiveClientManager.getAll();
5726 for (auto& current : clients) {
5727 if (current != nullptr) {
5728 const auto basicClient = current->getValue();
5729 if (basicClient.get() != nullptr) {
5730 std::string pkgName = basicClient->getPackageName();
5731 bool cameraPrivacyEnabled =
5732 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5733 if (cameraPrivacyEnabled) {
5734 basicClient->block();
5735 }
5736 }
5737 }
5738 }
5739}
5740
Svet Ganova453d0d2018-01-11 15:37:58 -08005741// NOTE: This is a remote API - make sure all args are validated
5742status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005743 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005744 return PERMISSION_DENIED;
5745 }
5746 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5747 return BAD_VALUE;
5748 }
Austin Borgered99f642023-06-01 16:51:35 -07005749 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005750 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005751 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005752 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005753 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005754 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005755 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005756 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005757 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005758 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005759 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005760 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005761 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005762 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005763 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005764 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005765 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005766 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005767 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005768 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005769 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005770 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005771 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005772 handleClearStreamUseCaseOverrides();
5773 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005774 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005775 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005776 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005777 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005778 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005779 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005780 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005781 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005782 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005783 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005784 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005785 }
5786 printHelp(err);
5787 return BAD_VALUE;
5788}
5789
malikakash82ed4352023-07-21 22:44:34 +00005790status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5791 uid_t uid = IPCThreadState::self()->getCallingUid();
5792 if (uid != AID_ROOT) {
5793 dprintf(err, "Must be adb root\n");
5794 return PERMISSION_DENIED;
5795 }
5796 if (args.size() != 4) {
5797 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5798 return BAD_VALUE;
5799 }
Austin Borgered99f642023-06-01 16:51:35 -07005800 std::string packageName = toStdString(args[1]);
5801 std::string cameraIdToReplace = toStdString(args[2]);
5802 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005803 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5804 return OK;
5805}
5806
Svet Ganova453d0d2018-01-11 15:37:58 -08005807status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005808 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005809
Svet Ganova453d0d2018-01-11 15:37:58 -08005810 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005811 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005812 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005813 } else if ((args[2] != toString16("idle"))) {
5814 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005815 return BAD_VALUE;
5816 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005817
5818 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005819 if (args.size() >= 5 && args[3] == toString16("--user")) {
5820 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005821 }
5822
5823 uid_t uid;
5824 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5825 return BAD_VALUE;
5826 }
5827
5828 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005829 return NO_ERROR;
5830}
5831
5832status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005833 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005834
5835 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005836 if (args.size() >= 4 && args[2] == toString16("--user")) {
5837 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005838 }
5839
5840 uid_t uid;
5841 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005842 return BAD_VALUE;
5843 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005844
5845 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005846 return NO_ERROR;
5847}
5848
5849status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005850 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005851
5852 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005853 if (args.size() >= 4 && args[2] == toString16("--user")) {
5854 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005855 }
5856
5857 uid_t uid;
5858 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005859 return BAD_VALUE;
5860 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005861
5862 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005863 return dprintf(out, "active\n");
5864 } else {
5865 return dprintf(out, "idle\n");
5866 }
5867}
5868
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005869status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005870 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005871 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5872 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5873 Mutex::Autolock lock(mServiceLock);
5874
5875 mOverrideRotateAndCropMode = rotateValue;
5876
5877 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5878
5879 const auto clients = mActiveClientManager.getAll();
5880 for (auto& current : clients) {
5881 if (current != nullptr) {
5882 const auto basicClient = current->getValue();
5883 if (basicClient.get() != nullptr) {
5884 basicClient->setRotateAndCropOverride(rotateValue);
5885 }
5886 }
5887 }
5888
5889 return OK;
5890}
5891
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005892status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5893 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005894 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005895 if ((*end != '\0') ||
5896 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5897 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5898 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5899 return BAD_VALUE;
5900 }
5901
5902 Mutex::Autolock lock(mServiceLock);
5903 mOverrideAutoframingMode = autoframingValue;
5904
5905 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5906
5907 const auto clients = mActiveClientManager.getAll();
5908 for (auto& current : clients) {
5909 if (current != nullptr) {
5910 const auto basicClient = current->getValue();
5911 if (basicClient.get() != nullptr) {
5912 basicClient->setAutoframingOverride(autoframingValue);
5913 }
5914 }
5915 }
5916
5917 return OK;
5918}
5919
Ravneetaeb20dc2022-03-30 05:33:03 +00005920status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005921 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005922
5923 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5924
5925 Mutex::Autolock lock(mServiceLock);
5926
5927 mCameraServiceWatchdogEnabled = enableWatchdog;
5928
5929 const auto clients = mActiveClientManager.getAll();
5930 for (auto& current : clients) {
5931 if (current != nullptr) {
5932 const auto basicClient = current->getValue();
5933 if (basicClient.get() != nullptr) {
5934 basicClient->setCameraServiceWatchdog(enableWatchdog);
5935 }
5936 }
5937 }
5938
5939 return OK;
5940}
5941
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005942status_t CameraService::handleGetRotateAndCrop(int out) {
5943 Mutex::Autolock lock(mServiceLock);
5944
5945 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5946}
5947
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005948status_t CameraService::handleGetAutoframing(int out) {
5949 Mutex::Autolock lock(mServiceLock);
5950
5951 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5952}
5953
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005954status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5955 char *endPtr;
5956 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005957 std::string maskString = toStdString(args[1]);
5958 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005959
5960 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005961 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005962 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5963
5964 Mutex::Autolock lock(mServiceLock);
5965
5966 mImageDumpMask = maskValue;
5967
5968 return OK;
5969}
5970
5971status_t CameraService::handleGetImageDumpMask(int out) {
5972 Mutex::Autolock lock(mServiceLock);
5973
5974 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5975}
5976
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005977status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005978 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005979 if (errno != 0) return BAD_VALUE;
5980
5981 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5982 Mutex::Autolock lock(mServiceLock);
5983
5984 mOverrideCameraMuteMode = (muteValue == 1);
5985
5986 const auto clients = mActiveClientManager.getAll();
5987 for (auto& current : clients) {
5988 if (current != nullptr) {
5989 const auto basicClient = current->getValue();
5990 if (basicClient.get() != nullptr) {
5991 if (basicClient->supportsCameraMute()) {
5992 basicClient->setCameraMute(mOverrideCameraMuteMode);
5993 }
5994 }
5995 }
5996 }
5997
5998 return OK;
5999}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006000
Shuzhen Wang16610a62022-12-15 22:38:07 -08006001status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6002 std::vector<int64_t> useCasesOverride;
6003 for (size_t i = 1; i < args.size(); i++) {
6004 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006005 std::string arg = toStdString(args[i]);
6006 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006007 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006008 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006009 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006010 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006011 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006012 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006013 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006014 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006015 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006016 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006017 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006018 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006019 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6020 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006021 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006022 return BAD_VALUE;
6023 }
6024 useCasesOverride.push_back(useCase);
6025 }
6026
6027 Mutex::Autolock lock(mServiceLock);
6028 mStreamUseCaseOverrides = std::move(useCasesOverride);
6029
6030 return OK;
6031}
6032
6033void CameraService::handleClearStreamUseCaseOverrides() {
6034 Mutex::Autolock lock(mServiceLock);
6035 mStreamUseCaseOverrides.clear();
6036}
6037
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006038status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6039 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006040 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006041 if ((*end != '\0') ||
6042 (zoomOverrideValue != -1 &&
6043 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6044 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6045 return BAD_VALUE;
6046 }
6047
6048 Mutex::Autolock lock(mServiceLock);
6049 mZoomOverrideValue = zoomOverrideValue;
6050
6051 const auto clients = mActiveClientManager.getAll();
6052 for (auto& current : clients) {
6053 if (current != nullptr) {
6054 const auto basicClient = current->getValue();
6055 if (basicClient.get() != nullptr) {
6056 if (basicClient->supportsZoomOverride()) {
6057 basicClient->setZoomOverride(mZoomOverrideValue);
6058 }
6059 }
6060 }
6061 }
6062
6063 return OK;
6064}
6065
Avichal Rakesh84147132021-11-11 17:47:11 -08006066status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006067 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006068 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006069 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006070 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006071 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006072 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006073 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006074 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006075 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006076 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006077 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006078 dprintf(outFd, "Camera service watch commands:\n"
6079 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6080 " starts watching the provided tags for clients with provided package\n"
6081 " recognizes tag shorthands like '3a'\n"
6082 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006083 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006084 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006085 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006086 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006087 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006088 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006089 return BAD_VALUE;
6090}
6091
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006092status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6093 Mutex::Autolock lock(mLogLock);
6094 size_t tagsIdx; // index of '-m'
6095 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006096 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006097 if (tagsIdx < args.size() - 1) {
6098 tags = args[tagsIdx + 1];
6099 } else {
6100 dprintf(outFd, "No tags provided.\n");
6101 return BAD_VALUE;
6102 }
6103
6104 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006105 // watch all clients if no clients are provided
6106 String16 clients = toString16(kWatchAllClientsFlag);
6107 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006108 clientsIdx++);
6109 if (clientsIdx < args.size() - 1) {
6110 clients = args[clientsIdx + 1];
6111 }
Austin Borgered99f642023-06-01 16:51:35 -07006112 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006113
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006114 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006115 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006116
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006117 bool serviceLock = tryLock(mServiceLock);
6118 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006119 auto cameraClients = mActiveClientManager.getAll();
6120 for (const auto &clientDescriptor: cameraClients) {
6121 if (clientDescriptor == nullptr) { continue; }
6122 sp<BasicClient> client = clientDescriptor->getValue();
6123 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006124
6125 if (isClientWatchedLocked(client.get())) {
6126 client->startWatchingTags(mMonitorTags, outFd);
6127 numWatchedClients++;
6128 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006129 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006130 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6131
6132 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006133 return OK;
6134}
6135
6136status_t CameraService::stopWatchingTags(int outFd) {
6137 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006138 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006139 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006140
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006141 mWatchedClientPackages.clear();
6142 mWatchedClientsDumpCache.clear();
6143
6144 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006145 auto cameraClients = mActiveClientManager.getAll();
6146 for (const auto &clientDescriptor : cameraClients) {
6147 if (clientDescriptor == nullptr) { continue; }
6148 sp<BasicClient> client = clientDescriptor->getValue();
6149 if (client.get() == nullptr) { continue; }
6150 client->stopWatchingTags(outFd);
6151 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006152 dprintf(outFd, "Stopped watching all clients.\n");
6153 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006154 return OK;
6155}
6156
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006157status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6158 Mutex::Autolock lock(mLogLock);
6159 size_t clearedSize = mWatchedClientsDumpCache.size();
6160 mWatchedClientsDumpCache.clear();
6161 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6162 return OK;
6163}
6164
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006165status_t CameraService::printWatchedTags(int outFd) {
6166 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006167 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006168
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006169 bool printedSomething = false; // tracks if any monitoring information was printed
6170 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006171
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006172 bool serviceLock = tryLock(mServiceLock);
6173 // get all watched clients that are currently connected
6174 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6175 if (clientDescriptor == nullptr) { continue; }
6176
6177 sp<BasicClient> client = clientDescriptor->getValue();
6178 if (client.get() == nullptr) { continue; }
6179 if (!isClientWatchedLocked(client.get())) { continue; }
6180
6181 std::vector<std::string> dumpVector;
6182 client->dumpWatchedEventsToVector(dumpVector);
6183
6184 size_t printIdx = dumpVector.size();
6185 if (printIdx == 0) {
6186 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006187 }
6188
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006189 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006190 const std::string &cameraId = clientDescriptor->getKey();
6191 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006192 while(printIdx > 0) {
6193 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006194 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006195 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006196 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006197 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006198 printedSomething = true;
6199
6200 connectedMonitoredClients.emplace(client->getPackageName());
6201 }
6202 if (serviceLock) { mServiceLock.unlock(); }
6203
6204 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6205 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006206 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006207 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6208 continue;
6209 }
6210
Austin Borgered99f642023-06-01 16:51:35 -07006211 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006212 dprintf(outFd, "%s\n", kv.second.c_str());
6213 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006214 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006215
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006216 if (!printedSomething) {
6217 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006218 }
6219
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006220 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006221}
6222
Avichal Rakesh84147132021-11-11 17:47:11 -08006223// Print all events in vector `events' that came after lastPrintedEvent
6224void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006225 const std::string &cameraId,
6226 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006227 const std::vector<std::string> &events,
6228 const std::string &lastPrintedEvent) {
6229 if (events.empty()) { return; }
6230
6231 // index of lastPrintedEvent in events.
6232 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6233 size_t lastPrintedIdx;
6234 for (lastPrintedIdx = 0;
6235 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6236 lastPrintedIdx++);
6237
6238 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6239
Avichal Rakesh84147132021-11-11 17:47:11 -08006240 // print events in chronological order (latest event last)
6241 size_t idxToPrint = lastPrintedIdx;
6242 do {
6243 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006244 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6245 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006246 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006247}
6248
6249// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6250// command should be interrupted if the user presses the return key, or if user loses any way to
6251// signal interrupt.
6252// If timeoutMs == 0, this function will always return false
6253bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6254 struct timeval startTime;
6255 int startTimeError = gettimeofday(&startTime, nullptr);
6256 if (startTimeError) {
6257 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6258 return true;
6259 }
6260
6261 const nfds_t numFds = 1;
6262 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6263
6264 struct timeval currTime;
6265 char buffer[2];
6266 while(true) {
6267 int currTimeError = gettimeofday(&currTime, nullptr);
6268 if (currTimeError) {
6269 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6270 return true;
6271 }
6272
6273 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6274 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6275 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6276
6277 if (remainingTimeMs <= 0) {
6278 // No user interrupt within timeoutMs, don't interrupt watch command
6279 return false;
6280 }
6281
6282 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6283 if (numFdsUpdated < 0) {
6284 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6285 return true;
6286 }
6287
6288 if (numFdsUpdated == 0) {
6289 // No user input within timeoutMs, don't interrupt watch command
6290 return false;
6291 }
6292
6293 if (!(pollFd.revents & POLLIN)) {
6294 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6295 return true;
6296 }
6297
6298 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6299 if (sizeRead < 0) {
6300 dprintf(outFd, "Error reading user input. Exiting.\n");
6301 return true;
6302 }
6303
6304 if (sizeRead == 0) {
6305 // Reached end of input fd (can happen if input is piped)
6306 // User has no way to signal an interrupt, so interrupt here
6307 return true;
6308 }
6309
6310 if (buffer[0] == '\n') {
6311 // User pressed return, interrupt watch command.
6312 return true;
6313 }
6314 }
6315}
6316
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006317status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6318 int inFd, int outFd) {
6319 // Figure out refresh interval, if present in args
6320 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006321 if (args.size() > 2) {
6322 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006323 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006324 intervalIdx++);
6325
6326 size_t intervalValIdx = intervalIdx + 1;
6327 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006328 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006329 if (errno) { return BAD_VALUE; }
6330 }
6331 }
6332
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006333 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6334 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006335
Avichal Rakesh84147132021-11-11 17:47:11 -08006336 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006337 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006338
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006339 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006340 bool serviceLock = tryLock(mServiceLock);
6341 auto cameraClients = mActiveClientManager.getAll();
6342 if (serviceLock) { mServiceLock.unlock(); }
6343
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006344 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006345 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006346 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006347
6348 sp<BasicClient> client = clientDescriptor->getValue();
6349 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006350 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006351
Austin Borgered99f642023-06-01 16:51:35 -07006352 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006353 // This also initializes the map entries with an empty string
6354 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6355
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006356 std::vector<std::string> latestEvents;
6357 client->dumpWatchedEventsToVector(latestEvents);
6358
6359 if (!latestEvents.empty()) {
6360 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006361 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006362 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006363 latestEvents,
6364 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006365 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006366 }
6367 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006368 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006369 break;
6370 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006371 }
6372 return OK;
6373}
6374
Austin Borgered99f642023-06-01 16:51:35 -07006375void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006376 mWatchedClientPackages.clear();
6377
Austin Borgered99f642023-06-01 16:51:35 -07006378 std::istringstream iss(clients);
6379 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006380
Austin Borgered99f642023-06-01 16:51:35 -07006381 while (std::getline(iss, nextClient, ',')) {
6382 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006383 // Don't need to track any other package if 'all' is present
6384 mWatchedClientPackages.clear();
6385 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6386 break;
6387 }
6388
6389 // track package names
6390 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006391 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006392}
6393
Svet Ganova453d0d2018-01-11 15:37:58 -08006394status_t CameraService::printHelp(int out) {
6395 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006396 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6397 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6398 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006399 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6400 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6401 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006402 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6403 " Valid values 0=false, 1=true, 2=auto\n"
6404 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006405 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6406 " Valid values 0=OFF, 1=ON for JPEG\n"
6407 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006408 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006409 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6410 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6411 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6412 " on. In case the number of usecases is smaller than the number of streams, the\n"
6413 " last use case is assigned to all the remaining streams. In case of multiple\n"
6414 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6415 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6416 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6417 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006418 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6419 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006420 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6421 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006422 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006423 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006424 " help print this message\n");
6425}
6426
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006427bool CameraService::isClientWatched(const BasicClient *client) {
6428 Mutex::Autolock lock(mLogLock);
6429 return isClientWatchedLocked(client);
6430}
6431
6432bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6433 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6434 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6435}
6436
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006437int32_t CameraService::updateAudioRestriction() {
6438 Mutex::Autolock lock(mServiceLock);
6439 return updateAudioRestrictionLocked();
6440}
6441
6442int32_t CameraService::updateAudioRestrictionLocked() {
6443 int32_t mode = 0;
6444 // iterate through all active client
6445 for (const auto& i : mActiveClientManager.getAll()) {
6446 const auto clientSp = i->getValue();
6447 mode |= clientSp->getAudioRestriction();
6448 }
6449
6450 bool modeChanged = (mAudioRestriction != mode);
6451 mAudioRestriction = mode;
6452 if (modeChanged) {
6453 mAppOps.setCameraAudioRestriction(mode);
6454 }
6455 return mode;
6456}
6457
Austin Borgered99f642023-06-01 16:51:35 -07006458status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006459 sp<BasicClient> clientSp) {
6460 std::unique_ptr<AutoConditionLock> lock =
6461 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6462 status_t res = NO_ERROR;
6463 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006464 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006465 mInjectionStatusListener->notifyInjectionError(
6466 externalCamId, UNKNOWN_TRANSACTION);
6467 clientSp->notifyError(
6468 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6469 CaptureResultExtras());
6470
6471 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6472 // other clients from connecting in mServiceLockWrapper if held
6473 mServiceLock.unlock();
6474
6475 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006476 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006477 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006478 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006479
6480 // Reacquire mServiceLock
6481 mServiceLock.lock();
6482 }
6483
6484 return res;
6485}
6486
Cliff Wud3a05312021-04-26 23:07:31 +08006487void CameraService::clearInjectionParameters() {
6488 {
6489 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006490 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006491 mInjectionInternalCamId = "";
6492 }
6493 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006494 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006495}
6496
Mathias Agopian65ab4712010-07-14 17:59:35 -07006497}; // namespace android