blob: 26208c532eba9eb3309d2de171e40e5ea09794e3 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080041#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080042#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070043#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/MemoryBase.h>
45#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080046#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080048#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070049#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070050#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070051#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080052#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080053#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070054#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070055#include "hidl/HidlCameraService.h"
56#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080057#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070058#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070059#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080060#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070062#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000063#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070064#include <utils/Errors.h>
65#include <utils/Log.h>
66#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070067#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080068#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080069#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080070#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080071#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070072#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000073#include <binder/IServiceManager.h>
74#include <binder/IActivityManager.h>
Austin Borgered99f642023-06-01 16:51:35 -070075#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080076
Ruben Brunkb2119af2014-05-09 19:57:56 -070077#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070078
79#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070080#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070081#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070082#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000083#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070084#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070086#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070087
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080088namespace {
89 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080090 const char* kActivityServiceName = "activity";
91 const char* kSensorPrivacyServiceName = "sensor_privacy";
92 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070093 const char* kProcessInfoServiceName = "processinfo";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080094}; // namespace anonymous
95
Mathias Agopian65ab4712010-07-14 17:59:35 -070096namespace android {
97
Austin Borgerea931242021-12-13 23:10:41 +000098using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -070099using namespace camera3::SessionConfigurationUtils;
100
101using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700102using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700103using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800104using hardware::ICamera;
105using hardware::ICameraClient;
106using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800107using hardware::camera2::ICameraInjectionCallback;
108using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800109using hardware::camera2::utils::CameraIdAndSessionConfiguration;
110using hardware::camera2::utils::ConcurrentCameraIdCombination;
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700111namespace flags = com::android::internal::camera::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800112
Mathias Agopian65ab4712010-07-14 17:59:35 -0700113// ----------------------------------------------------------------------------
114// Logging support -- this is for debugging only
115// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700116volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700117
Steve Blockb8a80522011-12-20 16:23:08 +0000118#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
119#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120
121static void setLogLevel(int level) {
122 android_atomic_write(level, &gLogLevel);
123}
124
Henri Chataingbcb99452023-11-01 17:40:30 +0000125int32_t format_as(CameraService::StatusInternal s) {
126 return fmt::underlying(s);
127}
128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130
Austin Borger249e6592024-03-10 22:28:11 -0700131// Permission strings (references to AttributionAndPermissionUtils for brevity)
132static const std::string &sDumpPermission =
133 AttributionAndPermissionUtils::sDumpPermission;
134static const std::string &sManageCameraPermission =
135 AttributionAndPermissionUtils::sManageCameraPermission;
136static const std::string &sCameraSendSystemEventsPermission =
137 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
138static const std::string &sCameraInjectExternalCameraPermission =
139 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
140
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000141// Constant integer for FGS Logging, used to denote the API type for logger
142static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700143const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800144static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
145static constexpr int32_t kSystemNativeClientState =
146 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700147static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700148
Austin Borgered99f642023-06-01 16:51:35 -0700149const std::string CameraService::kOfflineDevice("offline-");
150const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700151
Rucha Katakward9ea6452021-05-06 11:57:16 -0700152// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700153static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700154
Austin Borger74fca042022-05-23 12:41:21 -0700155CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700156 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
157 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
158 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
159 std::make_shared<AttributionAndPermissionUtils>()\
160 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700161 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
162 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800163 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800164 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700165 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700166 mSoundRef(0), mInitialized(false),
167 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000168 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700169 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800170 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700171 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
172 if (mMemFd == -1) {
173 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
174 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700175}
176
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800177// The word 'System' here does not refer to clients only on the system
178// partition. They just need to have a android system uid.
179static bool doesClientHaveSystemUid() {
180 return (CameraThreadState::getCallingUid() < AID_APP_START);
181}
182
Charles Chena7b613c2023-01-24 21:57:33 +0000183// Enable processes with isolated AID to request the binder
184void CameraService::instantiate() {
185 CameraService::publish(true);
186}
187
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800188void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700189 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800190 return;
191 }
192
193 ALOGV("appops service registered. setting camera audio restriction");
194 mAppOps.setCameraAudioRestriction(mAudioRestriction);
195}
196
Iliyan Malchev8951a972011-04-14 16:55:59 -0700197void CameraService::onFirstRef()
198{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700199
Ruben Brunkcc776712015-02-17 20:18:47 -0800200 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800201
Iliyan Malchev8951a972011-04-14 16:55:59 -0700202 BnCameraService::onFirstRef();
203
Ruben Brunk99e69712015-05-26 17:25:07 -0700204 // Update battery life tracking if service is restarting
205 BatteryNotifier& notifier(BatteryNotifier::getInstance());
206 notifier.noteResetCamera();
207 notifier.noteResetFlashlight();
208
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800209 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800210
Emilian Peevf53f66e2017-04-11 14:29:43 +0100211 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800212 if (res == OK) {
213 mInitialized = true;
214 }
215
Svet Ganova453d0d2018-01-11 15:37:58 -0800216 mUidPolicy = new UidPolicy(this);
217 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700218 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800219 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800220 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800221
222 // appops function setCamerAudioRestriction uses getService which
223 // is blocking till the appops service is ready. To enable early
224 // boot availability for cameraservice, use checkService which is
225 // non blocking and register for notifications
226 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700227 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800228 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700229 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800230 } else {
231 mAppOps.setCameraAudioRestriction(mAudioRestriction);
232 }
233
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700234 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
235 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000236 // Deprecated, so it will fail to register on newer devices
237 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700238 __FUNCTION__);
239 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700240
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700241 if (!AidlCameraService::registerService(this)) {
242 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
243 }
244
Shuzhen Wang24b44152019-09-20 10:38:11 -0700245 // This needs to be last call in this function, so that it's as close to
246 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700247 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700248 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800249}
250
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800251status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800252 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100253
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800254 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000255 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800256 {
257 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800258
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800259 if (nullptr == mCameraProviderManager.get()) {
260 mCameraProviderManager = new CameraProviderManager();
261 res = mCameraProviderManager->initialize(this);
262 if (res != OK) {
263 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
264 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700265 logServiceError("Unable to initialize camera provider manager",
266 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100268 }
269 }
270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271
272 // Setup vendor tags before we call get_camera_info the first time
273 // because HAL might need to setup static vendor keys in get_camera_info
274 // TODO: maybe put this into CameraProviderManager::initialize()?
275 mCameraProviderManager->setUpVendorTags();
276
277 if (nullptr == mFlashlight.get()) {
278 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700279 }
280
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800281 res = mFlashlight->findFlashUnits();
282 if (res != OK) {
283 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
284 }
285
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000286 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800287 }
288
289
290 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700291 if (getCameraState(cameraId) == nullptr) {
292 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800293 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000294 if (unavailPhysicalIds.count(cameraId) > 0) {
295 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700296 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 }
298 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800299 }
300
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700301 // Derive primary rear/front cameras, and filter their charactierstics.
302 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700303 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700304 // Assume internal cameras are advertised from the same
305 // provider. If multiple providers are registered at different time,
306 // and each provider contains multiple internal color cameras, the current
307 // logic may filter the characteristics of more than one front/rear color
308 // cameras.
309 Mutex::Autolock l(mServiceLock);
310 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700311 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700312
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800313 return OK;
314}
315
Austin Borgered99f642023-06-01 16:51:35 -0700316void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700317 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800318 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800319 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700320 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
321 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000322 ALOGV("%s: Skipping torch callback for system-only camera device %s",
323 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700324 continue;
325 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700326 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700327 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700328 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
329 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000330 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
331 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700332 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000333 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
334 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700335 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000336 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
337 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
338 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800339 }
340}
341
Mathias Agopian65ab4712010-07-14 17:59:35 -0700342CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800343 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800344 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800345 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800346 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347}
348
Emilian Peevaee727d2017-05-04 16:35:48 +0100349void CameraService::onNewProviderRegistered() {
350 enumerateProviders();
351}
352
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700353void CameraService::filterAPI1SystemCameraLocked(
354 const std::vector<std::string> &normalDeviceIds) {
355 mNormalDeviceIdsWithoutSystemCamera.clear();
356 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700357 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700358 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700359 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
360 continue;
361 }
362 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700363 // All system camera ids will necessarily come after public camera
364 // device ids as per the HAL interface contract.
365 break;
366 }
367 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
368 }
369 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
370 mNormalDeviceIdsWithoutSystemCamera.size());
371}
372
Austin Borgered99f642023-06-01 16:51:35 -0700373status_t CameraService::getSystemCameraKind(const std::string& cameraId,
374 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700375 auto state = getCameraState(cameraId);
376 if (state != nullptr) {
377 *kind = state->getSystemCameraKind();
378 return OK;
379 }
380 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700381 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382}
383
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800384void CameraService::updateCameraNumAndIds() {
385 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700386 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
387 // Excludes hidden secure cameras
388 mNumberOfCameras =
389 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
390 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800391 mNormalDeviceIds =
392 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800394}
395
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700396void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700397 // To claim to be S Performance primary cameras, the cameras must be
398 // backward compatible. So performance class primary camera Ids must be API1
399 // compatible.
400 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
401 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
402 int facing = -1;
403 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800404 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700405 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800406 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700407 if (facing == -1) {
408 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
409 return;
410 }
411
412 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
413 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700414 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
415 if (res == OK) {
416 mPerfClassPrimaryCameraIds.insert(cameraId);
417 } else {
418 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
419 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
420 break;
421 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422
423 if (facing == hardware::CAMERA_FACING_BACK) {
424 firstRearCameraSeen = true;
425 }
426 if (facing == hardware::CAMERA_FACING_FRONT) {
427 firstFrontCameraSeen = true;
428 }
429 }
430
431 if (firstRearCameraSeen && firstFrontCameraSeen) {
432 break;
433 }
434 }
435}
436
Austin Borgered99f642023-06-01 16:51:35 -0700437void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700438 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100439 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
440 if (res != OK) {
441 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
442 return;
443 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000444 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700445 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
446 if (res != OK) {
447 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
448 return;
449 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000450 std::vector<std::string> physicalCameraIds;
451 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700452 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100453 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700454 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100455 }
456
457 {
458 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700459 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000460 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100461 }
462
Austin Borgered99f642023-06-01 16:51:35 -0700463 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100464 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700465 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800466
Austin Borgered99f642023-06-01 16:51:35 -0700467 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100468 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800469
470 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700471 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100472}
473
Austin Borgered99f642023-06-01 16:51:35 -0700474void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800475 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700476 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100477 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700478 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100479 }
480
481 {
482 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700483 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100484 }
485}
486
Austin Borgered99f642023-06-01 16:51:35 -0700487void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800488 CameraDeviceStatus newHalStatus) {
489 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700490 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700491
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800492 StatusInternal newStatus = mapToInternal(newHalStatus);
493
Austin Borgered99f642023-06-01 16:51:35 -0700494 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800495
496 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700497 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700499 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100500
501 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700502 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100503
Austin Borgered99f642023-06-01 16:51:35 -0700504 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700505 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700506 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700507 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700508 return;
509 }
510
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800511 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800512
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800514 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700515 return;
516 }
517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000519 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
520 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800521
522 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
523 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700524 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800525
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800526 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700527 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800528 // Don't do this in updateStatus to avoid deadlock over mServiceLock
529 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700530
Ruben Brunkcc776712015-02-17 20:18:47 -0800531 // Remove cached shim parameters
532 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700533
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800534 // Remove online as well as offline client from the list of active clients,
535 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700536 clientToDisconnectOnline = removeClientLocked(cameraId);
537 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700538 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800539
Austin Borgered99f642023-06-01 16:51:35 -0700540 disconnectClient(cameraId, clientToDisconnectOnline);
541 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700542
Austin Borgered99f642023-06-01 16:51:35 -0700543 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800544 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000546 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
547 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700548 }
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700550 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800551}
Igor Murashkincba2c162013-03-20 15:56:31 -0700552
Austin Borgered99f642023-06-01 16:51:35 -0700553void CameraService::onDeviceStatusChanged(const std::string& id,
554 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800555 CameraDeviceStatus newHalStatus) {
556 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700557 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800558
559 StatusInternal newStatus = mapToInternal(newHalStatus);
560
561 std::shared_ptr<CameraState> state = getCameraState(id);
562
563 if (state == nullptr) {
564 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700565 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800566 return;
567 }
568
569 StatusInternal logicalCameraStatus = state->getStatus();
570 if (logicalCameraStatus != StatusInternal::PRESENT &&
571 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
572 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700573 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800574 return;
575 }
576
577 bool updated = false;
578 if (newStatus == StatusInternal::PRESENT) {
579 updated = state->removeUnavailablePhysicalId(physicalId);
580 } else {
581 updated = state->addUnavailablePhysicalId(physicalId);
582 }
583
584 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700585 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800586 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000587 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800588 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000589 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800590 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700591 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
592 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
593 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700594 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700595 return;
596 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800597 Mutex::Autolock lock(mStatusListenerLock);
598 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700599 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
600 listener->getListenerPid(), listener->getListenerUid())) {
601 ALOGV("Skipping discovery callback for system-only camera device %s",
602 id.c_str());
603 continue;
604 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700605 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700606 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700607 listener->handleBinderStatus(ret,
608 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
609 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
610 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800611 }
612 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700613}
614
Austin Borgered99f642023-06-01 16:51:35 -0700615void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800616 if (clientToDisconnect.get() != nullptr) {
617 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700618 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800619 // Notify the client of disconnection
620 clientToDisconnect->notifyError(
621 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
622 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800623 clientToDisconnect->disconnect();
624 }
625}
626
Austin Borgered99f642023-06-01 16:51:35 -0700627void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800628 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700629 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
630 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
631 if (res != OK) {
632 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700633 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700634 return;
635 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800636 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700637 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800638}
639
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700640
Austin Borgered99f642023-06-01 16:51:35 -0700641void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700642 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
643 Mutex::Autolock al(mTorchStatusMutex);
644 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
645}
646
Austin Borgered99f642023-06-01 16:51:35 -0700647void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800648 int32_t newStrengthLevel) {
649 Mutex::Autolock lock(mStatusListenerLock);
650 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700651 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700652 i->handleBinderStatus(ret,
653 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
654 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800655 }
656}
657
Austin Borgered99f642023-06-01 16:51:35 -0700658void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700659 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800660 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700661 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800662
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800663 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800664 status_t res = getTorchStatusLocked(cameraId, &status);
665 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700666 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700667 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800668 return;
669 }
670 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800671 return;
672 }
673
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800674 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800675 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800676 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
677 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678 return;
679 }
680
Ruben Brunkcc776712015-02-17 20:18:47 -0800681 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700682 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700683 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700684 auto iter = mTorchUidMap.find(cameraId);
685 if (iter != mTorchUidMap.end()) {
686 int oldUid = iter->second.second;
687 int newUid = iter->second.first;
688 BatteryNotifier& notifier(BatteryNotifier::getInstance());
689 if (oldUid != newUid) {
690 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800691 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700692 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700693 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800694 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700695 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700696 }
697 iter->second.second = newUid;
698 } else {
699 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800700 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700701 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700702 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700703 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700704 }
705 }
706 }
707 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700708 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800709}
710
Austin Borger249e6592024-03-10 22:28:11 -0700711bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700712 // Returns false if this is not an automotive device type.
713 if (!isAutomotiveDevice())
714 return false;
715
716 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700717 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700718 return false;
719
720 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
721 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
722 // This isn't a known camera ID, so it's not a system camera.
723 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
724 return false;
725 }
726
727 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
728 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
729 return false;
730 }
731
732 CameraMetadata cameraInfo;
733 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700734 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700735 if (res != OK){
736 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
737 cam_id.c_str());
738 return false;
739 }
740
741 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
742 if (auto_location.count != 1)
743 return false;
744
745 uint8_t location = auto_location.data.u8[0];
746 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
747 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
748 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
749 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
750 return false;
751 }
752
753 return true;
754}
755
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800756Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700757 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100758 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700759 bool hasSystemCameraPermissions =
Austin Borger1c1bee02023-06-01 16:51:35 -0700760 hasPermissionsForSystemCamera(std::string(), CameraThreadState::getCallingPid(),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700761 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700762 switch (type) {
763 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700764 if (hasSystemCameraPermissions) {
765 *numCameras = static_cast<int>(mNormalDeviceIds.size());
766 } else {
767 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
768 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800769 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700770 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700771 if (hasSystemCameraPermissions) {
772 *numCameras = mNumberOfCameras;
773 } else {
774 *numCameras = mNumberOfCamerasWithoutSystemCamera;
775 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800776 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700777 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800778 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700779 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800780 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
781 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700782 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800783 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700784}
785
malikakash73125c62023-07-21 22:44:34 +0000786Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700787 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000788 const int pid = CameraThreadState::getCallingPid();
789 const int uid = CameraThreadState::getCallingUid();
790 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
791 __FUNCTION__, pid, uid);
792 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
793 "Permission Denial: no permission to configure camera id mapping");
794 }
795 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000796 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000797 if (!parseStatus.isOk()) {
798 return parseStatus;
799 }
800 remapCameraIds(cameraIdRemappingMap);
801 return Status::ok();
802}
803
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700804Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
805 /* out */
806 hardware::camera2::impl::CameraMetadataNative* request) {
807 ATRACE_CALL();
808
809 if (!flags::feature_combination_query()) {
810 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
811 "Camera subsystem doesn't support this method!");
812 }
813 if (!mInitialized) {
814 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
815 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
816 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
817 }
818
819 const std::string cameraId = resolveCameraId(unresolvedCameraId,
820 CameraThreadState::getCallingUid());
821
822 binder::Status res;
823 if (request == nullptr) {
824 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
825 "Camera %s: Error creating default request", cameraId.c_str());
826 return res;
827 }
828 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
829 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
830 cameraId, templateId, &tempId);
831 if (!res.isOk()) {
832 ALOGE("%s: Camera %s: failed to map request Template %d",
833 __FUNCTION__, cameraId.c_str(), templateId);
834 return res;
835 }
836
837 if (shouldRejectSystemCameraConnection(cameraId)) {
838 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
839 "request for system only device %s: ", cameraId.c_str());
840 }
841
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700842 CameraMetadata metadata;
843 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
844 if (err == OK) {
845 request->swap(metadata);
846 } else if (err == BAD_VALUE) {
847 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
848 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
849 cameraId.c_str(), templateId, strerror(-err), err);
850 } else {
851 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
852 "Camera %s: Error creating default request for template %d: %s (%d)",
853 cameraId.c_str(), templateId, strerror(-err), err);
854 }
855 return res;
856}
857
858Status CameraService::isSessionConfigurationWithParametersSupported(
859 const std::string& unresolvedCameraId,
860 const SessionConfiguration& sessionConfiguration,
861 /*out*/
862 bool* supported) {
863 ATRACE_CALL();
864
865 if (!flags::feature_combination_query()) {
866 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
867 "Camera subsystem doesn't support this method!");
868 }
869 if (!mInitialized) {
870 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
871 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
872 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
873 }
874
875 const std::string cameraId = resolveCameraId(unresolvedCameraId,
876 CameraThreadState::getCallingUid());
877 if (supported == nullptr) {
878 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
879 unresolvedCameraId.c_str());
880 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
881 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
882 }
883
884 if (shouldRejectSystemCameraConnection(cameraId)) {
885 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
886 "session configuration with parameters support for system only device %s: ",
887 cameraId.c_str());
888 }
889
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700890 *supported = false;
891 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
892 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
893 supported);
894 binder::Status res;
895 switch (ret) {
896 case OK:
897 // Expected, do nothing.
898 break;
899 case INVALID_OPERATION: {
900 std::string msg = fmt::sprintf(
901 "Camera %s: Session configuration query not supported!",
902 cameraId.c_str());
903 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
904 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
905 }
906
907 break;
908 default: {
909 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
910 strerror(-ret), ret);
911 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
912 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
913 msg.c_str());
914 }
915 }
916
917 return res;
918}
919
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800920Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
921 int targetSdkVersion, bool overrideToPortrait,
922 const SessionConfiguration& sessionConfiguration,
923 /*out*/ CameraMetadata* outMetadata) {
924 ATRACE_CALL();
925
926 if (!mInitialized) {
927 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
928 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
929 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
930 }
931
932 const std::string cameraId =
933 resolveCameraId(unresolvedCameraId, CameraThreadState::getCallingUid());
934
935 if (outMetadata == nullptr) {
936 std::string msg =
937 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
938 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
939 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
940 }
941
942 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
943 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
944
945 status_t ret = mCameraProviderManager->getSessionCharacteristics(
946 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
947
948 // TODO(b/303645857): Remove fingerprintable metadata if the caller process does not have
949 // camera access permission.
950
951 Status res = Status::ok();
952 switch (ret) {
953 case OK:
954 // Expected, no handling needed.
955 break;
956 case INVALID_OPERATION: {
957 std::string msg = fmt::sprintf(
958 "Camera %s: Session characteristics query not supported!",
959 cameraId.c_str());
960 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
961 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
962 }
963 break;
964 default: {
965 std::string msg = fmt::sprintf("Camera %s: Error: %s (%d)", cameraId.c_str(),
966 strerror(-ret), ret);
967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
968 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
969 }
970 }
971
972 return res;
973}
974
malikakash82ed4352023-07-21 22:44:34 +0000975Status CameraService::parseCameraIdRemapping(
976 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +0000977 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700978 std::string packageName;
979 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +0000980 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +0000981 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +0000982 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +0000983 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
984 "CameraIdRemapping: Package name cannot be empty");
985 }
malikakash214f6e62023-08-10 23:50:56 +0000986 if (packageIdRemapping.cameraIdsToReplace.size()
987 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +0000988 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
989 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +0000990 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +0000991 }
malikakash214f6e62023-08-10 23:50:56 +0000992 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700993 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
994 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +0000995 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +0000996 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
997 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -0700998 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +0000999 }
1000 if (cameraIdToReplace == updatedCameraId) {
1001 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1002 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1003 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001004 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001005 }
1006 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001007 }
1008 }
1009 return Status::ok();
1010}
1011
1012void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1013 // Acquire mServiceLock and prevent other clients from connecting
1014 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1015 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1016
malikakashedb38962023-09-06 00:03:35 +00001017 // Collect all existing clients for camera Ids that are being
1018 // remapped in the new cameraIdRemapping, but only if they were being used by a
1019 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001020 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001021 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001022 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1023 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001024 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001025 id0.c_str(), id1.c_str());
1026 auto clientDescriptor = mActiveClientManager.get(id0);
1027 if (clientDescriptor != nullptr) {
1028 sp<BasicClient> clientSp = clientDescriptor->getValue();
1029 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001030 // This camera is being used by a targeted packageName and
1031 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001032 clientsToDisconnect.push_back(clientSp);
1033 cameraIdsToUpdate.push_back(id0);
1034 }
1035 }
1036 }
1037 }
1038
malikakashedb38962023-09-06 00:03:35 +00001039 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001040 // Notify the clients about the disconnection.
1041 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001042 CaptureResultExtras{});
1043 }
malikakash82ed4352023-07-21 22:44:34 +00001044
1045 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1046 // blocking other clients from connecting in mServiceLockWrapper if held.
1047 mServiceLock.unlock();
1048
malikakashedb38962023-09-06 00:03:35 +00001049 // Clear calling identity for disconnect() PID checks.
1050 int64_t token = CameraThreadState::clearCallingIdentity();
1051
malikakash82ed4352023-07-21 22:44:34 +00001052 // Disconnect clients.
1053 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001054 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1055 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001056 clientSp->disconnect();
1057 }
1058
malikakashedb38962023-09-06 00:03:35 +00001059 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1060 clientsToDisconnect.clear();
1061
1062 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001063 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001064
1065 {
1066 Mutex::Autolock lock(mCameraIdRemappingLock);
1067 // Update mCameraIdRemapping.
1068 mCameraIdRemapping.clear();
1069 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1070 }
malikakash82ed4352023-07-21 22:44:34 +00001071}
1072
malikakash22af94c2023-12-04 18:13:14 +00001073Status CameraService::injectSessionParams(
1074 const std::string& cameraId,
1075 const CameraMetadata& sessionParams) {
1076 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
1077 const int pid = CameraThreadState::getCallingPid();
1078 const int uid = CameraThreadState::getCallingUid();
1079 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1080 __FUNCTION__, pid, uid);
1081 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1082 "Permission Denial: no permission to inject session params");
1083 }
1084
1085 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1086 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1087
1088 auto clientDescriptor = mActiveClientManager.get(cameraId);
1089 if (clientDescriptor == nullptr) {
1090 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1091 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1092 "No active client for camera id %s", cameraId.c_str());
1093 }
1094
1095 sp<BasicClient> clientSp = clientDescriptor->getValue();
1096 status_t res = clientSp->injectSessionParams(sessionParams);
1097
1098 if (res != OK) {
1099 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1100 "Error injecting session params into camera \"%s\": %s (%d)",
1101 cameraId.c_str(), strerror(-res), res);
1102 }
1103 return Status::ok();
1104}
1105
Austin Borgered99f642023-06-01 16:51:35 -07001106std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1107 const std::string& inputCameraId, int clientUid) {
1108 std::string packageName = getPackageNameFromUid(clientUid);
1109 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001110 Mutex::Autolock lock(mCameraIdRemappingLock);
1111 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1112 packageMapIter != mCameraIdRemapping.end()) {
1113 for (auto& [id0, id1]: packageMapIter->second) {
1114 if (id1 == inputCameraId) {
1115 cameraIds.push_back(id0);
1116 }
1117 }
1118 }
1119 return cameraIds;
1120}
1121
Austin Borgered99f642023-06-01 16:51:35 -07001122std::string CameraService::resolveCameraId(
1123 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001124 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001125 const std::string& packageName) {
1126 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001127 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001128 packageNameVal = getPackageNameFromUid(clientUid);
1129 }
malikakash65d20692023-09-07 01:06:33 +00001130 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001131 // We shouldn't remap cameras for processes with system/vendor UIDs.
1132 return inputCameraId;
1133 }
malikakash82ed4352023-07-21 22:44:34 +00001134 Mutex::Autolock lock(mCameraIdRemappingLock);
1135 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1136 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001137 auto packageMap = packageMapIter->second;
1138 if (auto replacementIdIter = packageMap.find(inputCameraId);
1139 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001140 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001141 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001142 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001143 replacementIdIter->second.c_str());
1144 return replacementIdIter->second;
1145 }
1146 }
1147 return inputCameraId;
1148}
1149
Austin Borger18b30a72022-10-27 12:20:29 -07001150Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001151 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001152 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001153 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001154 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
1155 std::string cameraIdStr = resolveCameraId(
1156 unresolvedCameraId, CameraThreadState::getCallingUid());
1157
Austin Borgered99f642023-06-01 16:51:35 -07001158 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001159 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1160 "characteristics for system only device %s: ", cameraIdStr.c_str());
1161 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001162
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001163 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001164 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001165 return STATUS_ERROR(ERROR_DISCONNECTED,
1166 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001167 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001168 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001169 CameraThreadState::getCallingPid(), CameraThreadState::getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001170 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1171 if (hasSystemCameraPermissions) {
1172 cameraIdBound = mNumberOfCameras;
1173 }
1174 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001175 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1176 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001177 }
1178
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001179 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001180 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001181 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001182 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001183 if (err != OK) {
1184 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1185 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1186 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001187 logServiceError(std::string("Error retrieving camera info from device ")
1188 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001189 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001190
Ruben Brunkcc776712015-02-17 20:18:47 -08001191 return ret;
1192}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001193
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001194std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001195 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
1196 auto callingPid = CameraThreadState::getCallingPid();
1197 auto callingUid = CameraThreadState::getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001198 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1199 callingPid, callingUid, /* checkCameraPermissions= */ false);
1200 if (systemCameraPermissions || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001201 deviceIds = &mNormalDeviceIds;
1202 }
1203 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001204 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001205 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001206 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001207 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001208
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001209 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001210}
1211
Austin Borgered99f642023-06-01 16:51:35 -07001212std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001213 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001214 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001215}
1216
Austin Borgered99f642023-06-01 16:51:35 -07001217Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001218 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001219 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001220
malikakashedb38962023-09-06 00:03:35 +00001221 const std::string cameraId = resolveCameraId(unresolvedCameraId,
1222 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -07001223
Zhijun He2b59be82013-09-25 10:14:30 -07001224 if (!cameraInfo) {
1225 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001226 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001227 }
1228
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001229 if (!mInitialized) {
1230 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001231 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001232 return STATUS_ERROR(ERROR_DISCONNECTED,
1233 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001234 }
1235
Austin Borgered99f642023-06-01 16:51:35 -07001236 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001237 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001238 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001239 }
1240
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001241 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001242
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001243 bool overrideForPerfClass =
1244 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001245 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001246 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001247 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001248 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001249 if (res == NAME_NOT_FOUND) {
1250 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001251 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001252 strerror(-res), res);
1253 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001254 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1255 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001256 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001257 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001258 strerror(-res), res);
1259 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001260 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001261 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001262 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1263 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001264 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001265 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001266 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001267 int callingPid = CameraThreadState::getCallingPid();
1268 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001269 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001270 // If it's not calling from cameraserver, check the permission only if
1271 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1272 // it would've already been checked in shouldRejectSystemCameraConnection.
Austin Borger249e6592024-03-10 22:28:11 -07001273 bool checkPermissionForCamera = hasPermissionsForCamera(cameraId, callingPid, callingUid);
Emilian Peeve20c6372018-08-14 18:45:53 +01001274 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001275 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001276 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001277 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001278 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001279 &tagsRemoved);
1280 if (res != OK) {
1281 cameraInfo->clear();
1282 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1283 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001284 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001285 }
1286 }
1287
1288 if (!tagsRemoved.empty()) {
1289 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1290 tagsRemoved.data(), tagsRemoved.size());
1291 if (res != OK) {
1292 cameraInfo->clear();
1293 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001294 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001295 strerror(-res), res);
1296 }
1297 }
1298
Zhijun He2b59be82013-09-25 10:14:30 -07001299 return ret;
1300}
1301
malikakashedb38962023-09-06 00:03:35 +00001302Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001303 int32_t* torchStrength) {
1304 ATRACE_CALL();
1305 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001306
malikakashedb38962023-09-06 00:03:35 +00001307 const std::string cameraId = resolveCameraId(
malikakash65d20692023-09-07 01:06:33 +00001308 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001309 if (!mInitialized) {
1310 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1311 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1312 }
1313
1314 if(torchStrength == NULL) {
1315 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1316 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1317 }
1318
Austin Borgered99f642023-06-01 16:51:35 -07001319 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001320 if (res != OK) {
1321 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001322 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001323 strerror(-res), res);
1324 }
1325 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1326 return Status::ok();
1327}
1328
Austin Borgered99f642023-06-01 16:51:35 -07001329std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001330 time_t now = time(nullptr);
1331 char formattedTime[64];
1332 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001333 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001334}
1335
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001336Status CameraService::getCameraVendorTagDescriptor(
1337 /*out*/
1338 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001339 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001340 if (!mInitialized) {
1341 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001342 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001343 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001344 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1345 if (globalDescriptor != nullptr) {
1346 *desc = *(globalDescriptor.get());
1347 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001348 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001349}
1350
Emilian Peev71c73a22017-03-21 16:35:51 +00001351Status CameraService::getCameraVendorTagCache(
1352 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1353 ATRACE_CALL();
1354 if (!mInitialized) {
1355 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1356 return STATUS_ERROR(ERROR_DISCONNECTED,
1357 "Camera subsystem not available");
1358 }
1359 sp<VendorTagDescriptorCache> globalCache =
1360 VendorTagDescriptorCache::getGlobalVendorTagCache();
1361 if (globalCache != nullptr) {
1362 *cache = *(globalCache.get());
1363 }
1364 return Status::ok();
1365}
1366
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001367void CameraService::clearCachedVariables() {
1368 BasicClient::BasicClient::sCameraService = nullptr;
1369}
1370
Austin Borgered99f642023-06-01 16:51:35 -07001371std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001372 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001373 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001374
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001375 int deviceVersion = 0;
1376
Emilian Peevf53f66e2017-04-11 14:29:43 +01001377 status_t res;
1378 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001379 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001380 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001381 if (res != OK || transport == IPCTransport::INVALID) {
1382 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001383 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001384 return std::make_pair(-1, IPCTransport::INVALID) ;
1385 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001386 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001387
Emilian Peevf53f66e2017-04-11 14:29:43 +01001388 hardware::CameraInfo info;
1389 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001390 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001391 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001392 if (res != OK) {
1393 return std::make_pair(-1, IPCTransport::INVALID);
1394 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001395 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001396 if (orientation) {
1397 *orientation = info.orientation;
1398 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001399 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001400
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001401 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001402}
1403
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001404Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001405 switch(err) {
1406 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001407 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001408 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001409 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1410 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001411 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001412 return STATUS_ERROR(ERROR_DISCONNECTED,
1413 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001414 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001415 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1416 "Camera HAL encountered error %d: %s",
1417 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001418 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001419}
1420
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001421Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001422 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1423 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001424 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001425 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001426 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001427 bool forceSlowJpegMode, const std::string& originalCameraId,
1428 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001429 // For HIDL devices
1430 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1431 // Create CameraClient based on device version reported by the HAL.
1432 int deviceVersion = deviceVersionAndTransport.first;
1433 switch(deviceVersion) {
1434 case CAMERA_DEVICE_API_VERSION_1_0:
1435 ALOGE("Camera using old HAL version: %d", deviceVersion);
1436 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1437 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001438 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001439 break;
1440 case CAMERA_DEVICE_API_VERSION_3_0:
1441 case CAMERA_DEVICE_API_VERSION_3_1:
1442 case CAMERA_DEVICE_API_VERSION_3_2:
1443 case CAMERA_DEVICE_API_VERSION_3_3:
1444 case CAMERA_DEVICE_API_VERSION_3_4:
1445 case CAMERA_DEVICE_API_VERSION_3_5:
1446 case CAMERA_DEVICE_API_VERSION_3_6:
1447 case CAMERA_DEVICE_API_VERSION_3_7:
1448 break;
1449 default:
1450 // Should not be reachable
1451 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1452 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1453 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001454 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001455 }
1456 }
1457 if (effectiveApiLevel == API_1) { // Camera1 API route
1458 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001459 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001460 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001461 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001462 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1463 forceSlowJpegMode);
1464 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1465 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001466 } else { // Camera2 API route
1467 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1468 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001469 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001470 cameraService->mCameraServiceProxyWrapper,
1471 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001472 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001473 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001474 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001475 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001476 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001477}
1478
Austin Borgered99f642023-06-01 16:51:35 -07001479std::string CameraService::toString(std::set<userid_t> intSet) {
1480 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001481 bool first = true;
1482 for (userid_t i : intSet) {
1483 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001484 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001485 first = false;
1486 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001487 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001488 }
1489 }
Austin Borgered99f642023-06-01 16:51:35 -07001490 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001491}
1492
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001493int32_t CameraService::mapToInterface(TorchModeStatus status) {
1494 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1495 switch (status) {
1496 case TorchModeStatus::NOT_AVAILABLE:
1497 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1498 break;
1499 case TorchModeStatus::AVAILABLE_OFF:
1500 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1501 break;
1502 case TorchModeStatus::AVAILABLE_ON:
1503 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1504 break;
1505 default:
1506 ALOGW("Unknown new flash status: %d", status);
1507 }
1508 return serviceStatus;
1509}
1510
1511CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1512 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1513 switch (status) {
1514 case CameraDeviceStatus::NOT_PRESENT:
1515 serviceStatus = StatusInternal::NOT_PRESENT;
1516 break;
1517 case CameraDeviceStatus::PRESENT:
1518 serviceStatus = StatusInternal::PRESENT;
1519 break;
1520 case CameraDeviceStatus::ENUMERATING:
1521 serviceStatus = StatusInternal::ENUMERATING;
1522 break;
1523 default:
1524 ALOGW("Unknown new HAL device status: %d", status);
1525 }
1526 return serviceStatus;
1527}
1528
1529int32_t CameraService::mapToInterface(StatusInternal status) {
1530 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1531 switch (status) {
1532 case StatusInternal::NOT_PRESENT:
1533 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1534 break;
1535 case StatusInternal::PRESENT:
1536 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1537 break;
1538 case StatusInternal::ENUMERATING:
1539 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1540 break;
1541 case StatusInternal::NOT_AVAILABLE:
1542 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1543 break;
1544 case StatusInternal::UNKNOWN:
1545 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1546 break;
1547 default:
1548 ALOGW("Unknown new internal device status: %d", status);
1549 }
1550 return serviceStatus;
1551}
1552
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001553Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001554 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001555
Austin Borgered99f642023-06-01 16:51:35 -07001556 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001557 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001558 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001559 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001560 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1561 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001562 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001563 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001564 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001565 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001566 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001567 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001568 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001569}
1570
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001571Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001572 /*out*/
1573 CameraParameters* parameters) {
1574
1575 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1576
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001578
1579 if (parameters == NULL) {
1580 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001582 }
1583
malikakashedb38962023-09-06 00:03:35 +00001584 std::string unresolvedCameraId = std::to_string(cameraId);
1585 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1586 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001587
1588 // Check if we already have parameters
1589 {
1590 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001591 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001592 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001593 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001594 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001595 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001596 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001597 }
1598 CameraParameters p = cameraState->getShimParams();
1599 if (!p.isEmpty()) {
1600 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001601 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001602 }
1603 }
1604
Jayant Chowdhary12361932018-08-27 14:46:13 -07001605 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001606 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001607 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001609 // Error already logged by callee
1610 return ret;
1611 }
1612
1613 // Check for parameters again
1614 {
1615 // Scope for service lock
1616 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001617 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001618 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001619 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001621 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001622 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001623 CameraParameters p = cameraState->getShimParams();
1624 if (!p.isEmpty()) {
1625 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001627 }
1628 }
1629
Ruben Brunkcc776712015-02-17 20:18:47 -08001630 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1631 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001633}
1634
Austin Borgered99f642023-06-01 16:51:35 -07001635Status CameraService::validateConnectLocked(const std::string& cameraId,
1636 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001637 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001638
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001639#ifdef __BRILLO__
1640 UNUSED(clientName8);
1641 UNUSED(clientUid);
1642 UNUSED(clientPid);
1643 UNUSED(originalClientPid);
1644#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001645 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1646 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001647 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001648 return allowed;
1649 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001650#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001651
Jayant Chowdhary12361932018-08-27 14:46:13 -07001652 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001653
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001654 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1656 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001657 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001658 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001659 }
1660
Ruben Brunkcc776712015-02-17 20:18:47 -08001661 if (getCameraState(cameraId) == nullptr) {
1662 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001663 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001664 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001665 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001666 }
1667
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001668 status_t err = checkIfDeviceIsUsable(cameraId);
1669 if (err != NO_ERROR) {
1670 switch(err) {
1671 case -ENODEV:
1672 case -EBUSY:
1673 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001674 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001675 default:
1676 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001677 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001678 }
1679 }
1680 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001681}
1682
Austin Borgered99f642023-06-01 16:51:35 -07001683Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1684 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001685 /*out*/int& originalClientPid) const {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001686 int callingPid = CameraThreadState::getCallingPid();
1687 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001688
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001689 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001690 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001691 clientUid = callingUid;
1692 } else if (!isTrustedCallingUid(callingUid)) {
1693 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1694 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001695 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1696 "Untrusted caller (calling PID %d, UID %d) trying to "
1697 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001698 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001699 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001700 }
1701
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001702 // Check if we can trust clientPid
1703 if (clientPid == USE_CALLING_PID) {
1704 clientPid = callingPid;
1705 } else if (!isTrustedCallingUid(callingUid)) {
1706 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1707 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001708 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1709 "Untrusted caller (calling PID %d, UID %d) trying to "
1710 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001711 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001712 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001713 }
1714
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001715 if (shouldRejectSystemCameraConnection(cameraId)) {
1716 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1717 cameraId.c_str());
1718 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001719 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001720 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001721 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1722 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001723 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001724 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001725 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001726
1727 }
1728
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001729 // If it's not calling from cameraserver, check the permission if the
1730 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1731 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001732 bool checkPermissionForCamera =
1733 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001734 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001735 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001736 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001737 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1738 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001739 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001740 }
1741
Svet Ganova453d0d2018-01-11 15:37:58 -08001742 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001743 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001744 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001745 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1746 clientPid, clientUid);
1747 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001748 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1749 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001750 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001751 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001752 }
1753
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001754 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1755 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1756 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1757 if ((!isAutomotivePrivilegedClient(callingUid) ||
1758 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1759 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001760 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1761 return STATUS_ERROR_FMT(ERROR_DISABLED,
1762 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001763 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001764 }
1765
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001766 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1767 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001768 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001769 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001770
Ruben Brunk6267b532015-04-30 17:44:07 -07001771 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001772
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001773 // For non-system clients : Only allow clients who are being used by the current foreground
1774 // device user, unless calling from our own process.
1775 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001776 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001777 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1778 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001779 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001780 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1781 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001782 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001783 }
1784
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001785 if (flags::camera_hsum_permission()) {
1786 // If the System User tries to access the camera when the device is running in
1787 // headless system user mode, ensure that client has the required permission
1788 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001789 if (isHeadlessSystemUserMode()
1790 && (clientUserId == USER_SYSTEM)
1791 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001792 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1793 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1794 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1795 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001796 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001797 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001798 }
1799
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001800 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001801}
1802
Austin Borgered99f642023-06-01 16:51:35 -07001803status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001804 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001805 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001806 if (cameraState == nullptr) {
1807 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001808 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001809 return -ENODEV;
1810 }
1811
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001812 StatusInternal currentStatus = cameraState->getStatus();
1813 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001814 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001815 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001816 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001817 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001818 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001819 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001820 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001821 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001822
Ruben Brunkcc776712015-02-17 20:18:47 -08001823 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001824}
1825
Ruben Brunkcc776712015-02-17 20:18:47 -08001826void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001827 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001828
Ruben Brunkcc776712015-02-17 20:18:47 -08001829 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001830 auto clientDescriptor =
1831 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001832 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001833 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1834
1835 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001836 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001837
1838 if (evicted.size() > 0) {
1839 // This should never happen - clients should already have been removed in disconnect
1840 for (auto& i : evicted) {
1841 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001842 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001843 }
1844
1845 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1846 __FUNCTION__);
1847 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001848
1849 // And register a death notification for the client callback. Do
1850 // this last to avoid Binder policy where a nested Binder
1851 // transaction might be pre-empted to service the client death
1852 // notification if the client process dies before linkToDeath is
1853 // invoked.
1854 sp<IBinder> remoteCallback = client->getRemote();
1855 if (remoteCallback != nullptr) {
1856 remoteCallback->linkToDeath(this);
1857 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001858}
1859
Austin Borgered99f642023-06-01 16:51:35 -07001860status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1861 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1862 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001863 /*out*/
1864 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001865 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001866 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001867 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001868 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001869 DescriptorPtr clientDescriptor;
1870 {
1871 if (effectiveApiLevel == API_1) {
1872 // If we are using API1, any existing client for this camera ID with the same remote
1873 // should be returned rather than evicted to allow MediaRecorder to work properly.
1874
1875 auto current = mActiveClientManager.get(cameraId);
1876 if (current != nullptr) {
1877 auto clientSp = current->getValue();
1878 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001879 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001880 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001881 " API level, evicting prior client...");
1882 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001883 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001884 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001885 *client = clientSp;
1886 return NO_ERROR;
1887 }
1888 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001889 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001890 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001891
Ruben Brunkcc776712015-02-17 20:18:47 -08001892 // Get state for the given cameraId
1893 auto state = getCameraState(cameraId);
1894 if (state == nullptr) {
1895 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001896 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001897 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001898 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001899 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001900
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001901 sp<IServiceManager> sm = defaultServiceManager();
1902 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
1903 if (!binder && isAutomotivePrivilegedClient(CameraThreadState::getCallingUid())) {
1904 // If processinfo service is not available and the client is automotive privileged
1905 // client used for safety critical uses cases such as rear-view and surround-view which
1906 // needs to be available before android boot completes, then use the hardcoded values
1907 // for the process state and priority score. As this scenario is before android system
1908 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1909 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1910 // visible on the top.
1911 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1912 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1913 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1914 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1915 } else {
1916 // Get current active client PIDs
1917 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1918 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001919
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001920 std::vector<int> priorityScores(ownerPids.size());
1921 std::vector<int> states(ownerPids.size());
1922
1923 // Get priority scores of all active PIDs
1924 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1925 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1926 if (err != OK) {
1927 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1928 return err;
1929 }
1930
1931 // Update all active clients' priorities
1932 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1933 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1934 pidToPriorityMap.emplace(ownerPids[i],
1935 resource_policy::ClientPriority(priorityScores[i], states[i],
1936 /* isVendorClient won't get copied over*/ false,
1937 /* oomScoreOffset won't get copied over*/ 0));
1938 }
1939 mActiveClientManager.updatePriorities(pidToPriorityMap);
1940
1941 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1942 int32_t actualState = states[states.size() - 1];
1943
1944 // Make descriptor for incoming client. We store the oomScoreOffset
1945 // since we might need it later on new handleEvictionsLocked and
1946 // ProcessInfoService would not take that into account.
1947 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1948 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1949 state->getConflicting(), actualScore, clientPid, actualState,
1950 oomScoreOffset, systemNativeClient);
1951 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001952
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001953 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1954
Ruben Brunkcc776712015-02-17 20:18:47 -08001955 // Find clients that would be evicted
1956 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1957
1958 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1959 // background, so we cannot do evictions
1960 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1961 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1962 " priority).", clientPid);
1963
1964 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001965 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001966 auto incompatibleClients =
1967 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1968
Austin Borgered99f642023-06-01 16:51:35 -07001969 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1970 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1971 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001972 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001973
1974 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001975 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001976 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001977 i->getKey().c_str(),
1978 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001979 i->getOwnerId(), i->getPriority().getScore(),
1980 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001981 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07001982 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
1983 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00001984 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001985 }
1986
1987 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07001988 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08001989 mEventLog.add(msg);
1990
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07001991 auto current = mActiveClientManager.get(cameraId);
1992 if (current != nullptr) {
1993 return -EBUSY; // CAMERA_IN_USE
1994 } else {
1995 return -EUSERS; // MAX_CAMERAS_IN_USE
1996 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001997 }
1998
1999 for (auto& i : evicted) {
2000 sp<BasicClient> clientSp = i->getValue();
2001 if (clientSp.get() == nullptr) {
2002 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2003
2004 // TODO: Remove this
2005 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2006 __FUNCTION__);
2007 mActiveClientManager.remove(i);
2008 continue;
2009 }
2010
2011 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002012 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002013 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002014
Ruben Brunkcc776712015-02-17 20:18:47 -08002015 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002016 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002017 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2018 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002019 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002020 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002021 i->getPriority().getState(), cameraId.c_str(),
2022 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002023 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002024
2025 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002026 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002027 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002028 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002029 }
2030
Ruben Brunkcc776712015-02-17 20:18:47 -08002031 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2032 // other clients from connecting in mServiceLockWrapper if held
2033 mServiceLock.unlock();
2034
2035 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002036 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002037
2038 // Destroy evicted clients
2039 for (auto& i : evictedClients) {
2040 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002041 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002042 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002043
Jayant Chowdhary12361932018-08-27 14:46:13 -07002044 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002045
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002046 for (const auto& i : evictedClients) {
2047 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002048 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002049 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2050 if (ret == TIMED_OUT) {
2051 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002052 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2053 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002054 return -EBUSY;
2055 }
2056 if (ret != NO_ERROR) {
2057 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002058 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2059 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002060 return ret;
2061 }
2062 }
2063
2064 evictedClients.clear();
2065
Ruben Brunkcc776712015-02-17 20:18:47 -08002066 // Once clients have been disconnected, relock
2067 mServiceLock.lock();
2068
2069 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2070 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2071 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002072 }
2073
Ruben Brunkcc776712015-02-17 20:18:47 -08002074 *partial = clientDescriptor;
2075 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002076}
2077
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002078Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002079 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002080 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002081 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002082 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002083 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002084 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002085 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002086 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002087 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002088 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002089
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002090 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002091 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002092
malikakashedb38962023-09-06 00:03:35 +00002093 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
2094 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
2095 CameraThreadState::getCallingUid());
2096
Ruben Brunkcc776712015-02-17 20:18:47 -08002097 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002098 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2099 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002100 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002101 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002102
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002103 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002104 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
2105 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002107 }
2108
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002109 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002110
2111 const sp<IServiceManager> sm(defaultServiceManager());
2112 const auto& mActivityManager = getActivityManager();
2113 if (mActivityManager) {
2114 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2115 CameraThreadState::getCallingUid(),
2116 CameraThreadState::getCallingPid());
2117 }
2118
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002119 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002120}
2121
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002122bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2123 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002124 // If the client is not a vendor client, don't add listener if
2125 // a) the camera is a publicly hidden secure camera OR
2126 // b) the camera is a system only camera and the client doesn't
2127 // have android.permission.SYSTEM_CAMERA permissions.
2128 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2129 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002130 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002131 return true;
2132 }
2133 return false;
2134}
2135
Austin Borgered99f642023-06-01 16:51:35 -07002136bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002137 // Rules for rejection:
2138 // 1) If cameraserver tries to access this camera device, accept the
2139 // connection.
2140 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002141 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002142 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2143 // and the serving thread is a non hwbinder thread, the client must have
2144 // android.permission.SYSTEM_CAMERA permissions to connect.
2145
2146 int cPid = CameraThreadState::getCallingPid();
2147 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002148 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002149 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2150 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002151 // This isn't a known camera ID, so it's not a system camera
2152 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2153 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002154 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002155
2156 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002157 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002158 return false;
2159 }
2160 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002161 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002162 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2163 return true;
2164 }
2165 // (3) Here we only check for permissions if it is a system only camera device. This is since
2166 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2167 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2168 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002169 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002170 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002171 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2172 cameraId.c_str());
2173 return true;
2174 }
2175
2176 return false;
2177}
2178
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002179Status CameraService::connectDevice(
2180 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002181 const std::string& unresolvedCameraId,
2182 const std::string& clientPackageName,
2183 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002184 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002185 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08002186 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002187 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002188
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002189 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002190 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002191 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002192 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002193 int callingPid = CameraThreadState::getCallingPid();
Austin Borger249e6592024-03-10 22:28:11 -07002194 int callingUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002195 bool systemNativeClient = false;
2196 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002197 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002198 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002199 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002200 }
Austin Borger249e6592024-03-10 22:28:11 -07002201
malikakashedb38962023-09-06 00:03:35 +00002202 const std::string cameraId = resolveCameraId(
2203 unresolvedCameraId,
Austin Borger249e6592024-03-10 22:28:11 -07002204 callingUid,
malikakashedb38962023-09-06 00:03:35 +00002205 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002206
2207 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002208 std::string msg =
2209 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2210 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2211 cameraId.c_str());
2212 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2213 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002214 }
2215
Austin Borger9bfa0a72022-08-03 17:50:40 -07002216 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002217 if (clientUid == USE_CALLING_UID) {
2218 clientUserId = multiuser_get_user_id(callingUid);
2219 }
2220
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002221 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2222 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002223 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2224 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002225 std::string msg = "Camera disabled by device policy";
2226 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2227 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002228 }
2229
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002230 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002231 if (oomScoreOffset > 0
2232 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002233 callingUid)
2234 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002235 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002236 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002237 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2238 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2239 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002240 }
2241
Austin Borgered99f642023-06-01 16:51:35 -07002242 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2243 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002244 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002245 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002246 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002247
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002248 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002249 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002250 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002251 }
2252
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002253 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002254 Mutex::Autolock lock(mServiceLock);
2255
2256 // Clear the previous cached logs and reposition the
2257 // file offset to beginning of the file to log new data.
2258 // If either truncate or lseek fails, close the previous file and create a new one.
2259 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2260 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2261 // Close the previous memfd.
2262 close(mMemFd);
2263 // If failure to wipe the data, then create a new file and
2264 // assign the new value to mMemFd.
2265 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2266 if (mMemFd == -1) {
2267 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2268 }
2269 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002270 const sp<IServiceManager> sm(defaultServiceManager());
2271 const auto& mActivityManager = getActivityManager();
2272 if (mActivityManager) {
2273 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002274 callingUid,
2275 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002276 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002277 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002278}
2279
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002280bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2281 int callingPid, int callingUid) {
2282 if (!isAutomotiveDevice()) {
2283 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2284 }
2285
2286 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2287 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2288 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2289 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2290 "using camera %s", callingUid, cam_id.c_str());
2291 return false;
2292 }
2293
2294 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2295 return true;
2296 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2297 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002298 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2299 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002300 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2301 return false;
2302 } else {
2303 return true;
2304 }
2305 }
2306 return false;
2307}
2308
Austin Borgered99f642023-06-01 16:51:35 -07002309std::string CameraService::getPackageNameFromUid(int clientUid) {
2310 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002311
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002312 sp<IPermissionController> permCtrl;
2313 if (flags::cache_permission_services()) {
2314 permCtrl = getPermissionController();
2315 } else {
2316 sp<IServiceManager> sm = defaultServiceManager();
2317#pragma clang diagnostic push
2318#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2319 // Using deprecated function to preserve functionality until the
2320 // cache_permission_services flag is removed.
2321 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2322#pragma clang diagnostic pop
2323 if (binder == 0) {
2324 ALOGE("Cannot get permission service");
2325 permCtrl = nullptr;
2326 } else {
2327 permCtrl = interface_cast<IPermissionController>(binder);
2328 }
2329 }
2330
2331 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002332 // Return empty package name and the further interaction
2333 // with camera will likely fail
2334 return packageName;
2335 }
2336
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002337 Vector<String16> packages;
2338
2339 permCtrl->getPackagesForUid(clientUid, packages);
2340
2341 if (packages.isEmpty()) {
2342 ALOGE("No packages for calling UID %d", clientUid);
2343 // Return empty package name and the further interaction
2344 // with camera will likely fail
2345 return packageName;
2346 }
2347
2348 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002349 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002350
2351 return packageName;
2352}
2353
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002354template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002355Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2356 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2357 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002358 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002359 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002360 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002361 binder::Status ret = binder::Status::ok();
2362
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002363 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002364 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002365 int packageUid = (clientUid == USE_CALLING_UID) ?
2366 CameraThreadState::getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002367 if (clientPackageNameMaybe.size() <= 0) {
2368 // NDK calls don't come with package names, but we need one for various cases.
2369 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2370 // do exist. For all authentication cases, all packages under the same UID get the
2371 // same permissions, so picking any associated package name is sufficient. For some
2372 // other cases, this may give inaccurate names for clients in logs.
2373 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002374 clientPackageName = getPackageNameFromUid(packageUid);
2375 } else {
2376 clientPackageName = clientPackageNameMaybe;
2377 }
2378
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002379 int originalClientPid = 0;
2380
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002381 int packagePid = (clientPid == USE_CALLING_PID) ?
2382 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002383 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002384 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002385 static_cast<int>(effectiveApiLevel));
2386
Shuzhen Wang316781a2020-08-18 18:11:01 -07002387 nsecs_t openTimeNs = systemTime();
2388
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002389 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002390 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002391 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002392
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002393 {
2394 // Acquire mServiceLock and prevent other clients from connecting
2395 std::unique_ptr<AutoConditionLock> lock =
2396 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2397
2398 if (lock == nullptr) {
2399 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2400 , clientPid);
2401 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2402 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002403 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002404 }
2405
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002406 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002407 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002408 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2409 return ret;
2410 }
2411
2412 // Check the shim parameters after acquiring lock, if they have already been updated and
2413 // we were doing a shim update, return immediately
2414 if (shimUpdateOnly) {
2415 auto cameraState = getCameraState(cameraId);
2416 if (cameraState != nullptr) {
2417 if (!cameraState->getShimParams().isEmpty()) return ret;
2418 }
2419 }
2420
2421 status_t err;
2422
2423 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002424 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002425 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002426 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2427 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002428 switch (err) {
2429 case -ENODEV:
2430 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2431 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002432 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002433 case -EBUSY:
2434 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2435 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002436 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002437 case -EUSERS:
2438 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2439 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002440 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002441 default:
2442 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2443 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002444 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002445 }
2446 }
2447
2448 if (clientTmp.get() != nullptr) {
2449 // Handle special case for API1 MediaRecorder where the existing client is returned
2450 device = static_cast<CLIENT*>(clientTmp.get());
2451 return ret;
2452 }
2453
2454 // give flashlight a chance to close devices if necessary.
2455 mFlashlight->prepareDeviceOpen(cameraId);
2456
Austin Borger18b30a72022-10-27 12:20:29 -07002457 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002458 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002459 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2460 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002461 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002462 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002463 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002464 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002465 }
2466
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002467 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002468 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002469 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002470 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002471 clientFeatureId, cameraId, api1CameraId, facing,
2472 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002473 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002474 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002475 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002476 return ret;
2477 }
2478 client = static_cast<CLIENT*>(tmp.get());
2479
2480 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2481 __FUNCTION__);
2482
Austin Borgered99f642023-06-01 16:51:35 -07002483 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002484 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002485 if (err != OK) {
2486 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002487 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002488 mServiceLock.unlock();
2489 client->disconnect();
2490 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002491 switch(err) {
2492 case BAD_VALUE:
2493 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002494 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002495 case -EBUSY:
2496 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002497 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002498 case -EUSERS:
2499 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2500 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002501 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002502 case PERMISSION_DENIED:
2503 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002504 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002505 case -EACCES:
2506 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002507 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002508 case -ENODEV:
2509 default:
2510 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002511 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002512 strerror(-err), err);
2513 }
2514 }
2515
2516 // Update shim paremeters for legacy clients
2517 if (effectiveApiLevel == API_1) {
2518 // Assume we have always received a Client subclass for API1
2519 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2520 String8 rawParams = shimClient->getParameters();
2521 CameraParameters params(rawParams);
2522
2523 auto cameraState = getCameraState(cameraId);
2524 if (cameraState != nullptr) {
2525 cameraState->setShimParams(params);
2526 } else {
2527 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002528 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002529 }
2530 }
2531
Ravneetaeb20dc2022-03-30 05:33:03 +00002532 // Enable/disable camera service watchdog
2533 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2534
Emilian Peev6d45db82024-01-18 20:11:54 +00002535 CameraMetadata chars;
2536 bool rotateAndCropSupported = true;
2537 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2538 &chars, overrideToPortrait);
2539 if (err == OK) {
2540 auto availableRotateCropEntry = chars.find(
2541 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2542 if (availableRotateCropEntry.count <= 1) {
2543 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002544 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002545 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002546 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2547 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002548 }
2549
Emilian Peev6d45db82024-01-18 20:11:54 +00002550 if (rotateAndCropSupported) {
2551 // Set rotate-and-crop override behavior
2552 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2553 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2554 } else if (overrideToPortrait && portraitRotation != 0) {
2555 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2556 switch (portraitRotation) {
2557 case 90:
2558 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2559 break;
2560 case 180:
2561 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2562 break;
2563 case 270:
2564 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2565 break;
2566 default:
2567 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2568 break;
2569 }
2570 client->setRotateAndCropOverride(rotateAndCropMode);
2571 } else {
2572 client->setRotateAndCropOverride(
2573 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2574 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2575 }
2576 }
2577
2578 bool autoframingSupported = true;
2579 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2580 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2581 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2582 autoframingSupported = false;
2583 }
2584
2585 if (autoframingSupported) {
2586 // Set autoframing override behaviour
2587 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2588 client->setAutoframingOverride(mOverrideAutoframingMode);
2589 } else {
2590 client->setAutoframingOverride(
2591 mCameraServiceProxyWrapper->getAutoframingOverride(
2592 clientPackageName));
2593 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002594 }
2595
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002596 bool isCameraPrivacyEnabled;
2597 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002598 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002599 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2600 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2601 } else {
2602 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002603 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002604 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002605
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002606 if (client->supportsCameraMute()) {
2607 client->setCameraMute(
2608 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2609 } else if (isCameraPrivacyEnabled) {
2610 // no camera mute supported, but privacy is on! => disconnect
2611 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2612 client->getPackageName().c_str(), cameraId.c_str());
2613 // Do not hold mServiceLock while disconnecting clients, but
2614 // retain the condition blocking other clients from connecting
2615 // in mServiceLockWrapper if held.
2616 mServiceLock.unlock();
2617 // Clear caller identity temporarily so client disconnect PID
2618 // checks work correctly
2619 int64_t token = CameraThreadState::clearCallingIdentity();
2620 // Note AppOp to trigger the "Unblock" dialog
2621 client->noteAppOp();
2622 client->disconnect();
2623 CameraThreadState::restoreCallingIdentity(token);
2624 // Reacquire mServiceLock
2625 mServiceLock.lock();
2626
2627 return STATUS_ERROR_FMT(ERROR_DISABLED,
2628 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002629 }
2630
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002631 if (shimUpdateOnly) {
2632 // If only updating legacy shim parameters, immediately disconnect client
2633 mServiceLock.unlock();
2634 client->disconnect();
2635 mServiceLock.lock();
2636 } else {
2637 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002638 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002639 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002640
2641 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002642 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002643 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002644 } // lock is destroyed, allow further connect calls
2645
2646 // Important: release the mutex here so the client can call back into the service from its
2647 // destructor (can be at the end of the call)
2648 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002649
2650 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002651 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002652 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002653
Cliff Wud3a05312021-04-26 23:07:31 +08002654 {
2655 Mutex::Autolock lock(mInjectionParametersLock);
2656 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2657 mInjectionInitPending = false;
2658 status_t res = NO_ERROR;
2659 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2660 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002661 sp<BasicClient> clientSp = clientDescriptor->getValue();
2662 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2663 if(res != OK) {
2664 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2665 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002666 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002667 }
2668 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002669 if (res != OK) {
2670 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2671 }
2672 } else {
2673 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002674 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002675 res = NO_INIT;
2676 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2677 }
2678 }
2679 }
2680
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002681 return ret;
2682}
2683
Austin Borgered99f642023-06-01 16:51:35 -07002684status_t CameraService::addOfflineClient(const std::string &cameraId,
2685 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002686 if (offlineClient.get() == nullptr) {
2687 return BAD_VALUE;
2688 }
2689
2690 {
2691 // Acquire mServiceLock and prevent other clients from connecting
2692 std::unique_ptr<AutoConditionLock> lock =
2693 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2694
2695 if (lock == nullptr) {
2696 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2697 , __FUNCTION__, offlineClient->getClientPid());
2698 return TIMED_OUT;
2699 }
2700
2701 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2702 if (onlineClientDesc.get() == nullptr) {
2703 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2704 cameraId.c_str());
2705 return BAD_VALUE;
2706 }
2707
2708 // Offline clients do not evict or conflict with other online devices. Resource sharing
2709 // conflicts are handled by the camera provider which will either succeed or fail before
2710 // reaching this method.
2711 const auto& onlinePriority = onlineClientDesc->getPriority();
2712 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2713 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002714 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002715 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002716 // native clients don't have offline processing support.
2717 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002718 if (offlineClientDesc == nullptr) {
2719 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2720 return BAD_VALUE;
2721 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002722
2723 // Allow only one offline device per camera
2724 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2725 if (!incompatibleClients.empty()) {
2726 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2727 return BAD_VALUE;
2728 }
2729
Austin Borgered99f642023-06-01 16:51:35 -07002730 std::string monitorTags = isClientWatched(offlineClient.get())
2731 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002732 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002733 if (err != OK) {
2734 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2735 return err;
2736 }
2737
2738 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2739 if (evicted.size() > 0) {
2740 for (auto& i : evicted) {
2741 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002742 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002743 }
2744
2745 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2746 "properly", __FUNCTION__);
2747
2748 return BAD_VALUE;
2749 }
2750
2751 logConnectedOffline(offlineClientDesc->getKey(),
2752 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002753 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002754
2755 sp<IBinder> remoteCallback = offlineClient->getRemote();
2756 if (remoteCallback != nullptr) {
2757 remoteCallback->linkToDeath(this);
2758 }
2759 } // lock is destroyed, allow further connect calls
2760
2761 return OK;
2762}
2763
Austin Borgered99f642023-06-01 16:51:35 -07002764Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger1c1bee02023-06-01 16:51:35 -07002765 int32_t torchStrength, const sp<IBinder>& clientBinder) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002766 Mutex::Autolock lock(mServiceLock);
2767
2768 ATRACE_CALL();
2769 if (clientBinder == nullptr) {
2770 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2771 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2772 "Torch client binder in null.");
2773 }
2774
Rucha Katakwar38284522021-11-10 11:25:21 -08002775 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002776 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002777 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002778 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002779 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002780 }
2781
2782 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002783 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002784 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002785 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002786 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002787 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002788 }
2789
2790 StatusInternal cameraStatus = state->getStatus();
2791 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2792 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002793 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002794 (int)cameraStatus);
2795 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002796 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002797 }
2798
2799 {
2800 Mutex::Autolock al(mTorchStatusMutex);
2801 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002802 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002803 if (err != OK) {
2804 if (err == NAME_NOT_FOUND) {
2805 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002806 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002807 }
2808 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002809 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002810 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2811 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002812 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002813 }
2814
2815 if (status == TorchModeStatus::NOT_AVAILABLE) {
2816 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2817 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002818 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002819 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2820 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002821 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002822 } else {
2823 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002824 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002825 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2826 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002827 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002828 }
2829 }
2830 }
2831
2832 {
2833 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002834 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002835 }
2836 // Check if the current torch strength level is same as the new one.
2837 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002838 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002839
Austin Borgered99f642023-06-01 16:51:35 -07002840 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002841
2842 if (err != OK) {
2843 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002844 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002845 switch (err) {
2846 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002847 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2848 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002849 errorCode = ERROR_ILLEGAL_ARGUMENT;
2850 break;
2851 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002852 msg = fmt::sprintf("Camera \"%s\" is in use",
2853 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002854 errorCode = ERROR_CAMERA_IN_USE;
2855 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002856 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002857 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002858 "valid range.", torchStrength);
2859 errorCode = ERROR_ILLEGAL_ARGUMENT;
2860 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002861 default:
Austin Borgered99f642023-06-01 16:51:35 -07002862 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002863 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002864 }
Austin Borgered99f642023-06-01 16:51:35 -07002865 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2866 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002867 }
2868
2869 {
2870 // update the link to client's death
2871 // Store the last client that turns on each camera's torch mode.
2872 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002873 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002874 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002875 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002876 } else {
2877 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2878 mTorchClientMap.replaceValueAt(index, clientBinder);
2879 }
2880 clientBinder->linkToDeath(this);
2881 }
2882
2883 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002884 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002885 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002886 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002887 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002888 }
2889 return Status::ok();
2890}
2891
malikakash73125c62023-07-21 22:44:34 +00002892Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002893 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002894 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002895
2896 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002897 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002898 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002899 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2900 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002901 }
2902
Jayant Chowdhary12361932018-08-27 14:46:13 -07002903 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002904 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002905
Austin Borgered99f642023-06-01 16:51:35 -07002906 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002907 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002908 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002909 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002910 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002911 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002912 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002913 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002914 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002915 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002916 }
2917
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002918 StatusInternal cameraStatus = state->getStatus();
2919 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002920 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002921 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2922 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002923 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002924 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002925 }
2926
2927 {
2928 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002929 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002930 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002931 if (err != OK) {
2932 if (err == NAME_NOT_FOUND) {
2933 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002934 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002935 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002936 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002937 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002938 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002939 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002940 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002941 }
2942
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002943 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002944 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002945 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002946 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002947 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2948 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002949 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002950 } else {
2951 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002952 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002953 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2954 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002955 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002956 }
2957 }
2958 }
2959
Ruben Brunk99e69712015-05-26 17:25:07 -07002960 {
2961 // Update UID map - this is used in the torch status changed callbacks, so must be done
2962 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002963 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002964 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002965 }
2966
Austin Borgered99f642023-06-01 16:51:35 -07002967 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002968
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002969 if (err != OK) {
2970 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002971 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972 switch (err) {
2973 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002974 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2975 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002976 errorCode = ERROR_ILLEGAL_ARGUMENT;
2977 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002978 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002979 msg = fmt::sprintf("Camera \"%s\" is in use",
2980 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002981 errorCode = ERROR_CAMERA_IN_USE;
2982 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002983 default:
Austin Borgered99f642023-06-01 16:51:35 -07002984 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002985 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002986 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002987 errorCode = ERROR_INVALID_OPERATION;
2988 }
Austin Borgered99f642023-06-01 16:51:35 -07002989 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2990 logServiceError(msg, errorCode);
2991 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002992 }
2993
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002994 {
2995 // update the link to client's death
2996 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002997 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002998 if (enabled) {
2999 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003000 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003001 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003002 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003003 mTorchClientMap.replaceValueAt(index, clientBinder);
3004 }
3005 clientBinder->linkToDeath(this);
3006 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003007 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003008 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003009 }
3010
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003011 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003012 std::string torchState = enabled ? "on" : "off";
3013 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3014 torchState.c_str(), clientPid);
3015 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003016 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003017}
3018
Austin Borgered99f642023-06-01 16:51:35 -07003019void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3020 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3021 mTorchUidMap[cameraId].first = uid;
3022 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003023 } else {
3024 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003025 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003026 }
3027}
3028
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003029Status CameraService::notifySystemEvent(int32_t eventId,
3030 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003031 const int pid = CameraThreadState::getCallingPid();
3032 const int selfPid = getpid();
3033
3034 // Permission checks
3035 if (pid != selfPid) {
3036 // Ensure we're being called by system_server, or similar process with
3037 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003038 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003039 const int uid = CameraThreadState::getCallingUid();
3040 ALOGE("Permission Denial: cannot send updates to camera service about system"
3041 " events from pid=%d, uid=%d", pid, uid);
3042 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003043 "No permission to send updates to camera service about system events"
3044 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003045 }
3046 }
3047
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003048 ATRACE_CALL();
3049
Ruben Brunk36597b22015-03-20 22:15:57 -07003050 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003051 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003052 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003053 // from a system server crash
3054 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003055 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003056 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003057 break;
3058 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003059 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3060 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003061 if (args.size() != 1) {
3062 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3063 "USB Device Event requires 1 argument");
3064 }
3065
Valentin Iftime29e2e152021-08-13 15:17:33 +02003066 // Notify CameraProviderManager for lazy HALs
3067 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3068 std::to_string(args[0]));
3069 break;
3070 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003071 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003072 default: {
3073 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3074 eventId);
3075 break;
3076 }
3077 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003078 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003079}
3080
Emilian Peev53722fa2019-02-22 17:47:20 -08003081void CameraService::notifyMonitoredUids() {
3082 Mutex::Autolock lock(mStatusListenerLock);
3083
3084 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003085 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003086 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3087 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003088 }
3089}
3090
Austin Borgerdddb7552023-03-30 17:53:01 -07003091void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3092 Mutex::Autolock lock(mStatusListenerLock);
3093
3094 for (const auto& it : mListenerList) {
3095 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3096 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3097 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3098 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3099 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3100 }
3101 }
3102}
3103
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003104Status CameraService::notifyDeviceStateChange(int64_t newState) {
3105 const int pid = CameraThreadState::getCallingPid();
3106 const int selfPid = getpid();
3107
3108 // Permission checks
3109 if (pid != selfPid) {
3110 // Ensure we're being called by system_server, or similar process with
3111 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003112 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003113 const int uid = CameraThreadState::getCallingUid();
3114 ALOGE("Permission Denial: cannot send updates to camera service about device"
3115 " state changes from pid=%d, uid=%d", pid, uid);
3116 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3117 "No permission to send updates to camera service about device state"
3118 " changes from pid=%d, uid=%d", pid, uid);
3119 }
3120 }
3121
3122 ATRACE_CALL();
3123
Austin Borger18b30a72022-10-27 12:20:29 -07003124 {
3125 Mutex::Autolock lock(mServiceLock);
3126 mDeviceState = newState;
3127 }
3128
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003129 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003130
3131 return Status::ok();
3132}
3133
Emilian Peev8b64f282021-03-25 16:49:57 -07003134Status CameraService::notifyDisplayConfigurationChange() {
3135 ATRACE_CALL();
3136 const int callingPid = CameraThreadState::getCallingPid();
3137 const int selfPid = getpid();
3138
3139 // Permission checks
3140 if (callingPid != selfPid) {
3141 // Ensure we're being called by system_server, or similar process with
3142 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003143 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07003144 const int uid = CameraThreadState::getCallingUid();
3145 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3146 " changes from pid=%d, uid=%d", callingPid, uid);
3147 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3148 "No permission to send updates to camera service about orientation"
3149 " changes from pid=%d, uid=%d", callingPid, uid);
3150 }
3151 }
3152
3153 Mutex::Autolock lock(mServiceLock);
3154
3155 // Don't do anything if rotate-and-crop override via cmd is active
3156 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3157
3158 const auto clients = mActiveClientManager.getAll();
3159 for (auto& current : clients) {
3160 if (current != nullptr) {
3161 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003162 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3163 basicClient->setRotateAndCropOverride(
3164 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3165 basicClient->getPackageName(),
3166 basicClient->getCameraFacing(),
3167 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003168 }
3169 }
3170 }
3171
3172 return Status::ok();
3173}
3174
3175Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003176 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3177 ATRACE_CALL();
3178 if (!concurrentCameraIds) {
3179 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3180 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3181 }
3182
3183 if (!mInitialized) {
3184 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003185 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003186 return STATUS_ERROR(ERROR_DISCONNECTED,
3187 "Camera subsystem is not available");
3188 }
3189 // First call into the provider and get the set of concurrent camera
3190 // combinations
3191 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003192 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003193 for (auto &combination : concurrentCameraCombinations) {
3194 std::vector<std::string> validCombination;
3195 for (auto &cameraId : combination) {
3196 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003197 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003198 if (state == nullptr) {
3199 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3200 continue;
3201 }
3202 StatusInternal status = state->getStatus();
3203 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3204 continue;
3205 }
Austin Borgered99f642023-06-01 16:51:35 -07003206 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003207 continue;
3208 }
3209 validCombination.push_back(cameraId);
3210 }
3211 if (validCombination.size() != 0) {
3212 concurrentCameraIds->push_back(std::move(validCombination));
3213 }
3214 }
3215 return Status::ok();
3216}
3217
3218Status CameraService::isConcurrentSessionConfigurationSupported(
3219 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003220 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003221 if (!isSupported) {
3222 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3223 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3224 }
3225
3226 if (!mInitialized) {
3227 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3228 return STATUS_ERROR(ERROR_DISCONNECTED,
3229 "Camera subsystem is not available");
3230 }
3231
3232 // Check for camera permissions
Austin Borger249e6592024-03-10 22:28:11 -07003233 int callingPid = CameraThreadState::getCallingPid();
3234 int callingUid = CameraThreadState::getCallingUid();
3235 bool hasCameraPermission = ((callingPid == getpid()) ||
3236 hasPermissionsForCamera(callingPid, callingUid));
3237 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003238 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3239 "android.permission.CAMERA needed to call"
3240 "isConcurrentSessionConfigurationSupported");
3241 }
3242
3243 status_t res =
3244 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003245 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3246 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003247 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003248 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003249 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003250 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3251 "support %s (%d)", strerror(-res), res);
3252 }
3253 return Status::ok();
3254}
3255
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003256Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3257 /*out*/
3258 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003259 return addListenerHelper(listener, cameraStatuses);
3260}
3261
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003262binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3263 std::vector<hardware::CameraStatus>* cameraStatuses) {
3264 return addListenerHelper(listener, cameraStatuses, false, true);
3265}
3266
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003267Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3268 /*out*/
3269 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003270 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003271
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003272 ATRACE_CALL();
3273
Igor Murashkinbfc99152013-02-27 12:55:20 -08003274 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003275
Ruben Brunk3450ba72015-06-16 11:00:37 -07003276 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003277 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003278 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003279 }
3280
Charles Chenf075f082024-03-04 23:32:55 +00003281 auto clientPid = CameraThreadState::getCallingPid();
Austin Borger249e6592024-03-10 22:28:11 -07003282 auto clientUid = CameraThreadState::getCallingUid();
3283 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003284
Igor Murashkinbfc99152013-02-27 12:55:20 -08003285 Mutex::Autolock lock(mServiceLock);
3286
Ruben Brunkcc776712015-02-17 20:18:47 -08003287 {
3288 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003289 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003290 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003291 ALOGW("%s: Tried to add listener %p which was already subscribed",
3292 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003293 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003294 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003295 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003296
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003297 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003298 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3299 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003300 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003301 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003302 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003303 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003304 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3305 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3306 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003307 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003308 // The listener still needs to be added to the list of listeners, regardless of what
3309 // permissions the listener process has / whether it is a vendor listener. Since it might be
3310 // eligible to listen to other camera ids.
3311 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003312 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003313 }
3314
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003315 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003316 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003317 Mutex::Autolock lock(mCameraStatesLock);
3318 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003319 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003320 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003321 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003322 }
3323 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003324 // Remove the camera statuses that should be hidden from the client, we do
3325 // this after collecting the states in order to avoid holding
3326 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3327 // the same time.
3328 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3329 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3330 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3331 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3332 ALOGE("%s: Invalid camera id %s, skipping status update",
3333 __FUNCTION__, s.cameraId.c_str());
3334 return true;
3335 }
3336 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3337 clientUid);}), cameraStatuses->end());
3338
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003339 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003340 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003341 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003342 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003343 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003344
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003345 /*
3346 * Immediately signal current torch status to this listener only
3347 * This may be a subset of all the devices, so don't include it in the response directly
3348 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003349 {
3350 Mutex::Autolock al(mTorchStatusMutex);
3351 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003352 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003353 // The camera id is visible to the client. Fine to send torch
3354 // callback.
3355 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3356 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3357 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003358 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003359 }
3360
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003361 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003362}
Ruben Brunkcc776712015-02-17 20:18:47 -08003363
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003364Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003365 ATRACE_CALL();
3366
Igor Murashkinbfc99152013-02-27 12:55:20 -08003367 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3368
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003369 if (listener == 0) {
3370 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003371 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003372 }
3373
Igor Murashkinbfc99152013-02-27 12:55:20 -08003374 Mutex::Autolock lock(mServiceLock);
3375
Ruben Brunkcc776712015-02-17 20:18:47 -08003376 {
3377 Mutex::Autolock lock(mStatusListenerLock);
3378 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003379 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003380 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003381 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003382 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003383 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003384 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003385 }
3386 }
3387
3388 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3389 __FUNCTION__, listener.get());
3390
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003391 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003392}
3393
Austin Borgered99f642023-06-01 16:51:35 -07003394Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003395
3396 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003397 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3398
3399 if (parameters == NULL) {
3400 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003401 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003402 }
3403
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003404 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003405
3406 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003407 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003408 // Error logged by caller
3409 return ret;
3410 }
3411
3412 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003413
Austin Borgered99f642023-06-01 16:51:35 -07003414 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003415
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003416 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003417}
3418
Austin Borgered99f642023-06-01 16:51:35 -07003419Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003420 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003421 ATRACE_CALL();
3422
malikakashedb38962023-09-06 00:03:35 +00003423 const std::string cameraId = resolveCameraId(
3424 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003425
Austin Borgered99f642023-06-01 16:51:35 -07003426 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003427
3428 switch (apiVersion) {
3429 case API_VERSION_1:
3430 case API_VERSION_2:
3431 break;
3432 default:
Austin Borgered99f642023-06-01 16:51:35 -07003433 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3434 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3435 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003436 }
3437
Austin Borger18b30a72022-10-27 12:20:29 -07003438 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003439 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003440 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003441 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3442 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3443 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003444 }
3445 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3446 int deviceVersion = deviceVersionAndTransport.first;
3447 switch (deviceVersion) {
3448 case CAMERA_DEVICE_API_VERSION_1_0:
3449 case CAMERA_DEVICE_API_VERSION_3_0:
3450 case CAMERA_DEVICE_API_VERSION_3_1:
3451 if (apiVersion == API_VERSION_2) {
3452 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003453 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003454 *isSupported = false;
3455 } else { // if (apiVersion == API_VERSION_1) {
3456 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003457 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003458 *isSupported = true;
3459 }
3460 break;
3461 case CAMERA_DEVICE_API_VERSION_3_2:
3462 case CAMERA_DEVICE_API_VERSION_3_3:
3463 case CAMERA_DEVICE_API_VERSION_3_4:
3464 case CAMERA_DEVICE_API_VERSION_3_5:
3465 case CAMERA_DEVICE_API_VERSION_3_6:
3466 case CAMERA_DEVICE_API_VERSION_3_7:
3467 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003468 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003469 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003470 break;
3471 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003472 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3473 deviceVersion, cameraId.c_str());
3474 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3475 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003476 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003477 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003478 } else {
3479 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003480 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003481 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003482}
3483
Austin Borgered99f642023-06-01 16:51:35 -07003484Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003485 /*out*/ bool *isSupported) {
3486 ATRACE_CALL();
3487
malikakashedb38962023-09-06 00:03:35 +00003488 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3489 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003490
Austin Borgered99f642023-06-01 16:51:35 -07003491 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3492 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003493
3494 return Status::ok();
3495}
3496
Cliff Wud8cae102021-03-11 01:37:42 +08003497Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003498 const std::string& packageName, const std::string& internalCamId,
3499 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003500 const sp<ICameraInjectionCallback>& callback,
3501 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003502 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003503 ATRACE_CALL();
3504
Austin Borgered99f642023-06-01 16:51:35 -07003505 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003506 const int pid = CameraThreadState::getCallingPid();
3507 const int uid = CameraThreadState::getCallingUid();
3508 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3509 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3510 "Permission Denial: no permission to inject camera");
3511 }
3512
3513 ALOGV(
3514 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3515 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003516 __FUNCTION__, packageName.c_str(),
3517 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003518
Cliff Wud3a05312021-04-26 23:07:31 +08003519 {
3520 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003521 mInjectionInternalCamId = internalCamId;
3522 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003523 mInjectionStatusListener->addListener(callback);
3524 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003525 status_t res = NO_ERROR;
3526 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3527 // If the client already exists, we can directly connect to the camera device through the
3528 // client's injectCamera(), otherwise we need to wait until the client is established
3529 // (execute connectHelper()) before injecting the camera to the camera device.
3530 if (clientDescriptor != nullptr) {
3531 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003532 sp<BasicClient> clientSp = clientDescriptor->getValue();
3533 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3534 if(res != OK) {
3535 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3536 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003537 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003538 }
3539 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003540 if(res != OK) {
3541 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3542 }
3543 } else {
3544 mInjectionInitPending = true;
3545 }
3546 }
Cliff Wud8cae102021-03-11 01:37:42 +08003547
Cliff Wud3a05312021-04-26 23:07:31 +08003548 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003549}
3550
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003551Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003552 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003553 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3554 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3555 return Status::ok();
3556}
3557
Ruben Brunkcc776712015-02-17 20:18:47 -08003558void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003559 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003560 for (auto& i : mActiveClientManager.getAll()) {
3561 auto clientSp = i->getValue();
3562 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003563 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003564 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003565 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003566 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003567 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003568}
3569
Ruben Brunkcc776712015-02-17 20:18:47 -08003570bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003571 bool ret = false;
3572 {
3573 // Acquire mServiceLock and prevent other clients from connecting
3574 std::unique_ptr<AutoConditionLock> lock =
3575 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003576
Igor Murashkin634a5152013-02-20 17:15:11 -08003577
Ruben Brunkcc776712015-02-17 20:18:47 -08003578 std::vector<sp<BasicClient>> evicted;
3579 for (auto& i : mActiveClientManager.getAll()) {
3580 auto clientSp = i->getValue();
3581 if (clientSp.get() == nullptr) {
3582 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3583 mActiveClientManager.remove(i);
3584 continue;
3585 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003586 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003587 mActiveClientManager.remove(i);
3588 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003589
Ruben Brunkcc776712015-02-17 20:18:47 -08003590 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003591 clientSp->notifyError(
3592 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003593 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003594 }
3595 }
3596
Ruben Brunkcc776712015-02-17 20:18:47 -08003597 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3598 // other clients from connecting in mServiceLockWrapper if held
3599 mServiceLock.unlock();
3600
Ruben Brunk36597b22015-03-20 22:15:57 -07003601 // Do not clear caller identity, remote caller should be client proccess
3602
Ruben Brunkcc776712015-02-17 20:18:47 -08003603 for (auto& i : evicted) {
3604 if (i.get() != nullptr) {
3605 i->disconnect();
3606 ret = true;
3607 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003608 }
3609
Ruben Brunkcc776712015-02-17 20:18:47 -08003610 // Reacquire mServiceLock
3611 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003612
Ruben Brunkcc776712015-02-17 20:18:47 -08003613 } // lock is destroyed, allow further connect calls
3614
3615 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003616}
3617
Ruben Brunkcc776712015-02-17 20:18:47 -08003618std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003619 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003620 std::shared_ptr<CameraState> state;
3621 {
3622 Mutex::Autolock lock(mCameraStatesLock);
3623 auto iter = mCameraStates.find(cameraId);
3624 if (iter != mCameraStates.end()) {
3625 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003626 }
3627 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003628 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003629}
3630
Austin Borgered99f642023-06-01 16:51:35 -07003631sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003632 // Remove from active clients list
3633 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3634 if (clientDescriptorPtr == nullptr) {
3635 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003636 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003637 return sp<BasicClient>{nullptr};
3638 }
3639
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003640 sp<BasicClient> client = clientDescriptorPtr->getValue();
3641 if (client.get() != nullptr) {
3642 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3643 }
3644 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003645}
3646
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003647void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003648 // Acquire mServiceLock and prevent other clients from connecting
3649 std::unique_ptr<AutoConditionLock> lock =
3650 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3651
Ruben Brunk6267b532015-04-30 17:44:07 -07003652 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003653 for (size_t i = 0; i < newUserIds.size(); i++) {
3654 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003655 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003656 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003657 return;
3658 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003659 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003660 }
3661
Ruben Brunka8ca9152015-04-07 14:23:40 -07003662
Ruben Brunk6267b532015-04-30 17:44:07 -07003663 if (newAllowedUsers == mAllowedUsers) {
3664 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3665 return;
3666 }
3667
3668 logUserSwitch(mAllowedUsers, newAllowedUsers);
3669
3670 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003671
3672 // Current user has switched, evict all current clients.
3673 std::vector<sp<BasicClient>> evicted;
3674 for (auto& i : mActiveClientManager.getAll()) {
3675 auto clientSp = i->getValue();
3676
3677 if (clientSp.get() == nullptr) {
3678 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3679 continue;
3680 }
3681
Ruben Brunk6267b532015-04-30 17:44:07 -07003682 // Don't evict clients that are still allowed.
3683 uid_t clientUid = clientSp->getClientUid();
3684 userid_t clientUserId = multiuser_get_user_id(clientUid);
3685 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3686 continue;
3687 }
3688
Ruben Brunk36597b22015-03-20 22:15:57 -07003689 evicted.push_back(clientSp);
3690
Ruben Brunk36597b22015-03-20 22:15:57 -07003691 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003692 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003693
Ruben Brunk36597b22015-03-20 22:15:57 -07003694 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003695 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003696 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003697 " to user switch.", i->getKey().c_str(),
3698 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003699 i->getOwnerId(), i->getPriority().getScore(),
3700 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003701
3702 }
3703
3704 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3705 // blocking other clients from connecting in mServiceLockWrapper if held.
3706 mServiceLock.unlock();
3707
3708 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003709 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003710
3711 for (auto& i : evicted) {
3712 i->disconnect();
3713 }
3714
Jayant Chowdhary12361932018-08-27 14:46:13 -07003715 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003716
3717 // Reacquire mServiceLock
3718 mServiceLock.lock();
3719}
Ruben Brunkcc776712015-02-17 20:18:47 -08003720
Austin Borgered99f642023-06-01 16:51:35 -07003721void CameraService::logEvent(const std::string &event) {
3722 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003723 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003724 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003725 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003726 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003727 mEventLog.add(msg);
3728 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3729 // Error event not added to the dumpsys log before
3730 mEventLog.add(msg);
3731 sServiceErrorEventSet.insert(msg);
3732 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003733}
3734
Austin Borgered99f642023-06-01 16:51:35 -07003735void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3736 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003737 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003738 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3739 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003740}
3741
Austin Borgered99f642023-06-01 16:51:35 -07003742void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3743 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003744 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003745 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3746 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003747}
3748
Austin Borgered99f642023-06-01 16:51:35 -07003749void CameraService::logConnected(const std::string &cameraId, int clientPid,
3750 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003751 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003752 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3753 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003754}
3755
Austin Borgered99f642023-06-01 16:51:35 -07003756void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3757 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003758 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003759 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3760 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003761}
3762
Austin Borgered99f642023-06-01 16:51:35 -07003763void CameraService::logRejected(const std::string &cameraId, int clientPid,
3764 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003765 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003766 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3767 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003768}
3769
Austin Borgered99f642023-06-01 16:51:35 -07003770void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3771 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003772 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003773 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3774 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003775}
3776
Ruben Brunk6267b532015-04-30 17:44:07 -07003777void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3778 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003779 std::string newUsers = toString(newUserIds);
3780 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003781 if (oldUsers.size() == 0) {
3782 oldUsers = "<None>";
3783 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003784 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003785 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3786 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003787}
3788
Austin Borgered99f642023-06-01 16:51:35 -07003789void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003790 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003791 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003792}
3793
Austin Borgered99f642023-06-01 16:51:35 -07003794void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003795 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003796 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003797}
3798
Austin Borgered99f642023-06-01 16:51:35 -07003799void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003800 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003801 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003802}
3803
Austin Borgered99f642023-06-01 16:51:35 -07003804void CameraService::logServiceError(const std::string &msg, int errorCode) {
3805 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3806 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003807}
3808
Ruben Brunk36597b22015-03-20 22:15:57 -07003809status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3810 uint32_t flags) {
3811
Mathias Agopian65ab4712010-07-14 17:59:35 -07003812 // Permission checks
3813 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003814 case SHELL_COMMAND_TRANSACTION: {
3815 int in = data.readFileDescriptor();
3816 int out = data.readFileDescriptor();
3817 int err = data.readFileDescriptor();
3818 int argc = data.readInt32();
3819 Vector<String16> args;
3820 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3821 args.add(data.readString16());
3822 }
3823 sp<IBinder> unusedCallback;
3824 sp<IResultReceiver> resultReceiver;
3825 status_t status;
3826 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3827 return status;
3828 }
3829 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3830 return status;
3831 }
3832 status = shellCommand(in, out, err, args);
3833 if (resultReceiver != nullptr) {
3834 resultReceiver->send(status);
3835 }
3836 return NO_ERROR;
3837 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003838 }
3839
3840 return BnCameraService::onTransact(code, data, reply, flags);
3841}
3842
Mathias Agopian65ab4712010-07-14 17:59:35 -07003843// We share the media players for shutter and recording sound for all clients.
3844// A reference count is kept to determine when we will actually release the
3845// media players.
3846
Jaekyun Seokef498052018-03-23 13:09:44 +09003847sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3848 sp<MediaPlayer> mp = new MediaPlayer();
3849 status_t error;
3850 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003851 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003852 error = mp->prepare();
3853 }
3854 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003855 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003856 mp->disconnect();
3857 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003858 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003859 }
3860 return mp;
3861}
3862
username5755fea2018-12-27 09:48:08 +08003863void CameraService::increaseSoundRef() {
3864 Mutex::Autolock lock(mSoundLock);
3865 mSoundRef++;
3866}
3867
3868void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003869 ATRACE_CALL();
3870
username5755fea2018-12-27 09:48:08 +08003871 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3872 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3873 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3874 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3875 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3876 }
3877 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3878 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3879 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3880 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003881 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003882 }
3883 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3884 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3885 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3886 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3887 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003888 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003889}
3890
username5755fea2018-12-27 09:48:08 +08003891void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003892 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003893 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 if (--mSoundRef) return;
3895
3896 for (int i = 0; i < NUM_SOUNDS; i++) {
3897 if (mSoundPlayer[i] != 0) {
3898 mSoundPlayer[i]->disconnect();
3899 mSoundPlayer[i].clear();
3900 }
3901 }
3902}
3903
3904void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003905 ATRACE_CALL();
3906
Mathias Agopian65ab4712010-07-14 17:59:35 -07003907 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003908 if (kind < 0 || kind >= NUM_SOUNDS) {
3909 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3910 return;
3911 }
3912
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003914 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003915 sp<MediaPlayer> player = mSoundPlayer[kind];
3916 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003917 player->seekTo(0);
3918 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003919 }
3920}
3921
3922// ----------------------------------------------------------------------------
3923
3924CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003925 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07003926 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07003927 const std::string& clientPackageName, bool systemNativeClient,
3928 const std::optional<std::string>& clientFeatureId,
3929 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003930 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003931 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003932 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003933 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003934 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07003935 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003936 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003937 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003938 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003939 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003940 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003941{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003942 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003943 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003945 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946
username5755fea2018-12-27 09:48:08 +08003947 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003948
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003949 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003950}
3951
Mathias Agopian65ab4712010-07-14 17:59:35 -07003952// tear down the client
3953CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003954 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003955 mDestructionStarted = true;
3956
username5755fea2018-12-27 09:48:08 +08003957 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003958 // unconditionally disconnect. function is idempotent
3959 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003960}
3961
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003962sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3963
Igor Murashkin634a5152013-02-20 17:15:11 -08003964CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003965 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07003966 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07003967 const std::string& clientPackageName, bool nativeClient,
3968 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003969 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003970 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07003971 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003972 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003973 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003974 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3975 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003976 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003977 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07003978 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07003979 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003980 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003981 mRemoteBinder(remoteCallback),
3982 mOpsActive(false),
3983 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08003984{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003985 if (sCameraService == nullptr) {
3986 sCameraService = cameraService;
3987 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08003988
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003989 // There are 2 scenarios in which a client won't have AppOps operations
3990 // (both scenarios : native clients)
3991 // 1) It's an system native client*, the package name will be empty
3992 // and it will return from this function in the previous if condition
3993 // (This is the same as the previously existing behavior).
3994 // 2) It is a system native client, but its package name has been
3995 // modified for debugging, however it still must not use AppOps since
3996 // the package name is not a real one.
3997 //
3998 // * system native client - native client with UID < AID_APP_START. It
3999 // doesn't exclude clients not on the system partition.
4000 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004001 mAppOpsManager = std::make_unique<AppOpsManager>();
4002 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004003
Charles Chenf075f082024-03-04 23:32:55 +00004004 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004005}
4006
4007CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004008 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004009 mDestructionStarted = true;
4010}
4011
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004012binder::Status CameraService::BasicClient::disconnect() {
4013 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004014 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004015 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004016 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004017 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004018
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004019 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004020 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004021 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004022 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004023
4024 sp<IBinder> remote = getRemote();
4025 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004026 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004027 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004028
4029 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004030 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004031 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004032 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004033 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004034
Igor Murashkincba2c162013-03-20 15:56:31 -07004035 // client shouldn't be able to call into us anymore
4036 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004037
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004038 const auto& mActivityManager = getActivityManager();
4039 if (mActivityManager) {
4040 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
4041 CameraThreadState::getCallingUid(),
4042 CameraThreadState::getCallingPid());
4043 }
4044
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004045 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004046}
4047
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004048status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4049 // No dumping of clients directly over Binder,
4050 // must go through CameraService::dump
4051 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004052 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004053 return OK;
4054}
4055
Austin Borgered99f642023-06-01 16:51:35 -07004056status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004057 // Can't watch tags directly, must go through CameraService::startWatchingTags
4058 return OK;
4059}
4060
4061status_t CameraService::BasicClient::stopWatchingTags(int) {
4062 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4063 return OK;
4064}
4065
4066status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4067 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4068 return OK;
4069}
4070
Austin Borgered99f642023-06-01 16:51:35 -07004071std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004072 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004073}
4074
Emilian Peev8b64f282021-03-25 16:49:57 -07004075int CameraService::BasicClient::getCameraFacing() const {
4076 return mCameraFacing;
4077}
4078
4079int CameraService::BasicClient::getCameraOrientation() const {
4080 return mOrientation;
4081}
Ruben Brunkcc776712015-02-17 20:18:47 -08004082
4083int CameraService::BasicClient::getClientPid() const {
4084 return mClientPid;
4085}
4086
Ruben Brunk6267b532015-04-30 17:44:07 -07004087uid_t CameraService::BasicClient::getClientUid() const {
4088 return mClientUid;
4089}
4090
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004091bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4092 // Defaults to API2.
4093 return level == API_2;
4094}
4095
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004096status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004097 {
4098 Mutex::Autolock l(mAudioRestrictionLock);
4099 mAudioRestriction = mode;
4100 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004101 sCameraService->updateAudioRestriction();
4102 return OK;
4103}
4104
4105int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004106 return sCameraService->updateAudioRestriction();
4107}
4108
4109int32_t CameraService::BasicClient::getAudioRestriction() const {
4110 Mutex::Autolock l(mAudioRestrictionLock);
4111 return mAudioRestriction;
4112}
4113
4114bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4115 switch (mode) {
4116 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4117 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4118 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4119 return true;
4120 default:
4121 return false;
4122 }
4123}
4124
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004125status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4126 if (mode == AppOpsManager::MODE_ERRORED) {
4127 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004128 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004129 return PERMISSION_DENIED;
4130 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4131 // If the calling Uid is trusted (a native service), the AppOpsManager could
4132 // return MODE_IGNORED. Do not treat such case as error.
4133 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4134 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004135
4136 bool isCameraPrivacyEnabled;
4137 if (flags::camera_privacy_allowlist()) {
4138 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4139 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4140 } else {
4141 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004142 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004143 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004144 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4145 // We prefer to successfully open the camera and perform camera muting
4146 // or blocking in connectHelper as handleAppOpMode can be called before the
4147 // connection has been fully established and at that time camera muting
4148 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004149 if (!isUidActive || !isCameraPrivacyEnabled) {
4150 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004151 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004152 // Return the same error as for device policy manager rejection
4153 return -EACCES;
4154 }
4155 }
4156 return OK;
4157}
4158
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004159status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004160 ATRACE_CALL();
4161
Igor Murashkine6800ce2013-03-04 17:25:57 -08004162 {
4163 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004164 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004165 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004166 if (mAppOpsManager != nullptr) {
4167 // Notify app ops that the camera is not available
4168 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004169
4170 if (flags::watch_foreground_changes()) {
4171 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4172 toString16(mClientPackageName),
4173 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4174 } else {
4175 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004176 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004177 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004178
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004179 // Just check for camera acccess here on open - delay startOp until
4180 // camera frames start streaming in startCameraStreamingOps
4181 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004182 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004183 status_t res = handleAppOpMode(mode);
4184 if (res != OK) {
4185 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004186 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004187 }
4188
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004189 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004190
4191 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004192 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004193
Austin Borgerdddb7552023-03-30 17:53:01 -07004194 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004195
Shuzhen Wang695044d2020-03-06 09:02:23 -08004196 // Notify listeners of camera open/close status
4197 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4198
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004199 return OK;
4200}
4201
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004202status_t CameraService::BasicClient::startCameraStreamingOps() {
4203 ATRACE_CALL();
4204
4205 if (!mOpsActive) {
4206 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4207 return INVALID_OPERATION;
4208 }
4209 if (mOpsStreaming) {
4210 ALOGV("%s: Streaming already active!", __FUNCTION__);
4211 return OK;
4212 }
4213
4214 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004215 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004216
4217 if (mAppOpsManager != nullptr) {
4218 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004219 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4220 toString16(mClientFeatureId),
4221 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004222 status_t res = handleAppOpMode(mode);
4223 if (res != OK) {
4224 return res;
4225 }
4226 }
4227
4228 mOpsStreaming = true;
4229
4230 return OK;
4231}
4232
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004233status_t CameraService::BasicClient::noteAppOp() {
4234 ATRACE_CALL();
4235
4236 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004237 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004238
4239 // noteAppOp is only used for when camera mute is not supported, in order
4240 // to trigger the sensor privacy "Unblock" dialog
4241 if (mAppOpsManager != nullptr) {
4242 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004243 toString16(mClientPackageName), toString16(mClientFeatureId),
4244 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004245 status_t res = handleAppOpMode(mode);
4246 if (res != OK) {
4247 return res;
4248 }
4249 }
4250
4251 return OK;
4252}
4253
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004254status_t CameraService::BasicClient::finishCameraStreamingOps() {
4255 ATRACE_CALL();
4256
4257 if (!mOpsActive) {
4258 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4259 return INVALID_OPERATION;
4260 }
4261 if (!mOpsStreaming) {
4262 ALOGV("%s: Streaming not active!", __FUNCTION__);
4263 return OK;
4264 }
4265
4266 if (mAppOpsManager != nullptr) {
4267 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004268 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004269 mOpsStreaming = false;
4270 }
4271
4272 return OK;
4273}
4274
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004275status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004276 ATRACE_CALL();
4277
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004278 if (mOpsStreaming) {
4279 // Make sure we've notified everyone about camera stopping
4280 finishCameraStreamingOps();
4281 }
4282
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004283 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004284 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004285 mOpsActive = false;
4286
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004287 // This function is called when a client disconnects. This should
4288 // release the camera, but actually only if it was in a proper
4289 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004290 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004291 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004292
Ruben Brunkcc776712015-02-17 20:18:47 -08004293 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004294 sCameraService->updateStatus(StatusInternal::PRESENT,
4295 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004296 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004297 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004298 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4299 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004300 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004301 mOpsCallback.clear();
4302
Austin Borgerdddb7552023-03-30 17:53:01 -07004303 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004304
Shuzhen Wang695044d2020-03-06 09:02:23 -08004305 // Notify listeners of camera open/close status
4306 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4307
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004308 return OK;
4309}
4310
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004311void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004312 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004313 if (mAppOpsManager == nullptr) {
4314 return;
4315 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004316 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004317 if (op != AppOpsManager::OP_CAMERA) {
4318 ALOGW("Unexpected app ops notification received: %d", op);
4319 return;
4320 }
4321
4322 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004323 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004324 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004325 ALOGV("checkOp returns: %d, %s ", res,
4326 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4327 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4328 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4329 "UNKNOWN");
4330
Shuzhen Wang64900852021-02-05 09:03:29 -08004331 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004332 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4333 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004334 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004335 } else if (res == AppOpsManager::MODE_IGNORED) {
4336 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004337
Austin Borgerca1e0062023-06-28 11:32:55 -07004338 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4339 // If not visible, but still active, then we want to block instead of muting the camera.
4340 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4341 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4342
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004343 bool isCameraPrivacyEnabled;
4344 if (flags::camera_privacy_allowlist()) {
4345 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4346 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4347 } else {
4348 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004349 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004350 }
4351
4352 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004353 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4354 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4355 isCameraPrivacyEnabled);
4356 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4357 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4358 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004359 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004360 if (flags::watch_foreground_changes()) {
4361 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4362 setCameraMute(true);
4363 } else {
4364 block();
4365 }
4366 } else {
4367 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4368 setCameraMute(true);
4369 } else if (!isUidActive
4370 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4371 block();
4372 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004373 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004374 }
Evan Severson09ab4002021-02-10 14:15:19 -08004375 } else if (res == AppOpsManager::MODE_ALLOWED) {
4376 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004377 }
4378}
4379
Svet Ganova453d0d2018-01-11 15:37:58 -08004380void CameraService::BasicClient::block() {
4381 ATRACE_CALL();
4382
4383 // Reset the client PID to allow server-initiated disconnect,
4384 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004385 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004386 CaptureResultExtras resultExtras; // a dummy result (invalid)
4387 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4388 disconnect();
4389}
4390
Mathias Agopian65ab4712010-07-14 17:59:35 -07004391// ----------------------------------------------------------------------------
4392
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004393void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004394 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004395 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004396 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4397 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4398 api1ErrorCode = CAMERA_ERROR_DISABLED;
4399 }
4400 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004401 } else {
4402 ALOGE("mRemoteCallback is NULL!!");
4403 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004404}
4405
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004406// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004407binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004408 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004409 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004410}
4411
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004412bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4413 return level == API_1;
4414}
4415
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004416CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4417 mClient(client) {
4418}
4419
4420void CameraService::Client::OpsCallback::opChanged(int32_t op,
4421 const String16& packageName) {
4422 sp<BasicClient> client = mClient.promote();
4423 if (client != NULL) {
4424 client->opChanged(op, packageName);
4425 }
4426}
4427
Mathias Agopian65ab4712010-07-14 17:59:35 -07004428// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004429// UidPolicy
4430// ----------------------------------------------------------------------------
4431
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004432void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004433 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004434 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004435
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004436 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004437 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004438 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004439 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004440 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4441 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004442 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004443 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004444 if (res == OK) {
4445 mRegistered = true;
4446 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004447 } else {
4448 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004449 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004450}
4451
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004452void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004453 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004454 return;
4455 }
4456
4457 registerWithActivityManager();
4458}
4459
4460void CameraService::UidPolicy::registerSelf() {
4461 // Use check service to see if the activity service is available
4462 // If not available then register for notifications, instead of blocking
4463 // till the service is ready
4464 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004465 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004466 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004467 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004468 } else {
4469 registerWithActivityManager();
4470 }
4471}
4472
Svet Ganova453d0d2018-01-11 15:37:58 -08004473void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004474 Mutex::Autolock _l(mUidLock);
4475
Steven Moreland2f348142019-07-02 15:59:07 -07004476 mAm.unregisterUidObserver(this);
4477 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004478 mRegistered = false;
4479 mActiveUids.clear();
4480 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004481}
4482
4483void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4484 onUidIdle(uid, disabled);
4485}
4486
4487void CameraService::UidPolicy::onUidActive(uid_t uid) {
4488 Mutex::Autolock _l(mUidLock);
4489 mActiveUids.insert(uid);
4490}
4491
4492void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4493 bool deleted = false;
4494 {
4495 Mutex::Autolock _l(mUidLock);
4496 if (mActiveUids.erase(uid) > 0) {
4497 deleted = true;
4498 }
4499 }
4500 if (deleted) {
4501 sp<CameraService> service = mService.promote();
4502 if (service != nullptr) {
4503 service->blockClientsForUid(uid);
4504 }
4505 }
4506}
4507
Emilian Peev53722fa2019-02-22 17:47:20 -08004508void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004509 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004510 bool procStateChange = false;
4511 {
4512 Mutex::Autolock _l(mUidLock);
4513 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4514 mMonitoredUids[uid].procState != procState) {
4515 mMonitoredUids[uid].procState = procState;
4516 procStateChange = true;
4517 }
4518 }
4519
4520 if (procStateChange) {
4521 sp<CameraService> service = mService.promote();
4522 if (service != nullptr) {
4523 service->notifyMonitoredUids();
4524 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004525 }
4526}
4527
Austin Borgerdddb7552023-03-30 17:53:01 -07004528/**
4529 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4530 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4531 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4532 * monitoredUids. If it is revised above some other monitoredUid, signal
4533 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4534 * foreground apps in split screen - state changes will capture all other cases.
4535 */
4536void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4537 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004538 {
4539 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004540 auto it = mMonitoredUids.find(uid);
4541
4542 if (it != mMonitoredUids.end()) {
4543 if (it->second.hasCamera) {
4544 for (auto &monitoredUid : mMonitoredUids) {
4545 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004546 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004547 notifyUidSet.emplace(monitoredUid.first);
4548 }
4549 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004550 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004551 notifyUidSet.emplace(uid);
4552 } else {
4553 for (auto &monitoredUid : mMonitoredUids) {
4554 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004555 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004556 notifyUidSet.emplace(uid);
4557 }
4558 }
4559 }
4560 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004561 }
4562 }
4563
Austin Borgerdddb7552023-03-30 17:53:01 -07004564 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004565 sp<CameraService> service = mService.promote();
4566 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004567 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004568 }
4569 }
4570}
4571
Austin Borgerdddb7552023-03-30 17:53:01 -07004572/**
4573 * Register a uid for monitoring, and note whether it owns a camera.
4574 */
4575void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004576 Mutex::Autolock _l(mUidLock);
4577 auto it = mMonitoredUids.find(uid);
4578 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004579 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004580 } else {
Austin Borger65577682022-02-17 00:25:43 +00004581 MonitoredUid monitoredUid;
4582 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004583 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004584 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004585 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004586 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004587 if (res != OK) {
4588 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4589 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004590 }
4591
4592 if (openCamera) {
4593 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004594 }
4595}
4596
Austin Borgerdddb7552023-03-30 17:53:01 -07004597/**
4598 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4599 */
4600void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004601 Mutex::Autolock _l(mUidLock);
4602 auto it = mMonitoredUids.find(uid);
4603 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004604 it->second.refCount--;
4605 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004606 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004607 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004608 if (res != OK) {
4609 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4610 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004611 } else if (closeCamera) {
4612 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004613 }
4614 } else {
4615 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4616 }
4617}
4618
Austin Borgered99f642023-06-01 16:51:35 -07004619bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004620 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004621 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004622}
4623
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004624static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4625static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004626
Austin Borgered99f642023-06-01 16:51:35 -07004627bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004628 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004629 // If activity manager is unreachable, assume everything is active
4630 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004631 return true;
4632 }
4633 auto it = mOverrideUids.find(uid);
4634 if (it != mOverrideUids.end()) {
4635 return it->second;
4636 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004637 bool active = mActiveUids.find(uid) != mActiveUids.end();
4638 if (!active) {
4639 // We want active UIDs to always access camera with their first attempt since
4640 // there is no guarantee the app is robustly written and would retry getting
4641 // the camera on failure. The inverse case is not a problem as we would take
4642 // camera away soon once we get the callback that the uid is no longer active.
4643 ActivityManager am;
4644 // Okay to access with a lock held as UID changes are dispatched without
4645 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004646 int64_t startTimeMillis = 0;
4647 do {
4648 // TODO: Fix this b/109950150!
4649 // Okay this is a hack. There is a race between the UID turning active and
4650 // activity being resumed. The proper fix is very risky, so we temporary add
4651 // some polling which should happen pretty rarely anyway as the race is hard
4652 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004653 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004654 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004655 if (active) {
4656 break;
4657 }
4658 if (startTimeMillis <= 0) {
4659 startTimeMillis = uptimeMillis();
4660 }
4661 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004662 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004663 if (remainingTimeMillis <= 0) {
4664 break;
4665 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004666 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4667
4668 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004669 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004670 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004671 } while (true);
4672
Svet Ganov7b4ab782018-03-25 12:48:10 -07004673 if (active) {
4674 // Now that we found out the UID is actually active, cache that
4675 mActiveUids.insert(uid);
4676 }
4677 }
4678 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004679}
4680
Varun Shahb42f1eb2019-04-16 14:45:13 -07004681int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4682 Mutex::Autolock _l(mUidLock);
4683 return getProcStateLocked(uid);
4684}
4685
4686int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4687 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4688 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004689 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004690 }
4691 return procState;
4692}
4693
Austin Borgered99f642023-06-01 16:51:35 -07004694void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4695 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004696 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004697}
4698
Austin Borgered99f642023-06-01 16:51:35 -07004699void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004700 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004701}
4702
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004703void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4704 Mutex::Autolock _l(mUidLock);
4705 ALOGV("UidPolicy: ActivityManager has died");
4706 mRegistered = false;
4707 mActiveUids.clear();
4708}
4709
Austin Borgered99f642023-06-01 16:51:35 -07004710void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004711 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004712 bool wasActive = false;
4713 bool isActive = false;
4714 {
4715 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004716 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004717 mOverrideUids.erase(uid);
4718 if (insert) {
4719 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4720 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004721 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004722 }
4723 if (wasActive != isActive && !isActive) {
4724 sp<CameraService> service = mService.promote();
4725 if (service != nullptr) {
4726 service->blockClientsForUid(uid);
4727 }
4728 }
4729}
4730
4731// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004732// SensorPrivacyPolicy
4733// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004734
4735void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4736{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004737 Mutex::Autolock _l(mSensorPrivacyLock);
4738 if (mRegistered) {
4739 return;
4740 }
Evan Severson09ab4002021-02-10 14:15:19 -08004741 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004742 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004743 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004744 mSpm.addToggleSensorPrivacyListener(this);
4745 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004746 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004747 if (flags::camera_privacy_allowlist()) {
4748 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4749 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4750 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4751 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004752 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004753 if (res == OK) {
4754 mRegistered = true;
4755 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4756 }
4757}
4758
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004759void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4760 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004761 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004762 return;
4763 }
4764
4765 registerWithSensorPrivacyManager();
4766}
4767
4768void CameraService::SensorPrivacyPolicy::registerSelf() {
4769 // Use checkservice to see if the sensor_privacy service is available
4770 // If service is not available then register for notification
4771 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004772 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004773 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004774 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004775 } else {
4776 registerWithSensorPrivacyManager();
4777 }
4778}
4779
Michael Grooverd1d435a2018-12-18 17:39:42 -08004780void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4781 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004782 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004783 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004784 mSpm.removeToggleSensorPrivacyListener(this);
4785 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004786 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004787 mRegistered = false;
4788 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4789}
4790
4791bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004792 if (!mRegistered) {
4793 registerWithSensorPrivacyManager();
4794 }
4795
Michael Grooverd1d435a2018-12-18 17:39:42 -08004796 Mutex::Autolock _l(mSensorPrivacyLock);
4797 return mSensorPrivacyEnabled;
4798}
4799
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004800int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4801 if (!mRegistered) {
4802 registerWithSensorPrivacyManager();
4803 }
4804
4805 Mutex::Autolock _l(mSensorPrivacyLock);
4806 return mCameraPrivacyState;
4807}
4808
Evan Seversond0b69922022-01-27 10:47:34 -08004809bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004810 if (!hasCameraPrivacyFeature()) {
4811 return false;
4812 }
Evan Seversond0b69922022-01-27 10:47:34 -08004813 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004814}
4815
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004816bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4817 if (!hasCameraPrivacyFeature()) {
4818 return SensorPrivacyManager::DISABLED;
4819 }
4820 return mSpm.isCameraPrivacyEnabled(packageName);
4821}
4822
Evan Seversond0b69922022-01-27 10:47:34 -08004823binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004824 int toggleType, int sensor, bool enabled) {
4825 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4826 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4827 {
4828 Mutex::Autolock _l(mSensorPrivacyLock);
4829 mSensorPrivacyEnabled = enabled;
4830 }
4831 // if sensor privacy is enabled then block all clients from accessing the camera
4832 if (enabled) {
4833 sp<CameraService> service = mService.promote();
4834 if (service != nullptr) {
4835 service->blockAllClients();
4836 }
4837 }
4838 }
4839 return binder::Status::ok();
4840}
4841
4842binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4843 int, int sensor, int state) {
4844 if (!flags::camera_privacy_allowlist()
4845 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4846 return binder::Status::ok();
4847 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004848 {
4849 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004850 mCameraPrivacyState = state;
4851 }
4852 sp<CameraService> service = mService.promote();
4853 if (!service) {
4854 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004855 }
4856 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004857 if (state == SensorPrivacyManager::ENABLED) {
4858 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004859 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004860 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004861 }
4862 return binder::Status::ok();
4863}
4864
4865void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4866 Mutex::Autolock _l(mSensorPrivacyLock);
4867 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4868 mRegistered = false;
4869}
4870
Evan Severson09ab4002021-02-10 14:15:19 -08004871bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004872 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4873 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4874 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4875 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4876 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004877}
4878
Michael Grooverd1d435a2018-12-18 17:39:42 -08004879// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004880// CameraState
4881// ----------------------------------------------------------------------------
4882
Austin Borgered99f642023-06-01 16:51:35 -07004883CameraService::CameraState::CameraState(const std::string& id, int cost,
4884 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004885 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004886 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004887 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004888
4889CameraService::CameraState::~CameraState() {}
4890
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004891CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004892 Mutex::Autolock lock(mStatusLock);
4893 return mStatus;
4894}
4895
Austin Borgered99f642023-06-01 16:51:35 -07004896std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004897 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004898 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004899 return res;
4900}
4901
Ruben Brunkcc776712015-02-17 20:18:47 -08004902CameraParameters CameraService::CameraState::getShimParams() const {
4903 return mShimParams;
4904}
4905
4906void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4907 mShimParams = params;
4908}
4909
4910int CameraService::CameraState::getCost() const {
4911 return mCost;
4912}
4913
Austin Borgered99f642023-06-01 16:51:35 -07004914std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004915 return mConflicting;
4916}
4917
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004918SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4919 return mSystemCameraKind;
4920}
4921
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004922bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4923 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4924 != mPhysicalCameras.end();
4925}
4926
Austin Borgered99f642023-06-01 16:51:35 -07004927bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004928 Mutex::Autolock lock(mStatusLock);
4929 auto result = mUnavailablePhysicalIds.insert(physicalId);
4930 return result.second;
4931}
4932
Austin Borgered99f642023-06-01 16:51:35 -07004933bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004934 Mutex::Autolock lock(mStatusLock);
4935 auto count = mUnavailablePhysicalIds.erase(physicalId);
4936 return count > 0;
4937}
4938
Austin Borgered99f642023-06-01 16:51:35 -07004939void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004940 Mutex::Autolock lock(mStatusLock);
4941 mClientPackage = clientPackage;
4942}
4943
Austin Borgered99f642023-06-01 16:51:35 -07004944std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004945 Mutex::Autolock lock(mStatusLock);
4946 return mClientPackage;
4947}
4948
Ruben Brunkcc776712015-02-17 20:18:47 -08004949// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004950// ClientEventListener
4951// ----------------------------------------------------------------------------
4952
4953void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004954 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004955 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004956 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004957 if (basicClient.get() != nullptr) {
4958 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004959 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004960 static_cast<int>(basicClient->getClientUid()));
4961 }
4962}
4963
4964void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004965 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004966 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004967 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004968 if (basicClient.get() != nullptr) {
4969 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004970 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004971 static_cast<int>(basicClient->getClientUid()));
4972 }
4973}
4974
4975
4976// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004977// CameraClientManager
4978// ----------------------------------------------------------------------------
4979
Ruben Brunk99e69712015-05-26 17:25:07 -07004980CameraService::CameraClientManager::CameraClientManager() {
4981 setListener(std::make_shared<ClientEventListener>());
4982}
4983
Ruben Brunkcc776712015-02-17 20:18:47 -08004984CameraService::CameraClientManager::~CameraClientManager() {}
4985
4986sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004987 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004988 auto descriptor = get(id);
4989 if (descriptor == nullptr) {
4990 return sp<BasicClient>{nullptr};
4991 }
4992 return descriptor->getValue();
4993}
4994
Austin Borgered99f642023-06-01 16:51:35 -07004995std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004996 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004997 std::ostringstream ret;
4998 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004999 bool hasAny = false;
5000 for (auto& i : all) {
5001 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005002 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005003 int32_t cost = i->getCost();
5004 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005005 int32_t score = i->getPriority().getScore();
5006 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005007 auto conflicting = i->getConflicting();
5008 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005009 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005010 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005011 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005012 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005013 uid_t clientUid = clientSp->getClientUid();
5014 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005015 }
Austin Borgered99f642023-06-01 16:51:35 -07005016 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5017 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005018
Ruben Brunk6267b532015-04-30 17:44:07 -07005019 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005020 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005021 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005022 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005023 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005024 }
5025
Austin Borgered99f642023-06-01 16:51:35 -07005026 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005027 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005028 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005029 }
Austin Borgered99f642023-06-01 16:51:35 -07005030 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005031 }
Austin Borgered99f642023-06-01 16:51:35 -07005032 if (hasAny) ret << "\n";
5033 ret << "]\n";
5034 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005035}
5036
5037CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005038 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5039 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005040 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005041
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005042 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005043 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005044
Austin Borgered99f642023-06-01 16:51:35 -07005045 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005046 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5047 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005048}
5049
5050CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005051 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005052 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005053 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005054 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005055 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5056 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005057}
5058
5059// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005060// InjectionStatusListener
5061// ----------------------------------------------------------------------------
5062
5063void CameraService::InjectionStatusListener::addListener(
5064 const sp<ICameraInjectionCallback>& callback) {
5065 Mutex::Autolock lock(mListenerLock);
5066 if (mCameraInjectionCallback) return;
5067 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5068 if (res == OK) {
5069 mCameraInjectionCallback = callback;
5070 }
5071}
5072
5073void CameraService::InjectionStatusListener::removeListener() {
5074 Mutex::Autolock lock(mListenerLock);
5075 if (mCameraInjectionCallback == nullptr) {
5076 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5077 return;
5078 }
5079 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5080 mCameraInjectionCallback = nullptr;
5081}
5082
5083void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005084 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005085 if (mCameraInjectionCallback == nullptr) {
5086 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5087 return;
5088 }
Cliff Wud3a05312021-04-26 23:07:31 +08005089
5090 switch (err) {
5091 case -ENODEV:
5092 mCameraInjectionCallback->onInjectionError(
5093 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5094 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005095 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005096 break;
5097 case -EBUSY:
5098 mCameraInjectionCallback->onInjectionError(
5099 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5100 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005101 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005102 break;
5103 case DEAD_OBJECT:
5104 mCameraInjectionCallback->onInjectionError(
5105 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5106 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005107 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005108 break;
5109 case INVALID_OPERATION:
5110 mCameraInjectionCallback->onInjectionError(
5111 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5112 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005113 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005114 break;
5115 case UNKNOWN_TRANSACTION:
5116 mCameraInjectionCallback->onInjectionError(
5117 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5118 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005119 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005120 break;
5121 default:
5122 mCameraInjectionCallback->onInjectionError(
5123 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5124 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005125 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005126 }
Cliff Wud8cae102021-03-11 01:37:42 +08005127}
5128
5129void CameraService::InjectionStatusListener::binderDied(
5130 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005131 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5132 auto parent = mParent.promote();
5133 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005134 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5135 if (clientDescriptor != nullptr) {
5136 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5137 baseClientPtr->stopInjection();
5138 }
Cliff Wu3b268182021-07-06 15:44:43 +08005139 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005140 }
5141}
5142
5143// ----------------------------------------------------------------------------
5144// CameraInjectionSession
5145// ----------------------------------------------------------------------------
5146
5147binder::Status CameraService::CameraInjectionSession::stopInjection() {
5148 Mutex::Autolock lock(mInjectionSessionLock);
5149 auto parent = mParent.promote();
5150 if (parent == nullptr) {
5151 ALOGE("CameraInjectionSession: Parent is gone");
5152 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5153 "Camera service encountered error");
5154 }
Cliff Wud3a05312021-04-26 23:07:31 +08005155
5156 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005157 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5158 if (clientDescriptor != nullptr) {
5159 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5160 res = baseClientPtr->stopInjection();
5161 if (res != OK) {
5162 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5163 " ret != NO_ERROR: %d", res);
5164 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5165 "Camera session encountered error");
5166 }
5167 }
Cliff Wu3b268182021-07-06 15:44:43 +08005168 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005169 return binder::Status::ok();
5170}
5171
5172// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005173
5174static const int kDumpLockRetries = 50;
5175static const int kDumpLockSleep = 60000;
5176
5177static bool tryLock(Mutex& mutex)
5178{
5179 bool locked = false;
5180 for (int i = 0; i < kDumpLockRetries; ++i) {
5181 if (mutex.tryLock() == NO_ERROR) {
5182 locked = true;
5183 break;
5184 }
5185 usleep(kDumpLockSleep);
5186 }
5187 return locked;
5188}
5189
Rucha Katakwardf223072021-06-15 10:21:00 -07005190void CameraService::cacheDump() {
5191 if (mMemFd != -1) {
5192 const Vector<String16> args;
5193 ATRACE_CALL();
5194 // Acquiring service lock here will avoid the deadlock since
5195 // cacheDump will not be called during the second disconnect.
5196 Mutex::Autolock lock(mServiceLock);
5197
5198 Mutex::Autolock l(mCameraStatesLock);
5199 // Start collecting the info for open sessions and store it in temp file.
5200 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005201 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005202 auto clientDescriptor = mActiveClientManager.get(cameraId);
5203 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005204 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005205 // Log the current open session info before device is disconnected.
5206 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5207 }
5208 }
5209 }
5210}
5211
Mathias Agopian65ab4712010-07-14 17:59:35 -07005212status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005213 ATRACE_CALL();
5214
Austin Borgered99f642023-06-01 16:51:35 -07005215 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005216 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07005217 CameraThreadState::getCallingPid(),
5218 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005219 return NO_ERROR;
5220 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005221 bool locked = tryLock(mServiceLock);
5222 // failed to lock - CameraService is probably deadlocked
5223 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005224 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005225 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005226
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005227 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005228 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005229
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005230 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005231 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005232
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005233 if (locked) mServiceLock.unlock();
5234 return NO_ERROR;
5235 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005236 dprintf(fd, "\n== Service global info: ==\n\n");
5237 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005238 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005239 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5240 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005241 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5242 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5243 }
Austin Borgered99f642023-06-01 16:51:35 -07005244 std::string activeClientString = mActiveClientManager.toString();
5245 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5246 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005247 if (mStreamUseCaseOverrides.size() > 0) {
5248 dprintf(fd, "Active stream use case overrides:");
5249 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5250 dprintf(fd, " %" PRId64, useCaseOverride);
5251 }
5252 dprintf(fd, "\n");
5253 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005254
5255 dumpEventLog(fd);
5256
5257 bool stateLocked = tryLock(mCameraStatesLock);
5258 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005259 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005260 }
5261
Emilian Peevbd8c5032018-02-14 23:05:40 +00005262 int argSize = args.size();
5263 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005264 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005265 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005266 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005267 }
5268 break;
5269 }
5270 }
5271
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005272 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005273 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005274
Austin Borgered99f642023-06-01 16:51:35 -07005275 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005276
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005277 CameraParameters p = state.second->getShimParams();
5278 if (!p.isEmpty()) {
5279 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5280 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005281 }
5282
5283 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005284 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005285 // log the current open session info
5286 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005287 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005288 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005289 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005290
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005291 }
5292
5293 if (stateLocked) mCameraStatesLock.unlock();
5294
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005295 if (locked) mServiceLock.unlock();
5296
Emilian Peevf53f66e2017-04-11 14:29:43 +01005297 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005298
5299 dprintf(fd, "\n== Vendor tags: ==\n\n");
5300
5301 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5302 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005303 sp<VendorTagDescriptorCache> cache =
5304 VendorTagDescriptorCache::getGlobalVendorTagCache();
5305 if (cache == NULL) {
5306 dprintf(fd, "No vendor tags.\n");
5307 } else {
5308 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5309 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005310 } else {
5311 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5312 }
5313
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005314 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005315 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005316 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005317
5318 // Process dump arguments, if any
5319 int n = args.size();
5320 String16 verboseOption("-v");
5321 String16 unreachableOption("--unreachable");
5322 for (int i = 0; i < n; i++) {
5323 if (args[i] == verboseOption) {
5324 // change logging level
5325 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005326 std::string levelStr = toStdString(args[i+1]);
5327 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005328 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005329 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005330 } else if (args[i] == unreachableOption) {
5331 // Dump memory analysis
5332 // TODO - should limit be an argument parameter?
5333 UnreachableMemoryInfo info;
5334 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5335 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005336 dprintf(fd, "\n== Unable to dump unreachable memory. "
5337 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005338 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005339 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005340 std::string s = info.ToString(/*log_contents*/ true);
5341 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005342 }
5343 }
5344 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005345
5346 bool serviceLocked = tryLock(mServiceLock);
5347
5348 // Dump info from previous open sessions.
5349 // Reposition the offset to beginning of the file before reading
5350
5351 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5352 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5353 ssize_t size_read;
5354 char buf[4096];
5355 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5356 // Read data from file to a small buffer and write it to fd.
5357 write(fd, buf, size_read);
5358 if (size_read == -1) {
5359 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5360 break;
5361 }
5362 }
5363 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5364 } else {
5365 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5366 }
5367
5368 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005369 return NO_ERROR;
5370}
5371
Rucha Katakwardf223072021-06-15 10:21:00 -07005372void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005373 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005374 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005375 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005376 getFormattedCurrentTime().c_str(),
5377 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005378 dprintf(fd, " Client priority score: %d state: %d\n",
5379 clientDescriptor->getPriority().getScore(),
5380 clientDescriptor->getPriority().getState());
5381 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5382
5383 auto client = clientDescriptor->getValue();
5384 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005385 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005386
5387 client->dumpClient(fd, args);
5388}
5389
Austin Borgered99f642023-06-01 16:51:35 -07005390void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005391 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005392 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005393}
5394
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005395void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005396 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005397
5398 Mutex::Autolock l(mLogLock);
5399 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005400 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005401 }
5402
5403 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005404 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005405 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005406 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005407 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005408 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005409}
5410
Austin Borgered99f642023-06-01 16:51:35 -07005411void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005412 Mutex::Autolock lock(mLogLock);
5413 if (!isClientWatchedLocked(client)) { return; }
5414
5415 std::vector<std::string> dumpVector;
5416 client->dumpWatchedEventsToVector(dumpVector);
5417
5418 if (dumpVector.empty()) { return; }
5419
Austin Borgered99f642023-06-01 16:51:35 -07005420 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005421
Austin Borgered99f642023-06-01 16:51:35 -07005422 std::string currentTime = getFormattedCurrentTime();
5423 dumpString << "Cached @ ";
5424 dumpString << currentTime;
5425 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005426
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005427 size_t i = dumpVector.size();
5428
5429 // Store the string in reverse order (latest last)
5430 while (i > 0) {
5431 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005432 dumpString << cameraId;
5433 dumpString << ":";
5434 dumpString << client->getPackageName();
5435 dumpString << " ";
5436 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005437 }
5438
Austin Borgered99f642023-06-01 16:51:35 -07005439 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005440}
5441
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005442void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005443 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005444 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5445 if (mTorchClientMap[i] == who) {
5446 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005447 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005448 status_t res = mFlashlight->setTorchMode(cameraId, false);
5449 if (res) {
5450 ALOGE("%s: torch client died but couldn't turn off torch: "
5451 "%s (%d)", __FUNCTION__, strerror(-res), res);
5452 return;
5453 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005454 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005455 break;
5456 }
5457 }
5458}
5459
Ruben Brunkcc776712015-02-17 20:18:47 -08005460/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005461
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005462 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005463 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5464 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005465 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005466 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005467 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005468
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005469 // check torch client
5470 handleTorchClientBinderDied(who);
5471
5472 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005473 if(!evictClientIdByRemote(who)) {
5474 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005475 return;
5476 }
5477
Ruben Brunkcc776712015-02-17 20:18:47 -08005478 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5479 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005480}
5481
Austin Borgered99f642023-06-01 16:51:35 -07005482void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005483 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005484}
5485
Austin Borgered99f642023-06-01 16:51:35 -07005486void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005487 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005488 // Do not lock mServiceLock here or can get into a deadlock from
5489 // connect() -> disconnect -> updateStatus
5490
5491 auto state = getCameraState(cameraId);
5492
5493 if (state == nullptr) {
5494 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005495 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005496 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005497 }
5498
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005499 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5500 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5501 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005502 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005503 return;
5504 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005505
5506 // Collect the logical cameras without holding mStatusLock in updateStatus
5507 // as that can lead to a deadlock(b/162192331).
5508 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005509 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005510 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005511 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005512 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005513 (const std::string& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005514
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005515 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005516 // Update torch status if it has a flash unit.
5517 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005518 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005519 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5520 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005521 TorchModeStatus newTorchStatus =
5522 status == StatusInternal::PRESENT ?
5523 TorchModeStatus::AVAILABLE_OFF :
5524 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005525 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005526 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005527 }
5528 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005529 }
5530
5531 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005532 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005533 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005534
Ruben Brunkcc776712015-02-17 20:18:47 -08005535 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005536 bool isVendorListener = listener->isVendorListener();
5537 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
Kwangkyu Park01f84432023-09-15 17:08:17 +09005538 listener->getListenerPid(), listener->getListenerUid())) {
Shuzhen Wangb8259792021-05-27 09:27:06 -07005539 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005540 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005541 continue;
5542 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005543 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005544 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005545 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005546 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005547 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5548 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005549 // Also trigger the callbacks for cameras that were remapped to the current
5550 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005551 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005552 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5553 for (auto& remappedCameraId : remappedCameraIds) {
5554 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005555 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005556 listener->handleBinderStatus(ret,
5557 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5558 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5559 ret.exceptionCode());
5560 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005561 }
5562 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005563}
5564
Austin Borgered99f642023-06-01 16:51:35 -07005565void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5566 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005567 auto state = getCameraState(cameraId);
5568 if (state == nullptr) {
5569 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005570 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005571 return;
5572 }
5573 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005574 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005575 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005576 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005577 }
5578
Shuzhen Wang695044d2020-03-06 09:02:23 -08005579 Mutex::Autolock lock(mStatusListenerLock);
5580
5581 for (const auto& it : mListenerList) {
5582 if (!it->isOpenCloseCallbackAllowed()) {
5583 continue;
5584 }
5585
5586 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005587 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005588 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005589 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005590 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005591 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005592
5593 it->handleBinderStatus(ret,
5594 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5595 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005596 }
5597}
5598
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005599template<class Func>
5600void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005601 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005602 std::initializer_list<StatusInternal> rejectSourceStates,
5603 Func onStatusUpdatedLocked) {
5604 Mutex::Autolock lock(mStatusLock);
5605 StatusInternal oldStatus = mStatus;
5606 mStatus = status;
5607
5608 if (oldStatus == status) {
5609 return;
5610 }
5611
5612 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005613 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005614
5615 if (oldStatus == StatusInternal::NOT_PRESENT &&
5616 (status != StatusInternal::PRESENT &&
5617 status != StatusInternal::ENUMERATING)) {
5618
5619 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5620 __FUNCTION__);
5621 mStatus = oldStatus;
5622 return;
5623 }
5624
5625 /**
5626 * Sometimes we want to conditionally do a transition.
5627 * For example if a client disconnects, we want to go to PRESENT
5628 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5629 */
5630 for (auto& rejectStatus : rejectSourceStates) {
5631 if (oldStatus == rejectStatus) {
5632 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005633 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005634 mStatus = oldStatus;
5635 return;
5636 }
5637 }
5638
5639 onStatusUpdatedLocked(cameraId, status);
5640}
5641
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005642status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005643 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005644 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005645 if (!status) {
5646 return BAD_VALUE;
5647 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005648 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5649 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005650 // invalid camera ID or the camera doesn't have a flash unit
5651 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005652 }
5653
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005654 *status = mTorchStatusMap.valueAt(index);
5655 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005656}
5657
Austin Borgered99f642023-06-01 16:51:35 -07005658status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005659 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005660 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5661 if (index == NAME_NOT_FOUND) {
5662 return BAD_VALUE;
5663 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005664 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005665
5666 return OK;
5667}
5668
Austin Borgered99f642023-06-01 16:51:35 -07005669std::list<std::string> CameraService::getLogicalCameras(
5670 const std::string& physicalCameraId) {
5671 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005672 Mutex::Autolock lock(mCameraStatesLock);
5673 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005674 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5675 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005676 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005677 }
5678 return retList;
5679}
5680
5681void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005682 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005683 SystemCameraKind deviceKind) {
5684 // mStatusListenerLock is expected to be locked
5685 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005686 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005687 // Note: we check only the deviceKind of the physical camera id
5688 // since, logical camera ids and their physical camera ids are
5689 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005690 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5691 listener->getListenerPid(), listener->getListenerUid())) {
5692 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005693 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005694 continue;
5695 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005696 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005697 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005698 listener->handleBinderStatus(ret,
5699 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5700 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5701 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005702 }
5703 }
5704}
5705
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005706
Svet Ganova453d0d2018-01-11 15:37:58 -08005707void CameraService::blockClientsForUid(uid_t uid) {
5708 const auto clients = mActiveClientManager.getAll();
5709 for (auto& current : clients) {
5710 if (current != nullptr) {
5711 const auto basicClient = current->getValue();
5712 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5713 basicClient->block();
5714 }
5715 }
5716 }
5717}
5718
Michael Grooverd1d435a2018-12-18 17:39:42 -08005719void CameraService::blockAllClients() {
5720 const auto clients = mActiveClientManager.getAll();
5721 for (auto& current : clients) {
5722 if (current != nullptr) {
5723 const auto basicClient = current->getValue();
5724 if (basicClient.get() != nullptr) {
5725 basicClient->block();
5726 }
5727 }
5728 }
5729}
5730
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005731void CameraService::blockPrivacyEnabledClients() {
5732 const auto clients = mActiveClientManager.getAll();
5733 for (auto& current : clients) {
5734 if (current != nullptr) {
5735 const auto basicClient = current->getValue();
5736 if (basicClient.get() != nullptr) {
5737 std::string pkgName = basicClient->getPackageName();
5738 bool cameraPrivacyEnabled =
5739 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5740 if (cameraPrivacyEnabled) {
5741 basicClient->block();
5742 }
5743 }
5744 }
5745 }
5746}
5747
Svet Ganova453d0d2018-01-11 15:37:58 -08005748// NOTE: This is a remote API - make sure all args are validated
5749status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005750 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005751 return PERMISSION_DENIED;
5752 }
5753 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5754 return BAD_VALUE;
5755 }
Austin Borgered99f642023-06-01 16:51:35 -07005756 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005757 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005758 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005759 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005760 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005761 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005762 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005763 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005764 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005765 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005766 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005767 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005768 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005769 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005770 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005771 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005772 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005773 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005774 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005775 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005776 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005777 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005778 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005779 handleClearStreamUseCaseOverrides();
5780 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005781 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005782 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005783 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005784 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005785 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005786 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005787 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005788 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005789 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005790 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005791 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005792 }
5793 printHelp(err);
5794 return BAD_VALUE;
5795}
5796
malikakash82ed4352023-07-21 22:44:34 +00005797status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5798 uid_t uid = IPCThreadState::self()->getCallingUid();
5799 if (uid != AID_ROOT) {
5800 dprintf(err, "Must be adb root\n");
5801 return PERMISSION_DENIED;
5802 }
5803 if (args.size() != 4) {
5804 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5805 return BAD_VALUE;
5806 }
Austin Borgered99f642023-06-01 16:51:35 -07005807 std::string packageName = toStdString(args[1]);
5808 std::string cameraIdToReplace = toStdString(args[2]);
5809 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005810 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5811 return OK;
5812}
5813
Svet Ganova453d0d2018-01-11 15:37:58 -08005814status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005815 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005816
Svet Ganova453d0d2018-01-11 15:37:58 -08005817 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005818 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005819 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005820 } else if ((args[2] != toString16("idle"))) {
5821 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005822 return BAD_VALUE;
5823 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005824
5825 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005826 if (args.size() >= 5 && args[3] == toString16("--user")) {
5827 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005828 }
5829
5830 uid_t uid;
5831 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5832 return BAD_VALUE;
5833 }
5834
5835 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005836 return NO_ERROR;
5837}
5838
5839status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005840 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005841
5842 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005843 if (args.size() >= 4 && args[2] == toString16("--user")) {
5844 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005845 }
5846
5847 uid_t uid;
5848 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005849 return BAD_VALUE;
5850 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005851
5852 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005853 return NO_ERROR;
5854}
5855
5856status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005857 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005858
5859 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005860 if (args.size() >= 4 && args[2] == toString16("--user")) {
5861 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005862 }
5863
5864 uid_t uid;
5865 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005866 return BAD_VALUE;
5867 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005868
5869 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005870 return dprintf(out, "active\n");
5871 } else {
5872 return dprintf(out, "idle\n");
5873 }
5874}
5875
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005876status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005877 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005878 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5879 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5880 Mutex::Autolock lock(mServiceLock);
5881
5882 mOverrideRotateAndCropMode = rotateValue;
5883
5884 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5885
5886 const auto clients = mActiveClientManager.getAll();
5887 for (auto& current : clients) {
5888 if (current != nullptr) {
5889 const auto basicClient = current->getValue();
5890 if (basicClient.get() != nullptr) {
5891 basicClient->setRotateAndCropOverride(rotateValue);
5892 }
5893 }
5894 }
5895
5896 return OK;
5897}
5898
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005899status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5900 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005901 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005902 if ((*end != '\0') ||
5903 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5904 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5905 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5906 return BAD_VALUE;
5907 }
5908
5909 Mutex::Autolock lock(mServiceLock);
5910 mOverrideAutoframingMode = autoframingValue;
5911
5912 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5913
5914 const auto clients = mActiveClientManager.getAll();
5915 for (auto& current : clients) {
5916 if (current != nullptr) {
5917 const auto basicClient = current->getValue();
5918 if (basicClient.get() != nullptr) {
5919 basicClient->setAutoframingOverride(autoframingValue);
5920 }
5921 }
5922 }
5923
5924 return OK;
5925}
5926
Ravneetaeb20dc2022-03-30 05:33:03 +00005927status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005928 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005929
5930 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5931
5932 Mutex::Autolock lock(mServiceLock);
5933
5934 mCameraServiceWatchdogEnabled = enableWatchdog;
5935
5936 const auto clients = mActiveClientManager.getAll();
5937 for (auto& current : clients) {
5938 if (current != nullptr) {
5939 const auto basicClient = current->getValue();
5940 if (basicClient.get() != nullptr) {
5941 basicClient->setCameraServiceWatchdog(enableWatchdog);
5942 }
5943 }
5944 }
5945
5946 return OK;
5947}
5948
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005949status_t CameraService::handleGetRotateAndCrop(int out) {
5950 Mutex::Autolock lock(mServiceLock);
5951
5952 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5953}
5954
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005955status_t CameraService::handleGetAutoframing(int out) {
5956 Mutex::Autolock lock(mServiceLock);
5957
5958 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5959}
5960
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005961status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5962 char *endPtr;
5963 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005964 std::string maskString = toStdString(args[1]);
5965 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005966
5967 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005968 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005969 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5970
5971 Mutex::Autolock lock(mServiceLock);
5972
5973 mImageDumpMask = maskValue;
5974
5975 return OK;
5976}
5977
5978status_t CameraService::handleGetImageDumpMask(int out) {
5979 Mutex::Autolock lock(mServiceLock);
5980
5981 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5982}
5983
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005984status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005985 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005986 if (errno != 0) return BAD_VALUE;
5987
5988 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5989 Mutex::Autolock lock(mServiceLock);
5990
5991 mOverrideCameraMuteMode = (muteValue == 1);
5992
5993 const auto clients = mActiveClientManager.getAll();
5994 for (auto& current : clients) {
5995 if (current != nullptr) {
5996 const auto basicClient = current->getValue();
5997 if (basicClient.get() != nullptr) {
5998 if (basicClient->supportsCameraMute()) {
5999 basicClient->setCameraMute(mOverrideCameraMuteMode);
6000 }
6001 }
6002 }
6003 }
6004
6005 return OK;
6006}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006007
Shuzhen Wang16610a62022-12-15 22:38:07 -08006008status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6009 std::vector<int64_t> useCasesOverride;
6010 for (size_t i = 1; i < args.size(); i++) {
6011 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006012 std::string arg = toStdString(args[i]);
6013 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006014 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006015 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006016 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006017 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006018 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006019 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006020 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006021 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006022 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006023 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006024 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006025 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006026 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6027 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006028 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006029 return BAD_VALUE;
6030 }
6031 useCasesOverride.push_back(useCase);
6032 }
6033
6034 Mutex::Autolock lock(mServiceLock);
6035 mStreamUseCaseOverrides = std::move(useCasesOverride);
6036
6037 return OK;
6038}
6039
6040void CameraService::handleClearStreamUseCaseOverrides() {
6041 Mutex::Autolock lock(mServiceLock);
6042 mStreamUseCaseOverrides.clear();
6043}
6044
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006045status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6046 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006047 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006048 if ((*end != '\0') ||
6049 (zoomOverrideValue != -1 &&
6050 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6051 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6052 return BAD_VALUE;
6053 }
6054
6055 Mutex::Autolock lock(mServiceLock);
6056 mZoomOverrideValue = zoomOverrideValue;
6057
6058 const auto clients = mActiveClientManager.getAll();
6059 for (auto& current : clients) {
6060 if (current != nullptr) {
6061 const auto basicClient = current->getValue();
6062 if (basicClient.get() != nullptr) {
6063 if (basicClient->supportsZoomOverride()) {
6064 basicClient->setZoomOverride(mZoomOverrideValue);
6065 }
6066 }
6067 }
6068 }
6069
6070 return OK;
6071}
6072
Avichal Rakesh84147132021-11-11 17:47:11 -08006073status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006074 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006075 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006076 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006077 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006078 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006079 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006080 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006081 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006082 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006083 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006084 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006085 dprintf(outFd, "Camera service watch commands:\n"
6086 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6087 " starts watching the provided tags for clients with provided package\n"
6088 " recognizes tag shorthands like '3a'\n"
6089 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006090 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006091 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006092 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006093 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006094 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006095 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006096 return BAD_VALUE;
6097}
6098
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006099status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6100 Mutex::Autolock lock(mLogLock);
6101 size_t tagsIdx; // index of '-m'
6102 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006103 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006104 if (tagsIdx < args.size() - 1) {
6105 tags = args[tagsIdx + 1];
6106 } else {
6107 dprintf(outFd, "No tags provided.\n");
6108 return BAD_VALUE;
6109 }
6110
6111 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006112 // watch all clients if no clients are provided
6113 String16 clients = toString16(kWatchAllClientsFlag);
6114 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006115 clientsIdx++);
6116 if (clientsIdx < args.size() - 1) {
6117 clients = args[clientsIdx + 1];
6118 }
Austin Borgered99f642023-06-01 16:51:35 -07006119 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006120
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006121 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006122 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006123
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006124 bool serviceLock = tryLock(mServiceLock);
6125 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006126 auto cameraClients = mActiveClientManager.getAll();
6127 for (const auto &clientDescriptor: cameraClients) {
6128 if (clientDescriptor == nullptr) { continue; }
6129 sp<BasicClient> client = clientDescriptor->getValue();
6130 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006131
6132 if (isClientWatchedLocked(client.get())) {
6133 client->startWatchingTags(mMonitorTags, outFd);
6134 numWatchedClients++;
6135 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006136 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006137 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6138
6139 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006140 return OK;
6141}
6142
6143status_t CameraService::stopWatchingTags(int outFd) {
6144 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006145 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006146 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006147
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006148 mWatchedClientPackages.clear();
6149 mWatchedClientsDumpCache.clear();
6150
6151 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006152 auto cameraClients = mActiveClientManager.getAll();
6153 for (const auto &clientDescriptor : cameraClients) {
6154 if (clientDescriptor == nullptr) { continue; }
6155 sp<BasicClient> client = clientDescriptor->getValue();
6156 if (client.get() == nullptr) { continue; }
6157 client->stopWatchingTags(outFd);
6158 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006159 dprintf(outFd, "Stopped watching all clients.\n");
6160 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006161 return OK;
6162}
6163
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006164status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6165 Mutex::Autolock lock(mLogLock);
6166 size_t clearedSize = mWatchedClientsDumpCache.size();
6167 mWatchedClientsDumpCache.clear();
6168 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6169 return OK;
6170}
6171
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006172status_t CameraService::printWatchedTags(int outFd) {
6173 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006174 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006175
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006176 bool printedSomething = false; // tracks if any monitoring information was printed
6177 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006178
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006179 bool serviceLock = tryLock(mServiceLock);
6180 // get all watched clients that are currently connected
6181 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6182 if (clientDescriptor == nullptr) { continue; }
6183
6184 sp<BasicClient> client = clientDescriptor->getValue();
6185 if (client.get() == nullptr) { continue; }
6186 if (!isClientWatchedLocked(client.get())) { continue; }
6187
6188 std::vector<std::string> dumpVector;
6189 client->dumpWatchedEventsToVector(dumpVector);
6190
6191 size_t printIdx = dumpVector.size();
6192 if (printIdx == 0) {
6193 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006194 }
6195
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006196 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006197 const std::string &cameraId = clientDescriptor->getKey();
6198 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006199 while(printIdx > 0) {
6200 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006201 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006202 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006203 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006204 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006205 printedSomething = true;
6206
6207 connectedMonitoredClients.emplace(client->getPackageName());
6208 }
6209 if (serviceLock) { mServiceLock.unlock(); }
6210
6211 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6212 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006213 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006214 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6215 continue;
6216 }
6217
Austin Borgered99f642023-06-01 16:51:35 -07006218 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006219 dprintf(outFd, "%s\n", kv.second.c_str());
6220 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006221 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006222
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006223 if (!printedSomething) {
6224 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006225 }
6226
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006227 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006228}
6229
Avichal Rakesh84147132021-11-11 17:47:11 -08006230// Print all events in vector `events' that came after lastPrintedEvent
6231void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006232 const std::string &cameraId,
6233 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006234 const std::vector<std::string> &events,
6235 const std::string &lastPrintedEvent) {
6236 if (events.empty()) { return; }
6237
6238 // index of lastPrintedEvent in events.
6239 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6240 size_t lastPrintedIdx;
6241 for (lastPrintedIdx = 0;
6242 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6243 lastPrintedIdx++);
6244
6245 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6246
Avichal Rakesh84147132021-11-11 17:47:11 -08006247 // print events in chronological order (latest event last)
6248 size_t idxToPrint = lastPrintedIdx;
6249 do {
6250 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006251 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6252 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006253 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006254}
6255
6256// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6257// command should be interrupted if the user presses the return key, or if user loses any way to
6258// signal interrupt.
6259// If timeoutMs == 0, this function will always return false
6260bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6261 struct timeval startTime;
6262 int startTimeError = gettimeofday(&startTime, nullptr);
6263 if (startTimeError) {
6264 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6265 return true;
6266 }
6267
6268 const nfds_t numFds = 1;
6269 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6270
6271 struct timeval currTime;
6272 char buffer[2];
6273 while(true) {
6274 int currTimeError = gettimeofday(&currTime, nullptr);
6275 if (currTimeError) {
6276 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6277 return true;
6278 }
6279
6280 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6281 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6282 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6283
6284 if (remainingTimeMs <= 0) {
6285 // No user interrupt within timeoutMs, don't interrupt watch command
6286 return false;
6287 }
6288
6289 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6290 if (numFdsUpdated < 0) {
6291 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6292 return true;
6293 }
6294
6295 if (numFdsUpdated == 0) {
6296 // No user input within timeoutMs, don't interrupt watch command
6297 return false;
6298 }
6299
6300 if (!(pollFd.revents & POLLIN)) {
6301 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6302 return true;
6303 }
6304
6305 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6306 if (sizeRead < 0) {
6307 dprintf(outFd, "Error reading user input. Exiting.\n");
6308 return true;
6309 }
6310
6311 if (sizeRead == 0) {
6312 // Reached end of input fd (can happen if input is piped)
6313 // User has no way to signal an interrupt, so interrupt here
6314 return true;
6315 }
6316
6317 if (buffer[0] == '\n') {
6318 // User pressed return, interrupt watch command.
6319 return true;
6320 }
6321 }
6322}
6323
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006324status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6325 int inFd, int outFd) {
6326 // Figure out refresh interval, if present in args
6327 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006328 if (args.size() > 2) {
6329 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006330 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006331 intervalIdx++);
6332
6333 size_t intervalValIdx = intervalIdx + 1;
6334 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006335 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006336 if (errno) { return BAD_VALUE; }
6337 }
6338 }
6339
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006340 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6341 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006342
Avichal Rakesh84147132021-11-11 17:47:11 -08006343 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006344 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006345
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006346 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006347 bool serviceLock = tryLock(mServiceLock);
6348 auto cameraClients = mActiveClientManager.getAll();
6349 if (serviceLock) { mServiceLock.unlock(); }
6350
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006351 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006352 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006353 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006354
6355 sp<BasicClient> client = clientDescriptor->getValue();
6356 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006357 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006358
Austin Borgered99f642023-06-01 16:51:35 -07006359 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006360 // This also initializes the map entries with an empty string
6361 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6362
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006363 std::vector<std::string> latestEvents;
6364 client->dumpWatchedEventsToVector(latestEvents);
6365
6366 if (!latestEvents.empty()) {
6367 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006368 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006369 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006370 latestEvents,
6371 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006372 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006373 }
6374 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006375 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006376 break;
6377 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006378 }
6379 return OK;
6380}
6381
Austin Borgered99f642023-06-01 16:51:35 -07006382void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006383 mWatchedClientPackages.clear();
6384
Austin Borgered99f642023-06-01 16:51:35 -07006385 std::istringstream iss(clients);
6386 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006387
Austin Borgered99f642023-06-01 16:51:35 -07006388 while (std::getline(iss, nextClient, ',')) {
6389 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006390 // Don't need to track any other package if 'all' is present
6391 mWatchedClientPackages.clear();
6392 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6393 break;
6394 }
6395
6396 // track package names
6397 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006398 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006399}
6400
Svet Ganova453d0d2018-01-11 15:37:58 -08006401status_t CameraService::printHelp(int out) {
6402 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006403 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6404 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6405 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006406 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6407 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6408 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006409 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6410 " Valid values 0=false, 1=true, 2=auto\n"
6411 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006412 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6413 " Valid values 0=OFF, 1=ON for JPEG\n"
6414 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006415 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006416 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6417 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6418 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6419 " on. In case the number of usecases is smaller than the number of streams, the\n"
6420 " last use case is assigned to all the remaining streams. In case of multiple\n"
6421 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6422 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6423 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6424 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006425 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6426 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006427 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6428 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006429 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006430 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006431 " help print this message\n");
6432}
6433
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006434bool CameraService::isClientWatched(const BasicClient *client) {
6435 Mutex::Autolock lock(mLogLock);
6436 return isClientWatchedLocked(client);
6437}
6438
6439bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6440 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6441 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6442}
6443
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006444int32_t CameraService::updateAudioRestriction() {
6445 Mutex::Autolock lock(mServiceLock);
6446 return updateAudioRestrictionLocked();
6447}
6448
6449int32_t CameraService::updateAudioRestrictionLocked() {
6450 int32_t mode = 0;
6451 // iterate through all active client
6452 for (const auto& i : mActiveClientManager.getAll()) {
6453 const auto clientSp = i->getValue();
6454 mode |= clientSp->getAudioRestriction();
6455 }
6456
6457 bool modeChanged = (mAudioRestriction != mode);
6458 mAudioRestriction = mode;
6459 if (modeChanged) {
6460 mAppOps.setCameraAudioRestriction(mode);
6461 }
6462 return mode;
6463}
6464
Austin Borgered99f642023-06-01 16:51:35 -07006465status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006466 sp<BasicClient> clientSp) {
6467 std::unique_ptr<AutoConditionLock> lock =
6468 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6469 status_t res = NO_ERROR;
6470 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006471 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006472 mInjectionStatusListener->notifyInjectionError(
6473 externalCamId, UNKNOWN_TRANSACTION);
6474 clientSp->notifyError(
6475 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6476 CaptureResultExtras());
6477
6478 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6479 // other clients from connecting in mServiceLockWrapper if held
6480 mServiceLock.unlock();
6481
6482 // Clear caller identity temporarily so client disconnect PID checks work correctly
6483 int64_t token = CameraThreadState::clearCallingIdentity();
6484 clientSp->disconnect();
6485 CameraThreadState::restoreCallingIdentity(token);
6486
6487 // Reacquire mServiceLock
6488 mServiceLock.lock();
6489 }
6490
6491 return res;
6492}
6493
Cliff Wud3a05312021-04-26 23:07:31 +08006494void CameraService::clearInjectionParameters() {
6495 {
6496 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006497 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006498 mInjectionInternalCamId = "";
6499 }
6500 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006501 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006502}
6503
Mathias Agopian65ab4712010-07-14 17:59:35 -07006504}; // namespace android