blob: f73e34e10e09ef9f59eb2e756acb13e01e9f0e59 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Joanne Chung02c13d02023-01-16 12:58:05 +000041#include <android/permission/PermissionChecker.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080042#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080043#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070044#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/MemoryBase.h>
46#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080047#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080049#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070050#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070051#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070052#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080053#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080054#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070055#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070056#include "hidl/HidlCameraService.h"
57#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080058#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070059#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070060#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080061#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070062#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070063#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000064#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070065#include <utils/Errors.h>
66#include <utils/Log.h>
67#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070068#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080069#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080070#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080071#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080072#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070073#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000074#include <binder/IServiceManager.h>
75#include <binder/IActivityManager.h>
Austin Borgered99f642023-06-01 16:51:35 -070076#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080077
Ruben Brunkb2119af2014-05-09 19:57:56 -070078#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070079
80#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070081#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070082#include "api2/CameraDeviceClient.h"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070083#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000084#include "utils/TagMonitor.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070085#include "utils/CameraThreadState.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070086#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080089namespace {
90 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080091 const char* kActivityServiceName = "activity";
92 const char* kSensorPrivacyServiceName = "sensor_privacy";
93 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070094 const char* kProcessInfoServiceName = "processinfo";
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080095}; // namespace anonymous
96
Mathias Agopian65ab4712010-07-14 17:59:35 -070097namespace android {
98
Austin Borgerea931242021-12-13 23:10:41 +000099using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700100using namespace camera3::SessionConfigurationUtils;
101
102using binder::Status;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700103using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700104using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800105using hardware::ICamera;
106using hardware::ICameraClient;
107using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800108using hardware::camera2::ICameraInjectionCallback;
109using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800110using hardware::camera2::utils::CameraIdAndSessionConfiguration;
111using hardware::camera2::utils::ConcurrentCameraIdCombination;
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700112namespace flags = com::android::internal::camera::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800113
Mathias Agopian65ab4712010-07-14 17:59:35 -0700114// ----------------------------------------------------------------------------
115// Logging support -- this is for debugging only
116// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700117volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700118
Steve Blockb8a80522011-12-20 16:23:08 +0000119#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
120#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700121
122static void setLogLevel(int level) {
123 android_atomic_write(level, &gLogLevel);
124}
125
Henri Chataingbcb99452023-11-01 17:40:30 +0000126int32_t format_as(CameraService::StatusInternal s) {
127 return fmt::underlying(s);
128}
129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131
Austin Borgered99f642023-06-01 16:51:35 -0700132static const std::string sDumpPermission("android.permission.DUMP");
133static const std::string sManageCameraPermission("android.permission.MANAGE_CAMERA");
134static const std::string sCameraPermission("android.permission.CAMERA");
135static const std::string sSystemCameraPermission("android.permission.SYSTEM_CAMERA");
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700136static const std::string sCameraHeadlessSystemUserPermission(
137 "android.permission.CAMERA_HEADLESS_SYSTEM_USER");
Austin Borgered99f642023-06-01 16:51:35 -0700138static const std::string
Jayant Chowdhary5216b212019-07-17 09:26:23 -0700139 sCameraSendSystemEventsPermission("android.permission.CAMERA_SEND_SYSTEM_EVENTS");
Austin Borgered99f642023-06-01 16:51:35 -0700140static const std::string sCameraOpenCloseListenerPermission(
Shuzhen Wang695044d2020-03-06 09:02:23 -0800141 "android.permission.CAMERA_OPEN_CLOSE_LISTENER");
Austin Borgered99f642023-06-01 16:51:35 -0700142static const std::string
Cliff Wud8cae102021-03-11 01:37:42 +0800143 sCameraInjectExternalCameraPermission("android.permission.CAMERA_INJECT_EXTERNAL_CAMERA");
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000144// Constant integer for FGS Logging, used to denote the API type for logger
145static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700146const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800147static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
148static constexpr int32_t kSystemNativeClientState =
149 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700150static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700151
Austin Borgered99f642023-06-01 16:51:35 -0700152const std::string CameraService::kOfflineDevice("offline-");
153const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700154
Rucha Katakward9ea6452021-05-06 11:57:16 -0700155// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700156static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700157
Austin Borger74fca042022-05-23 12:41:21 -0700158CameraService::CameraService(
159 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper) :
160 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
161 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800162 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800163 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700164 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700165 mSoundRef(0), mInitialized(false),
166 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000167 ALOGI("CameraService started (pid=%d)", getpid());
Ruben Brunkcc776712015-02-17 20:18:47 -0800168 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700169 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
170 if (mMemFd == -1) {
171 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
172 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700173}
174
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800175// The word 'System' here does not refer to clients only on the system
176// partition. They just need to have a android system uid.
177static bool doesClientHaveSystemUid() {
178 return (CameraThreadState::getCallingUid() < AID_APP_START);
179}
180
Charles Chena7b613c2023-01-24 21:57:33 +0000181// Enable processes with isolated AID to request the binder
182void CameraService::instantiate() {
183 CameraService::publish(true);
184}
185
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800186void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700187 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800188 return;
189 }
190
191 ALOGV("appops service registered. setting camera audio restriction");
192 mAppOps.setCameraAudioRestriction(mAudioRestriction);
193}
194
Iliyan Malchev8951a972011-04-14 16:55:59 -0700195void CameraService::onFirstRef()
196{
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -0700197
Ruben Brunkcc776712015-02-17 20:18:47 -0800198 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800199
Iliyan Malchev8951a972011-04-14 16:55:59 -0700200 BnCameraService::onFirstRef();
201
Ruben Brunk99e69712015-05-26 17:25:07 -0700202 // Update battery life tracking if service is restarting
203 BatteryNotifier& notifier(BatteryNotifier::getInstance());
204 notifier.noteResetCamera();
205 notifier.noteResetFlashlight();
206
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800207 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800208
Emilian Peevf53f66e2017-04-11 14:29:43 +0100209 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800210 if (res == OK) {
211 mInitialized = true;
212 }
213
Svet Ganova453d0d2018-01-11 15:37:58 -0800214 mUidPolicy = new UidPolicy(this);
215 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800216 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
217 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800218 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800219
220 // appops function setCamerAudioRestriction uses getService which
221 // is blocking till the appops service is ready. To enable early
222 // boot availability for cameraservice, use checkService which is
223 // non blocking and register for notifications
224 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700225 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800226 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700227 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800228 } else {
229 mAppOps.setCameraAudioRestriction(mAudioRestriction);
230 }
231
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700232 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
233 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000234 // Deprecated, so it will fail to register on newer devices
235 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700236 __FUNCTION__);
237 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700238
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700239 if (!AidlCameraService::registerService(this)) {
240 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
241 }
242
Shuzhen Wang24b44152019-09-20 10:38:11 -0700243 // This needs to be last call in this function, so that it's as close to
244 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700245 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700246 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800247}
248
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800249status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800250 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100251
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800252 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000253 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800254 {
255 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800256
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800257 if (nullptr == mCameraProviderManager.get()) {
258 mCameraProviderManager = new CameraProviderManager();
259 res = mCameraProviderManager->initialize(this);
260 if (res != OK) {
261 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
262 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700263 logServiceError("Unable to initialize camera provider manager",
264 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100266 }
267 }
268
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800269
270 // Setup vendor tags before we call get_camera_info the first time
271 // because HAL might need to setup static vendor keys in get_camera_info
272 // TODO: maybe put this into CameraProviderManager::initialize()?
273 mCameraProviderManager->setUpVendorTags();
274
275 if (nullptr == mFlashlight.get()) {
276 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700277 }
278
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800279 res = mFlashlight->findFlashUnits();
280 if (res != OK) {
281 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
282 }
283
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000284 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800285 }
286
287
288 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700289 if (getCameraState(cameraId) == nullptr) {
290 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800291 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000292 if (unavailPhysicalIds.count(cameraId) > 0) {
293 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700294 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000295 }
296 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800297 }
298
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700299 // Derive primary rear/front cameras, and filter their charactierstics.
300 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700301 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700302 // Assume internal cameras are advertised from the same
303 // provider. If multiple providers are registered at different time,
304 // and each provider contains multiple internal color cameras, the current
305 // logic may filter the characteristics of more than one front/rear color
306 // cameras.
307 Mutex::Autolock l(mServiceLock);
308 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700309 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700310
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800311 return OK;
312}
313
Austin Borgered99f642023-06-01 16:51:35 -0700314void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700315 SystemCameraKind systemCameraKind) {
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800316 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800317 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700318 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
319 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000320 ALOGV("%s: Skipping torch callback for system-only camera device %s",
321 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700322 continue;
323 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700324 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -0700325 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700326 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
327 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +0000328 // Also trigger the torch callbacks for cameras that were remapped to the current cameraId
329 // for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -0700330 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +0000331 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
332 for (auto& remappedCameraId : remappedCameraIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700333 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +0000334 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
335 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
336 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800337 }
338}
339
Mathias Agopian65ab4712010-07-14 17:59:35 -0700340CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800341 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800342 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800343 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800344 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700345}
346
Emilian Peevaee727d2017-05-04 16:35:48 +0100347void CameraService::onNewProviderRegistered() {
348 enumerateProviders();
349}
350
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700351void CameraService::filterAPI1SystemCameraLocked(
352 const std::vector<std::string> &normalDeviceIds) {
353 mNormalDeviceIdsWithoutSystemCamera.clear();
354 for (auto &deviceId : normalDeviceIds) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700355 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -0700356 if (getSystemCameraKind(deviceId, &deviceKind) != OK) {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700357 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, deviceId.c_str());
358 continue;
359 }
360 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700361 // All system camera ids will necessarily come after public camera
362 // device ids as per the HAL interface contract.
363 break;
364 }
365 mNormalDeviceIdsWithoutSystemCamera.push_back(deviceId);
366 }
367 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
368 mNormalDeviceIdsWithoutSystemCamera.size());
369}
370
Austin Borgered99f642023-06-01 16:51:35 -0700371status_t CameraService::getSystemCameraKind(const std::string& cameraId,
372 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700373 auto state = getCameraState(cameraId);
374 if (state != nullptr) {
375 *kind = state->getSystemCameraKind();
376 return OK;
377 }
378 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700379 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700380}
381
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800382void CameraService::updateCameraNumAndIds() {
383 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700384 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
385 // Excludes hidden secure cameras
386 mNumberOfCameras =
387 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
388 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800389 mNormalDeviceIds =
390 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700391 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800392}
393
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700394void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700395 // To claim to be S Performance primary cameras, the cameras must be
396 // backward compatible. So performance class primary camera Ids must be API1
397 // compatible.
398 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
399 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
400 int facing = -1;
401 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800402 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700403 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800404 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700405 if (facing == -1) {
406 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
407 return;
408 }
409
410 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
411 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700412 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
413 if (res == OK) {
414 mPerfClassPrimaryCameraIds.insert(cameraId);
415 } else {
416 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
417 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
418 break;
419 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700420
421 if (facing == hardware::CAMERA_FACING_BACK) {
422 firstRearCameraSeen = true;
423 }
424 if (facing == hardware::CAMERA_FACING_FRONT) {
425 firstFrontCameraSeen = true;
426 }
427 }
428
429 if (firstRearCameraSeen && firstFrontCameraSeen) {
430 break;
431 }
432 }
433}
434
Austin Borgered99f642023-06-01 16:51:35 -0700435void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700436 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100437 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
438 if (res != OK) {
439 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
440 return;
441 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000442 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700443 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
444 if (res != OK) {
445 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
446 return;
447 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000448 std::vector<std::string> physicalCameraIds;
449 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700450 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100451 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700452 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100453 }
454
455 {
456 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700457 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000458 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100459 }
460
Austin Borgered99f642023-06-01 16:51:35 -0700461 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100462 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700463 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800464
Austin Borgered99f642023-06-01 16:51:35 -0700465 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100466 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800467
468 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700469 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100470}
471
Austin Borgered99f642023-06-01 16:51:35 -0700472void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800473 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700474 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100475 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700476 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100477 }
478
479 {
480 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700481 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100482 }
483}
484
Austin Borgered99f642023-06-01 16:51:35 -0700485void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800486 CameraDeviceStatus newHalStatus) {
487 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700488 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700489
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800490 StatusInternal newStatus = mapToInternal(newHalStatus);
491
Austin Borgered99f642023-06-01 16:51:35 -0700492 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800493
494 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700495 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100496 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700497 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498
499 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700500 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100501
Austin Borgered99f642023-06-01 16:51:35 -0700502 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700503 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700504 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700505 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700506 return;
507 }
508
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800509 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800510
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800511 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800512 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700513 return;
514 }
515
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800516 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000517 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
518 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800519
520 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
521 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700522 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800523
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800524 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700525 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800526 // Don't do this in updateStatus to avoid deadlock over mServiceLock
527 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700528
Ruben Brunkcc776712015-02-17 20:18:47 -0800529 // Remove cached shim parameters
530 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700531
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800532 // Remove online as well as offline client from the list of active clients,
533 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700534 clientToDisconnectOnline = removeClientLocked(cameraId);
535 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700536 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800537
Austin Borgered99f642023-06-01 16:51:35 -0700538 disconnectClient(cameraId, clientToDisconnectOnline);
539 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700540
Austin Borgered99f642023-06-01 16:51:35 -0700541 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800542 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800543 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000544 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
545 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700546 }
Austin Borgered99f642023-06-01 16:51:35 -0700547 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700548 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800549}
Igor Murashkincba2c162013-03-20 15:56:31 -0700550
Austin Borgered99f642023-06-01 16:51:35 -0700551void CameraService::onDeviceStatusChanged(const std::string& id,
552 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800553 CameraDeviceStatus newHalStatus) {
554 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700555 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800556
557 StatusInternal newStatus = mapToInternal(newHalStatus);
558
559 std::shared_ptr<CameraState> state = getCameraState(id);
560
561 if (state == nullptr) {
562 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700563 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800564 return;
565 }
566
567 StatusInternal logicalCameraStatus = state->getStatus();
568 if (logicalCameraStatus != StatusInternal::PRESENT &&
569 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
570 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700571 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800572 return;
573 }
574
575 bool updated = false;
576 if (newStatus == StatusInternal::PRESENT) {
577 updated = state->removeUnavailablePhysicalId(physicalId);
578 } else {
579 updated = state->addUnavailablePhysicalId(physicalId);
580 }
581
582 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700583 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800584 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000585 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800586 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000587 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800588 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700589 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
590 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
591 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700592 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700593 return;
594 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800595 Mutex::Autolock lock(mStatusListenerLock);
596 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700597 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
598 listener->getListenerPid(), listener->getListenerUid())) {
599 ALOGV("Skipping discovery callback for system-only camera device %s",
600 id.c_str());
601 continue;
602 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700603 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -0700604 mapToInterface(newStatus), id, physicalId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700605 listener->handleBinderStatus(ret,
606 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
607 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
608 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800609 }
610 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700611}
612
Austin Borgered99f642023-06-01 16:51:35 -0700613void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800614 if (clientToDisconnect.get() != nullptr) {
615 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700616 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800617 // Notify the client of disconnection
618 clientToDisconnect->notifyError(
619 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
620 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800621 clientToDisconnect->disconnect();
622 }
623}
624
Austin Borgered99f642023-06-01 16:51:35 -0700625void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800626 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700627 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
628 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
629 if (res != OK) {
630 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700631 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700632 return;
633 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800634 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700635 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800636}
637
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700638
Austin Borgered99f642023-06-01 16:51:35 -0700639void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700640 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
641 Mutex::Autolock al(mTorchStatusMutex);
642 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
643}
644
Austin Borgered99f642023-06-01 16:51:35 -0700645void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800646 int32_t newStrengthLevel) {
647 Mutex::Autolock lock(mStatusListenerLock);
648 for (auto& i : mListenerList) {
Austin Borgered99f642023-06-01 16:51:35 -0700649 auto ret = i->getListener()->onTorchStrengthLevelChanged(cameraId, newStrengthLevel);
Austin Borgere8e2c422022-05-12 13:45:24 -0700650 i->handleBinderStatus(ret,
651 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
652 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800653 }
654}
655
Austin Borgered99f642023-06-01 16:51:35 -0700656void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700657 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800658 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700659 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800660
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800661 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800662 status_t res = getTorchStatusLocked(cameraId, &status);
663 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700664 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700665 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800666 return;
667 }
668 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800669 return;
670 }
671
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800672 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800673 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800674 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
675 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800676 return;
677 }
678
Ruben Brunkcc776712015-02-17 20:18:47 -0800679 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700680 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700681 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700682 auto iter = mTorchUidMap.find(cameraId);
683 if (iter != mTorchUidMap.end()) {
684 int oldUid = iter->second.second;
685 int newUid = iter->second.first;
686 BatteryNotifier& notifier(BatteryNotifier::getInstance());
687 if (oldUid != newUid) {
688 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800689 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700690 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700691 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800692 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700693 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700694 }
695 iter->second.second = newUid;
696 } else {
697 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800698 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700699 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700700 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700701 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700702 }
703 }
704 }
705 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700706 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800707}
708
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700709static bool isAutomotiveDevice() {
710 // Checks the property ro.hardware.type and returns true if it is
711 // automotive.
712 char value[PROPERTY_VALUE_MAX] = {0};
713 property_get("ro.hardware.type", value, "");
714 return strncmp(value, "automotive", PROPERTY_VALUE_MAX) == 0;
715}
716
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700717static bool isHeadlessSystemUserMode() {
718 // Checks if the device is running in headless system user mode
719 // by checking the property ro.fw.mu.headless_system_user.
720 char value[PROPERTY_VALUE_MAX] = {0};
721 property_get("ro.fw.mu.headless_system_user", value, "");
722 return strncmp(value, "true", PROPERTY_VALUE_MAX) == 0;
723}
724
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700725static bool isAutomotivePrivilegedClient(int32_t uid) {
726 // Returns false if this is not an automotive device type.
727 if (!isAutomotiveDevice())
728 return false;
729
730 // Returns true if the uid is AID_AUTOMOTIVE_EVS which is a
731 // privileged client uid used for safety critical use cases such as
732 // rear view and surround view.
733 return uid == AID_AUTOMOTIVE_EVS;
734}
735
Austin Borger1c1bee02023-06-01 16:51:35 -0700736bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const{
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700737 // Returns false if this is not an automotive device type.
738 if (!isAutomotiveDevice())
739 return false;
740
741 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700742 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700743 return false;
744
745 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
746 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
747 // This isn't a known camera ID, so it's not a system camera.
748 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
749 return false;
750 }
751
752 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
753 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
754 return false;
755 }
756
757 CameraMetadata cameraInfo;
758 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700759 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700760 if (res != OK){
761 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
762 cam_id.c_str());
763 return false;
764 }
765
766 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
767 if (auto_location.count != 1)
768 return false;
769
770 uint8_t location = auto_location.data.u8[0];
771 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
772 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
773 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
774 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
775 return false;
776 }
777
778 return true;
779}
780
Austin Borger1c1bee02023-06-01 16:51:35 -0700781bool CameraService::checkPermission(const std::string& cameraId, const std::string& permission,
782 const AttributionSourceState& attributionSource, const std::string& message,
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700783 int32_t attributedOpCode) const{
784 if (isAutomotivePrivilegedClient(attributionSource.uid)) {
Austin Borger1c1bee02023-06-01 16:51:35 -0700785 // If cameraId is empty, then it means that this check is not used for the
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700786 // purpose of accessing a specific camera, hence grant permission just
787 // based on uid to the automotive privileged client.
Austin Borger1c1bee02023-06-01 16:51:35 -0700788 if (cameraId.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700789 return true;
790 // If this call is used for accessing a specific camera then cam_id must be provided.
791 // In that case, only pre-grants the permission for accessing the exterior system only
792 // camera.
Austin Borger1c1bee02023-06-01 16:51:35 -0700793 return isAutomotiveExteriorSystemCamera(cameraId);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700794 }
795
Joanne Chung02c13d02023-01-16 12:58:05 +0000796 permission::PermissionChecker permissionChecker;
Austin Borger1c1bee02023-06-01 16:51:35 -0700797 return permissionChecker.checkPermissionForPreflight(toString16(permission), attributionSource,
798 toString16(message), attributedOpCode)
799 != permission::PermissionChecker::PERMISSION_HARD_DENIED;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700800}
801
Austin Borger1c1bee02023-06-01 16:51:35 -0700802bool CameraService::hasPermissionsForSystemCamera(const std::string& cameraId, int callingPid,
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700803 int callingUid) const{
Joanne Chung02c13d02023-01-16 12:58:05 +0000804 AttributionSourceState attributionSource{};
805 attributionSource.pid = callingPid;
806 attributionSource.uid = callingUid;
Austin Borger1c1bee02023-06-01 16:51:35 -0700807 bool checkPermissionForSystemCamera = checkPermission(cameraId,
808 sSystemCameraPermission, attributionSource, std::string(), AppOpsManager::OP_NONE);
809 bool checkPermissionForCamera = checkPermission(cameraId,
810 sCameraPermission, attributionSource, std::string(), AppOpsManager::OP_NONE);
Joanne Chung02c13d02023-01-16 12:58:05 +0000811 return checkPermissionForSystemCamera && checkPermissionForCamera;
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700812}
813
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -0700814bool CameraService::hasPermissionsForCameraHeadlessSystemUser(const std::string& cameraId,
815 int callingPid, int callingUid) const{
816 AttributionSourceState attributionSource{};
817 attributionSource.pid = callingPid;
818 attributionSource.uid = callingUid;
819 return checkPermission(cameraId, sCameraHeadlessSystemUserPermission, attributionSource,
820 std::string(), AppOpsManager::OP_NONE);
821}
822
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800823Status CameraService::getNumberOfCameras(int32_t type, int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700824 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +0100825 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700826 bool hasSystemCameraPermissions =
Austin Borger1c1bee02023-06-01 16:51:35 -0700827 hasPermissionsForSystemCamera(std::string(), CameraThreadState::getCallingPid(),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700828 CameraThreadState::getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700829 switch (type) {
830 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700831 if (hasSystemCameraPermissions) {
832 *numCameras = static_cast<int>(mNormalDeviceIds.size());
833 } else {
834 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
835 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700837 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700838 if (hasSystemCameraPermissions) {
839 *numCameras = mNumberOfCameras;
840 } else {
841 *numCameras = mNumberOfCamerasWithoutSystemCamera;
842 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800843 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700844 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800845 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700846 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800847 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
848 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700849 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800850 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700851}
852
malikakash73125c62023-07-21 22:44:34 +0000853Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700854 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
malikakash82ed4352023-07-21 22:44:34 +0000855 const int pid = CameraThreadState::getCallingPid();
856 const int uid = CameraThreadState::getCallingUid();
857 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
858 __FUNCTION__, pid, uid);
859 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
860 "Permission Denial: no permission to configure camera id mapping");
861 }
862 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000863 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000864 if (!parseStatus.isOk()) {
865 return parseStatus;
866 }
867 remapCameraIds(cameraIdRemappingMap);
868 return Status::ok();
869}
870
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700871Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
872 /* out */
873 hardware::camera2::impl::CameraMetadataNative* request) {
874 ATRACE_CALL();
875
876 if (!flags::feature_combination_query()) {
877 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
878 "Camera subsystem doesn't support this method!");
879 }
880 if (!mInitialized) {
881 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
882 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
883 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
884 }
885
886 const std::string cameraId = resolveCameraId(unresolvedCameraId,
887 CameraThreadState::getCallingUid());
888
889 binder::Status res;
890 if (request == nullptr) {
891 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
892 "Camera %s: Error creating default request", cameraId.c_str());
893 return res;
894 }
895 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
896 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
897 cameraId, templateId, &tempId);
898 if (!res.isOk()) {
899 ALOGE("%s: Camera %s: failed to map request Template %d",
900 __FUNCTION__, cameraId.c_str(), templateId);
901 return res;
902 }
903
904 if (shouldRejectSystemCameraConnection(cameraId)) {
905 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
906 "request for system only device %s: ", cameraId.c_str());
907 }
908
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700909 CameraMetadata metadata;
910 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
911 if (err == OK) {
912 request->swap(metadata);
913 } else if (err == BAD_VALUE) {
914 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
915 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
916 cameraId.c_str(), templateId, strerror(-err), err);
917 } else {
918 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
919 "Camera %s: Error creating default request for template %d: %s (%d)",
920 cameraId.c_str(), templateId, strerror(-err), err);
921 }
922 return res;
923}
924
925Status CameraService::isSessionConfigurationWithParametersSupported(
926 const std::string& unresolvedCameraId,
927 const SessionConfiguration& sessionConfiguration,
928 /*out*/
929 bool* supported) {
930 ATRACE_CALL();
931
932 if (!flags::feature_combination_query()) {
933 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
934 "Camera subsystem doesn't support this method!");
935 }
936 if (!mInitialized) {
937 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
938 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
939 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
940 }
941
942 const std::string cameraId = resolveCameraId(unresolvedCameraId,
943 CameraThreadState::getCallingUid());
944 if (supported == nullptr) {
945 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
946 unresolvedCameraId.c_str());
947 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
948 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
949 }
950
951 if (shouldRejectSystemCameraConnection(cameraId)) {
952 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
953 "session configuration with parameters support for system only device %s: ",
954 cameraId.c_str());
955 }
956
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700957 *supported = false;
958 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(cameraId.c_str(),
959 sessionConfiguration, /*mOverrideForPerfClass*/false, /*checkSessionParams*/true,
960 supported);
961 binder::Status res;
962 switch (ret) {
963 case OK:
964 // Expected, do nothing.
965 break;
966 case INVALID_OPERATION: {
967 std::string msg = fmt::sprintf(
968 "Camera %s: Session configuration query not supported!",
969 cameraId.c_str());
970 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
971 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
972 }
973
974 break;
975 default: {
976 std::string msg = fmt::sprintf( "Camera %s: Error: %s (%d)", cameraId.c_str(),
977 strerror(-ret), ret);
978 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
979 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT,
980 msg.c_str());
981 }
982 }
983
984 return res;
985}
986
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800987Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
988 int targetSdkVersion, bool overrideToPortrait,
989 const SessionConfiguration& sessionConfiguration,
990 /*out*/ CameraMetadata* outMetadata) {
991 ATRACE_CALL();
992
993 if (!mInitialized) {
994 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
995 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
996 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
997 }
998
999 const std::string cameraId =
1000 resolveCameraId(unresolvedCameraId, CameraThreadState::getCallingUid());
1001
1002 if (outMetadata == nullptr) {
1003 std::string msg =
1004 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1005 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1006 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1007 }
1008
1009 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1010 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
1011
1012 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1013 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1014
1015 // TODO(b/303645857): Remove fingerprintable metadata if the caller process does not have
1016 // camera access permission.
1017
1018 Status res = Status::ok();
1019 switch (ret) {
1020 case OK:
1021 // Expected, no handling needed.
1022 break;
1023 case INVALID_OPERATION: {
1024 std::string msg = fmt::sprintf(
1025 "Camera %s: Session characteristics query not supported!",
1026 cameraId.c_str());
1027 ALOGD("%s: %s", __FUNCTION__, msg.c_str());
1028 res = STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1029 }
1030 break;
1031 default: {
1032 std::string msg = fmt::sprintf("Camera %s: Error: %s (%d)", cameraId.c_str(),
1033 strerror(-ret), ret);
1034 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1035 res = STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1036 }
1037 }
1038
1039 return res;
1040}
1041
malikakash82ed4352023-07-21 22:44:34 +00001042Status CameraService::parseCameraIdRemapping(
1043 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001044 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001045 std::string packageName;
1046 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +00001047 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001048 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001049 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001050 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1051 "CameraIdRemapping: Package name cannot be empty");
1052 }
malikakash214f6e62023-08-10 23:50:56 +00001053 if (packageIdRemapping.cameraIdsToReplace.size()
1054 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001055 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1056 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001057 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001058 }
malikakash214f6e62023-08-10 23:50:56 +00001059 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001060 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1061 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001062 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001063 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1064 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001065 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001066 }
1067 if (cameraIdToReplace == updatedCameraId) {
1068 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1069 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1070 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001071 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001072 }
1073 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001074 }
1075 }
1076 return Status::ok();
1077}
1078
1079void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1080 // Acquire mServiceLock and prevent other clients from connecting
1081 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1082 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1083
malikakashedb38962023-09-06 00:03:35 +00001084 // Collect all existing clients for camera Ids that are being
1085 // remapped in the new cameraIdRemapping, but only if they were being used by a
1086 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001087 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001088 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001089 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1090 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001091 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001092 id0.c_str(), id1.c_str());
1093 auto clientDescriptor = mActiveClientManager.get(id0);
1094 if (clientDescriptor != nullptr) {
1095 sp<BasicClient> clientSp = clientDescriptor->getValue();
1096 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001097 // This camera is being used by a targeted packageName and
1098 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001099 clientsToDisconnect.push_back(clientSp);
1100 cameraIdsToUpdate.push_back(id0);
1101 }
1102 }
1103 }
1104 }
1105
malikakashedb38962023-09-06 00:03:35 +00001106 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001107 // Notify the clients about the disconnection.
1108 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001109 CaptureResultExtras{});
1110 }
malikakash82ed4352023-07-21 22:44:34 +00001111
1112 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1113 // blocking other clients from connecting in mServiceLockWrapper if held.
1114 mServiceLock.unlock();
1115
malikakashedb38962023-09-06 00:03:35 +00001116 // Clear calling identity for disconnect() PID checks.
1117 int64_t token = CameraThreadState::clearCallingIdentity();
1118
malikakash82ed4352023-07-21 22:44:34 +00001119 // Disconnect clients.
1120 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001121 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1122 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001123 clientSp->disconnect();
1124 }
1125
malikakashedb38962023-09-06 00:03:35 +00001126 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1127 clientsToDisconnect.clear();
1128
1129 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001130 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001131
1132 {
1133 Mutex::Autolock lock(mCameraIdRemappingLock);
1134 // Update mCameraIdRemapping.
1135 mCameraIdRemapping.clear();
1136 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1137 }
malikakash82ed4352023-07-21 22:44:34 +00001138}
1139
malikakash22af94c2023-12-04 18:13:14 +00001140Status CameraService::injectSessionParams(
1141 const std::string& cameraId,
1142 const CameraMetadata& sessionParams) {
1143 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
1144 const int pid = CameraThreadState::getCallingPid();
1145 const int uid = CameraThreadState::getCallingUid();
1146 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1147 __FUNCTION__, pid, uid);
1148 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1149 "Permission Denial: no permission to inject session params");
1150 }
1151
1152 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1153 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1154
1155 auto clientDescriptor = mActiveClientManager.get(cameraId);
1156 if (clientDescriptor == nullptr) {
1157 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1158 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1159 "No active client for camera id %s", cameraId.c_str());
1160 }
1161
1162 sp<BasicClient> clientSp = clientDescriptor->getValue();
1163 status_t res = clientSp->injectSessionParams(sessionParams);
1164
1165 if (res != OK) {
1166 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1167 "Error injecting session params into camera \"%s\": %s (%d)",
1168 cameraId.c_str(), strerror(-res), res);
1169 }
1170 return Status::ok();
1171}
1172
Austin Borgered99f642023-06-01 16:51:35 -07001173std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1174 const std::string& inputCameraId, int clientUid) {
1175 std::string packageName = getPackageNameFromUid(clientUid);
1176 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001177 Mutex::Autolock lock(mCameraIdRemappingLock);
1178 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1179 packageMapIter != mCameraIdRemapping.end()) {
1180 for (auto& [id0, id1]: packageMapIter->second) {
1181 if (id1 == inputCameraId) {
1182 cameraIds.push_back(id0);
1183 }
1184 }
1185 }
1186 return cameraIds;
1187}
1188
Austin Borgered99f642023-06-01 16:51:35 -07001189std::string CameraService::resolveCameraId(
1190 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001191 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001192 const std::string& packageName) {
1193 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001194 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001195 packageNameVal = getPackageNameFromUid(clientUid);
1196 }
malikakash65d20692023-09-07 01:06:33 +00001197 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001198 // We shouldn't remap cameras for processes with system/vendor UIDs.
1199 return inputCameraId;
1200 }
malikakash82ed4352023-07-21 22:44:34 +00001201 Mutex::Autolock lock(mCameraIdRemappingLock);
1202 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1203 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001204 auto packageMap = packageMapIter->second;
1205 if (auto replacementIdIter = packageMap.find(inputCameraId);
1206 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001207 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001208 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001209 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001210 replacementIdIter->second.c_str());
1211 return replacementIdIter->second;
1212 }
1213 }
1214 return inputCameraId;
1215}
1216
Austin Borger18b30a72022-10-27 12:20:29 -07001217Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001218 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001219 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001220 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001221 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
1222 std::string cameraIdStr = resolveCameraId(
1223 unresolvedCameraId, CameraThreadState::getCallingUid());
1224
Austin Borgered99f642023-06-01 16:51:35 -07001225 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001226 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1227 "characteristics for system only device %s: ", cameraIdStr.c_str());
1228 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001229
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001230 if (!mInitialized) {
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");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001234 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001235 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001236 CameraThreadState::getCallingPid(), CameraThreadState::getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001237 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1238 if (hasSystemCameraPermissions) {
1239 cameraIdBound = mNumberOfCameras;
1240 }
1241 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1243 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 }
1245
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001246 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001247 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001248 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001249 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001250 if (err != OK) {
1251 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1252 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1253 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001254 logServiceError(std::string("Error retrieving camera info from device ")
1255 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001256 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001257
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 return ret;
1259}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001260
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001261std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001262 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
1263 auto callingPid = CameraThreadState::getCallingPid();
1264 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00001265 AttributionSourceState attributionSource{};
1266 attributionSource.pid = callingPid;
1267 attributionSource.uid = callingUid;
Austin Borger1c1bee02023-06-01 16:51:35 -07001268 bool checkPermissionForSystemCamera = checkPermission(std::to_string(cameraIdInt),
1269 sSystemCameraPermission, attributionSource, std::string(),
1270 AppOpsManager::OP_NONE);
Joanne Chung02c13d02023-01-16 12:58:05 +00001271 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001272 deviceIds = &mNormalDeviceIds;
1273 }
1274 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001275 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001276 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001277 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001278 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001279
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001280 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001281}
1282
Austin Borgered99f642023-06-01 16:51:35 -07001283std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001284 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001285 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001286}
1287
Austin Borgered99f642023-06-01 16:51:35 -07001288Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001289 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001290 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001291
malikakashedb38962023-09-06 00:03:35 +00001292 const std::string cameraId = resolveCameraId(unresolvedCameraId,
1293 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -07001294
Zhijun He2b59be82013-09-25 10:14:30 -07001295 if (!cameraInfo) {
1296 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001297 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001298 }
1299
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001300 if (!mInitialized) {
1301 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001302 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001303 return STATUS_ERROR(ERROR_DISCONNECTED,
1304 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001305 }
1306
Austin Borgered99f642023-06-01 16:51:35 -07001307 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001308 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001309 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001310 }
1311
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001312 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001313
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001314 bool overrideForPerfClass =
1315 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001316 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001317 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001318 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001319 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001320 if (res == NAME_NOT_FOUND) {
1321 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001322 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001323 strerror(-res), res);
1324 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001325 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1326 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001327 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001328 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001329 strerror(-res), res);
1330 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001331 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001332 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001333 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1334 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001335 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001336 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001337 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001338 int callingPid = CameraThreadState::getCallingPid();
1339 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001340 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001341 // If it's not calling from cameraserver, check the permission only if
1342 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1343 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +00001344 AttributionSourceState attributionSource{};
1345 attributionSource.pid = callingPid;
1346 attributionSource.uid = callingUid;
Austin Borger1c1bee02023-06-01 16:51:35 -07001347 bool checkPermissionForCamera = checkPermission(cameraId, sCameraPermission,
1348 attributionSource, std::string(), AppOpsManager::OP_NONE);
Emilian Peeve20c6372018-08-14 18:45:53 +01001349 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001350 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001351 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001352 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001353 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001354 &tagsRemoved);
1355 if (res != OK) {
1356 cameraInfo->clear();
1357 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1358 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001359 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001360 }
1361 }
1362
1363 if (!tagsRemoved.empty()) {
1364 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1365 tagsRemoved.data(), tagsRemoved.size());
1366 if (res != OK) {
1367 cameraInfo->clear();
1368 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001369 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001370 strerror(-res), res);
1371 }
1372 }
1373
Zhijun He2b59be82013-09-25 10:14:30 -07001374 return ret;
1375}
1376
malikakashedb38962023-09-06 00:03:35 +00001377Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001378 int32_t* torchStrength) {
1379 ATRACE_CALL();
1380 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001381 const std::string cameraId = resolveCameraId(
malikakash65d20692023-09-07 01:06:33 +00001382 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001383 if (!mInitialized) {
1384 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1385 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1386 }
1387
1388 if(torchStrength == NULL) {
1389 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1390 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1391 }
1392
Austin Borgered99f642023-06-01 16:51:35 -07001393 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001394 if (res != OK) {
1395 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001396 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001397 strerror(-res), res);
1398 }
1399 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1400 return Status::ok();
1401}
1402
Austin Borgered99f642023-06-01 16:51:35 -07001403std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001404 time_t now = time(nullptr);
1405 char formattedTime[64];
1406 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001407 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001408}
1409
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001410Status CameraService::getCameraVendorTagDescriptor(
1411 /*out*/
1412 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001413 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001414 if (!mInitialized) {
1415 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001416 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001417 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001418 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1419 if (globalDescriptor != nullptr) {
1420 *desc = *(globalDescriptor.get());
1421 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001422 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001423}
1424
Emilian Peev71c73a22017-03-21 16:35:51 +00001425Status CameraService::getCameraVendorTagCache(
1426 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1427 ATRACE_CALL();
1428 if (!mInitialized) {
1429 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1430 return STATUS_ERROR(ERROR_DISCONNECTED,
1431 "Camera subsystem not available");
1432 }
1433 sp<VendorTagDescriptorCache> globalCache =
1434 VendorTagDescriptorCache::getGlobalVendorTagCache();
1435 if (globalCache != nullptr) {
1436 *cache = *(globalCache.get());
1437 }
1438 return Status::ok();
1439}
1440
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001441void CameraService::clearCachedVariables() {
1442 BasicClient::BasicClient::sCameraService = nullptr;
1443}
1444
Austin Borgered99f642023-06-01 16:51:35 -07001445std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001446 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001447 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001448
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001449 int deviceVersion = 0;
1450
Emilian Peevf53f66e2017-04-11 14:29:43 +01001451 status_t res;
1452 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001453 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001454 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001455 if (res != OK || transport == IPCTransport::INVALID) {
1456 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001457 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001458 return std::make_pair(-1, IPCTransport::INVALID) ;
1459 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001460 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001461
Emilian Peevf53f66e2017-04-11 14:29:43 +01001462 hardware::CameraInfo info;
1463 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001464 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001465 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001466 if (res != OK) {
1467 return std::make_pair(-1, IPCTransport::INVALID);
1468 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001469 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001470 if (orientation) {
1471 *orientation = info.orientation;
1472 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001473 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001474
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001475 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001476}
1477
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001478Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001479 switch(err) {
1480 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001481 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001482 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001483 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1484 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001485 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001486 return STATUS_ERROR(ERROR_DISCONNECTED,
1487 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001488 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001489 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1490 "Camera HAL encountered error %d: %s",
1491 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001492 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001493}
1494
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001495Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001496 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1497 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001498 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001499 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001500 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001501 bool forceSlowJpegMode, const std::string& originalCameraId,
1502 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001503 // For HIDL devices
1504 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1505 // Create CameraClient based on device version reported by the HAL.
1506 int deviceVersion = deviceVersionAndTransport.first;
1507 switch(deviceVersion) {
1508 case CAMERA_DEVICE_API_VERSION_1_0:
1509 ALOGE("Camera using old HAL version: %d", deviceVersion);
1510 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1511 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001512 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001513 break;
1514 case CAMERA_DEVICE_API_VERSION_3_0:
1515 case CAMERA_DEVICE_API_VERSION_3_1:
1516 case CAMERA_DEVICE_API_VERSION_3_2:
1517 case CAMERA_DEVICE_API_VERSION_3_3:
1518 case CAMERA_DEVICE_API_VERSION_3_4:
1519 case CAMERA_DEVICE_API_VERSION_3_5:
1520 case CAMERA_DEVICE_API_VERSION_3_6:
1521 case CAMERA_DEVICE_API_VERSION_3_7:
1522 break;
1523 default:
1524 // Should not be reachable
1525 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1526 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1527 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001528 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001529 }
1530 }
1531 if (effectiveApiLevel == API_1) { // Camera1 API route
1532 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001533 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borgered99f642023-06-01 16:51:35 -07001534 packageName, featureId, cameraId,
1535 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001536 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1537 forceSlowJpegMode);
1538 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1539 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001540 } else { // Camera2 API route
1541 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1542 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001543 *client = new CameraDeviceClient(cameraService, tmp,
1544 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1545 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001546 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001547 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001548 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001549 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001550}
1551
Austin Borgered99f642023-06-01 16:51:35 -07001552std::string CameraService::toString(std::set<userid_t> intSet) {
1553 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001554 bool first = true;
1555 for (userid_t i : intSet) {
1556 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001557 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001558 first = false;
1559 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001560 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001561 }
1562 }
Austin Borgered99f642023-06-01 16:51:35 -07001563 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001564}
1565
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001566int32_t CameraService::mapToInterface(TorchModeStatus status) {
1567 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1568 switch (status) {
1569 case TorchModeStatus::NOT_AVAILABLE:
1570 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1571 break;
1572 case TorchModeStatus::AVAILABLE_OFF:
1573 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1574 break;
1575 case TorchModeStatus::AVAILABLE_ON:
1576 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1577 break;
1578 default:
1579 ALOGW("Unknown new flash status: %d", status);
1580 }
1581 return serviceStatus;
1582}
1583
1584CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1585 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1586 switch (status) {
1587 case CameraDeviceStatus::NOT_PRESENT:
1588 serviceStatus = StatusInternal::NOT_PRESENT;
1589 break;
1590 case CameraDeviceStatus::PRESENT:
1591 serviceStatus = StatusInternal::PRESENT;
1592 break;
1593 case CameraDeviceStatus::ENUMERATING:
1594 serviceStatus = StatusInternal::ENUMERATING;
1595 break;
1596 default:
1597 ALOGW("Unknown new HAL device status: %d", status);
1598 }
1599 return serviceStatus;
1600}
1601
1602int32_t CameraService::mapToInterface(StatusInternal status) {
1603 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1604 switch (status) {
1605 case StatusInternal::NOT_PRESENT:
1606 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1607 break;
1608 case StatusInternal::PRESENT:
1609 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1610 break;
1611 case StatusInternal::ENUMERATING:
1612 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1613 break;
1614 case StatusInternal::NOT_AVAILABLE:
1615 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1616 break;
1617 case StatusInternal::UNKNOWN:
1618 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1619 break;
1620 default:
1621 ALOGW("Unknown new internal device status: %d", status);
1622 }
1623 return serviceStatus;
1624}
1625
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001627 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001628
Austin Borgered99f642023-06-01 16:51:35 -07001629 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001630 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001631 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001633 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1634 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001635 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001636 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001637 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001638 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001639 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001640 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001641 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001642}
1643
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001645 /*out*/
1646 CameraParameters* parameters) {
1647
1648 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651
1652 if (parameters == NULL) {
1653 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001655 }
1656
malikakashedb38962023-09-06 00:03:35 +00001657 std::string unresolvedCameraId = std::to_string(cameraId);
1658 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1659 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001660
1661 // Check if we already have parameters
1662 {
1663 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001664 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001665 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001666 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001667 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001668 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001669 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001670 }
1671 CameraParameters p = cameraState->getShimParams();
1672 if (!p.isEmpty()) {
1673 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001674 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001675 }
1676 }
1677
Jayant Chowdhary12361932018-08-27 14:46:13 -07001678 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001679 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001680 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001681 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001682 // Error already logged by callee
1683 return ret;
1684 }
1685
1686 // Check for parameters again
1687 {
1688 // Scope for service lock
1689 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001690 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001691 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001692 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001693 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001694 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001695 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001696 CameraParameters p = cameraState->getShimParams();
1697 if (!p.isEmpty()) {
1698 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001699 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001700 }
1701 }
1702
Ruben Brunkcc776712015-02-17 20:18:47 -08001703 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1704 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001705 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001706}
1707
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001708// Can camera service trust the caller based on the calling UID?
1709static bool isTrustedCallingUid(uid_t uid) {
1710 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001711 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001712 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001713 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001714 return true;
1715 default:
1716 return false;
1717 }
1718}
1719
Austin Borgered99f642023-06-01 16:51:35 -07001720static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
1721 int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07001722 PermissionController pc;
Austin Borgered99f642023-06-01 16:51:35 -07001723 uid = pc.getPackageUid(toString16(packageName), 0);
Nicholas Sauera3620332019-04-03 14:05:17 -07001724 if (uid <= 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001725 ALOGE("Unknown package: '%s'", packageName.c_str());
1726 dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07001727 return BAD_VALUE;
1728 }
1729
1730 if (userId < 0) {
1731 ALOGE("Invalid user: %d", userId);
1732 dprintf(err, "Invalid user: %d\n", userId);
1733 return BAD_VALUE;
1734 }
1735
1736 uid = multiuser_get_uid(userId, uid);
1737 return NO_ERROR;
1738}
1739
Austin Borgered99f642023-06-01 16:51:35 -07001740Status CameraService::validateConnectLocked(const std::string& cameraId,
1741 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001742 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001743
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001744#ifdef __BRILLO__
1745 UNUSED(clientName8);
1746 UNUSED(clientUid);
1747 UNUSED(clientPid);
1748 UNUSED(originalClientPid);
1749#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001750 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1751 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001752 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001753 return allowed;
1754 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001755#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001756
Jayant Chowdhary12361932018-08-27 14:46:13 -07001757 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001758
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001759 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001760 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1761 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001762 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001763 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001764 }
1765
Ruben Brunkcc776712015-02-17 20:18:47 -08001766 if (getCameraState(cameraId) == nullptr) {
1767 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001768 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001769 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001770 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001771 }
1772
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001773 status_t err = checkIfDeviceIsUsable(cameraId);
1774 if (err != NO_ERROR) {
1775 switch(err) {
1776 case -ENODEV:
1777 case -EBUSY:
1778 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001779 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001780 default:
1781 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001782 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001783 }
1784 }
1785 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001786}
1787
Austin Borgered99f642023-06-01 16:51:35 -07001788Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1789 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001790 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001791 AttributionSourceState attributionSource{};
1792
Jayant Chowdhary12361932018-08-27 14:46:13 -07001793 int callingPid = CameraThreadState::getCallingPid();
1794 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001795
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001796 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001797 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001798 clientUid = callingUid;
1799 } else if (!isTrustedCallingUid(callingUid)) {
1800 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1801 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001802 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1803 "Untrusted caller (calling PID %d, UID %d) trying to "
1804 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001805 callingPid, callingUid, cameraId.c_str(),
1806 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001807 }
1808
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001809 // Check if we can trust clientPid
1810 if (clientPid == USE_CALLING_PID) {
1811 clientPid = callingPid;
1812 } else if (!isTrustedCallingUid(callingUid)) {
1813 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1814 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001815 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1816 "Untrusted caller (calling PID %d, UID %d) trying to "
1817 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001818 callingPid, callingUid, cameraId.c_str(),
1819 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001820 }
1821
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001822 if (shouldRejectSystemCameraConnection(cameraId)) {
1823 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1824 cameraId.c_str());
1825 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001826 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001827 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001828 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1829 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001830 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001831 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001832 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001833
1834 }
1835
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001836 // If it's not calling from cameraserver, check the permission if the
1837 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1838 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001839 attributionSource.pid = clientPid;
1840 attributionSource.uid = clientUid;
Austin Borgered99f642023-06-01 16:51:35 -07001841 attributionSource.packageName = clientName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001842 bool checkPermissionForCamera = checkPermission(cameraId, sCameraPermission, attributionSource,
Austin Borger1c1bee02023-06-01 16:51:35 -07001843 std::string(), AppOpsManager::OP_NONE);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001844 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001845 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001846 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001847 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1848 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001849 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001850 }
1851
Svet Ganova453d0d2018-01-11 15:37:58 -08001852 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001853 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001854 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001855 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1856 clientPid, clientUid);
1857 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001858 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1859 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001860 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001861 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001862 }
1863
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001864 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1865 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1866 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1867 if ((!isAutomotivePrivilegedClient(callingUid) ||
1868 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1869 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001870 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1871 return STATUS_ERROR_FMT(ERROR_DISABLED,
1872 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001873 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001874 }
1875
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001876 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1877 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001878 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001879 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001880
Ruben Brunk6267b532015-04-30 17:44:07 -07001881 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001882
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001883 // For non-system clients : Only allow clients who are being used by the current foreground
1884 // device user, unless calling from our own process.
1885 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001886 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001887 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1888 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001889 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001890 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1891 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001892 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001893 }
1894
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001895 if (flags::camera_hsum_permission()) {
1896 // If the System User tries to access the camera when the device is running in
1897 // headless system user mode, ensure that client has the required permission
1898 // CAMERA_HEADLESS_SYSTEM_USER.
1899 if (isHeadlessSystemUserMode() && (clientUserId == USER_SYSTEM) &&
1900 !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
1901 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1902 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1903 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1904 User without camera headless system user permission",
1905 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
1906 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001907 }
1908
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001909 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001910}
1911
Austin Borgered99f642023-06-01 16:51:35 -07001912status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001913 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001914 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001915 if (cameraState == nullptr) {
1916 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001917 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001918 return -ENODEV;
1919 }
1920
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001921 StatusInternal currentStatus = cameraState->getStatus();
1922 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001923 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001924 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001925 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001926 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001927 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001928 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001929 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001930 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001931
Ruben Brunkcc776712015-02-17 20:18:47 -08001932 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001933}
1934
Ruben Brunkcc776712015-02-17 20:18:47 -08001935void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001936 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001937
Ruben Brunkcc776712015-02-17 20:18:47 -08001938 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001939 auto clientDescriptor =
1940 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001941 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001942 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1943
1944 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001945 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001946
1947 if (evicted.size() > 0) {
1948 // This should never happen - clients should already have been removed in disconnect
1949 for (auto& i : evicted) {
1950 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001951 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001952 }
1953
1954 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1955 __FUNCTION__);
1956 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001957
1958 // And register a death notification for the client callback. Do
1959 // this last to avoid Binder policy where a nested Binder
1960 // transaction might be pre-empted to service the client death
1961 // notification if the client process dies before linkToDeath is
1962 // invoked.
1963 sp<IBinder> remoteCallback = client->getRemote();
1964 if (remoteCallback != nullptr) {
1965 remoteCallback->linkToDeath(this);
1966 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001967}
1968
Austin Borgered99f642023-06-01 16:51:35 -07001969status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1970 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1971 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001972 /*out*/
1973 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001974 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001975 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001976 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001977 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001978 DescriptorPtr clientDescriptor;
1979 {
1980 if (effectiveApiLevel == API_1) {
1981 // If we are using API1, any existing client for this camera ID with the same remote
1982 // should be returned rather than evicted to allow MediaRecorder to work properly.
1983
1984 auto current = mActiveClientManager.get(cameraId);
1985 if (current != nullptr) {
1986 auto clientSp = current->getValue();
1987 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001988 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001989 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001990 " API level, evicting prior client...");
1991 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001992 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001993 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001994 *client = clientSp;
1995 return NO_ERROR;
1996 }
1997 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001998 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001999 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002000
Ruben Brunkcc776712015-02-17 20:18:47 -08002001 // Get state for the given cameraId
2002 auto state = getCameraState(cameraId);
2003 if (state == nullptr) {
2004 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002005 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002006 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002007 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002008 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002009
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002010 sp<IServiceManager> sm = defaultServiceManager();
2011 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
2012 if (!binder && isAutomotivePrivilegedClient(CameraThreadState::getCallingUid())) {
2013 // If processinfo service is not available and the client is automotive privileged
2014 // client used for safety critical uses cases such as rear-view and surround-view which
2015 // needs to be available before android boot completes, then use the hardcoded values
2016 // for the process state and priority score. As this scenario is before android system
2017 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2018 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2019 // visible on the top.
2020 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2021 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2022 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2023 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2024 } else {
2025 // Get current active client PIDs
2026 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2027 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002028
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002029 std::vector<int> priorityScores(ownerPids.size());
2030 std::vector<int> states(ownerPids.size());
2031
2032 // Get priority scores of all active PIDs
2033 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2034 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2035 if (err != OK) {
2036 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2037 return err;
2038 }
2039
2040 // Update all active clients' priorities
2041 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2042 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2043 pidToPriorityMap.emplace(ownerPids[i],
2044 resource_policy::ClientPriority(priorityScores[i], states[i],
2045 /* isVendorClient won't get copied over*/ false,
2046 /* oomScoreOffset won't get copied over*/ 0));
2047 }
2048 mActiveClientManager.updatePriorities(pidToPriorityMap);
2049
2050 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2051 int32_t actualState = states[states.size() - 1];
2052
2053 // Make descriptor for incoming client. We store the oomScoreOffset
2054 // since we might need it later on new handleEvictionsLocked and
2055 // ProcessInfoService would not take that into account.
2056 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2057 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2058 state->getConflicting(), actualScore, clientPid, actualState,
2059 oomScoreOffset, systemNativeClient);
2060 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002061
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002062 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2063
Ruben Brunkcc776712015-02-17 20:18:47 -08002064 // Find clients that would be evicted
2065 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2066
2067 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2068 // background, so we cannot do evictions
2069 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2070 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2071 " priority).", clientPid);
2072
2073 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002074 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002075 auto incompatibleClients =
2076 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2077
Austin Borgered99f642023-06-01 16:51:35 -07002078 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2079 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2080 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002081 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002082
2083 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002084 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002085 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002086 i->getKey().c_str(),
2087 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002088 i->getOwnerId(), i->getPriority().getScore(),
2089 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002090 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002091 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2092 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002093 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002094 }
2095
2096 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002097 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002098 mEventLog.add(msg);
2099
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002100 auto current = mActiveClientManager.get(cameraId);
2101 if (current != nullptr) {
2102 return -EBUSY; // CAMERA_IN_USE
2103 } else {
2104 return -EUSERS; // MAX_CAMERAS_IN_USE
2105 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 }
2107
2108 for (auto& i : evicted) {
2109 sp<BasicClient> clientSp = i->getValue();
2110 if (clientSp.get() == nullptr) {
2111 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2112
2113 // TODO: Remove this
2114 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2115 __FUNCTION__);
2116 mActiveClientManager.remove(i);
2117 continue;
2118 }
2119
2120 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002121 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002122 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002123
Ruben Brunkcc776712015-02-17 20:18:47 -08002124 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002125 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002126 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2127 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002128 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002129 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002130 i->getPriority().getState(), cameraId.c_str(),
2131 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002132 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002133
2134 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002135 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002136 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002137 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002138 }
2139
Ruben Brunkcc776712015-02-17 20:18:47 -08002140 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2141 // other clients from connecting in mServiceLockWrapper if held
2142 mServiceLock.unlock();
2143
2144 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002145 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002146
2147 // Destroy evicted clients
2148 for (auto& i : evictedClients) {
2149 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002150 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002151 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002152
Jayant Chowdhary12361932018-08-27 14:46:13 -07002153 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002154
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002155 for (const auto& i : evictedClients) {
2156 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002157 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002158 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2159 if (ret == TIMED_OUT) {
2160 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002161 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2162 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002163 return -EBUSY;
2164 }
2165 if (ret != NO_ERROR) {
2166 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002167 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2168 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002169 return ret;
2170 }
2171 }
2172
2173 evictedClients.clear();
2174
Ruben Brunkcc776712015-02-17 20:18:47 -08002175 // Once clients have been disconnected, relock
2176 mServiceLock.lock();
2177
2178 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2179 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2180 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002181 }
2182
Ruben Brunkcc776712015-02-17 20:18:47 -08002183 *partial = clientDescriptor;
2184 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002185}
2186
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002187Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002188 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002189 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002190 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002191 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002192 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002193 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002194 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002195 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002196 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002197 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002198
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002199 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002200 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002201
malikakashedb38962023-09-06 00:03:35 +00002202 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
2203 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
2204 CameraThreadState::getCallingUid());
2205
Ruben Brunkcc776712015-02-17 20:18:47 -08002206 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002207 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2208 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002209 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002210 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002211
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002212 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002213 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
2214 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002215 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002216 }
2217
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002218 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002219
2220 const sp<IServiceManager> sm(defaultServiceManager());
2221 const auto& mActivityManager = getActivityManager();
2222 if (mActivityManager) {
2223 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2224 CameraThreadState::getCallingUid(),
2225 CameraThreadState::getCallingPid());
2226 }
2227
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002228 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002229}
2230
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002231bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2232 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002233 // If the client is not a vendor client, don't add listener if
2234 // a) the camera is a publicly hidden secure camera OR
2235 // b) the camera is a system only camera and the client doesn't
2236 // have android.permission.SYSTEM_CAMERA permissions.
2237 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2238 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002239 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002240 return true;
2241 }
2242 return false;
2243}
2244
Austin Borgered99f642023-06-01 16:51:35 -07002245bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002246 // Rules for rejection:
2247 // 1) If cameraserver tries to access this camera device, accept the
2248 // connection.
2249 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002250 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002251 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2252 // and the serving thread is a non hwbinder thread, the client must have
2253 // android.permission.SYSTEM_CAMERA permissions to connect.
2254
2255 int cPid = CameraThreadState::getCallingPid();
2256 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002257 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002258 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2259 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002260 // This isn't a known camera ID, so it's not a system camera
2261 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2262 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002263 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002264
2265 // (1) Cameraserver trying to connect, accept.
2266 if (CameraThreadState::getCallingPid() == getpid()) {
2267 return false;
2268 }
2269 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002270 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002271 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2272 return true;
2273 }
2274 // (3) Here we only check for permissions if it is a system only camera device. This is since
2275 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2276 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2277 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002278 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002279 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002280 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2281 cameraId.c_str());
2282 return true;
2283 }
2284
2285 return false;
2286}
2287
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002288Status CameraService::connectDevice(
2289 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002290 const std::string& unresolvedCameraId,
2291 const std::string& clientPackageName,
2292 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002293 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002294 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08002295 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002296 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002297
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002298 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002299 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002300 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002301 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002302 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002303 bool systemNativeClient = false;
2304 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
2305 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07002306 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
2307 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002308 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002309 }
malikakashedb38962023-09-06 00:03:35 +00002310 const std::string cameraId = resolveCameraId(
2311 unresolvedCameraId,
2312 CameraThreadState::getCallingUid(),
2313 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002314
2315 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002316 std::string msg =
2317 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2318 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2319 cameraId.c_str());
2320 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2321 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002322 }
2323
Austin Borger9bfa0a72022-08-03 17:50:40 -07002324 userid_t clientUserId = multiuser_get_user_id(clientUid);
2325 int callingUid = CameraThreadState::getCallingUid();
2326 if (clientUid == USE_CALLING_UID) {
2327 clientUserId = multiuser_get_user_id(callingUid);
2328 }
2329
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002330 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2331 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002332 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2333 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002334 std::string msg = "Camera disabled by device policy";
2335 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2336 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002337 }
2338
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002339 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002340 if (oomScoreOffset > 0
2341 && !hasPermissionsForSystemCamera(cameraId, callingPid,
2342 CameraThreadState::getCallingUid())
2343 && !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07002344 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002345 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002346 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2347 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2348 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002349 }
2350
Austin Borgered99f642023-06-01 16:51:35 -07002351 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2352 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002353 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002354 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002355 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002356
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002358 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002359 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002360 }
2361
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002362 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002363 Mutex::Autolock lock(mServiceLock);
2364
2365 // Clear the previous cached logs and reposition the
2366 // file offset to beginning of the file to log new data.
2367 // If either truncate or lseek fails, close the previous file and create a new one.
2368 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2369 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2370 // Close the previous memfd.
2371 close(mMemFd);
2372 // If failure to wipe the data, then create a new file and
2373 // assign the new value to mMemFd.
2374 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2375 if (mMemFd == -1) {
2376 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2377 }
2378 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002379 const sp<IServiceManager> sm(defaultServiceManager());
2380 const auto& mActivityManager = getActivityManager();
2381 if (mActivityManager) {
2382 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2383 CameraThreadState::getCallingUid(),
2384 CameraThreadState::getCallingPid());
2385 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002386 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002387}
2388
Austin Borgered99f642023-06-01 16:51:35 -07002389std::string CameraService::getPackageNameFromUid(int clientUid) {
2390 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002391
2392 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002393 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002394 if (binder == 0) {
2395 ALOGE("Cannot get permission service");
2396 // Return empty package name and the further interaction
2397 // with camera will likely fail
2398 return packageName;
2399 }
2400
2401 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2402 Vector<String16> packages;
2403
2404 permCtrl->getPackagesForUid(clientUid, packages);
2405
2406 if (packages.isEmpty()) {
2407 ALOGE("No packages for calling UID %d", clientUid);
2408 // Return empty package name and the further interaction
2409 // with camera will likely fail
2410 return packageName;
2411 }
2412
2413 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002414 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002415
2416 return packageName;
2417}
2418
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002419template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002420Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2421 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2422 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002423 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002424 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002425 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002426 binder::Status ret = binder::Status::ok();
2427
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002428 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002429 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002430 int packageUid = (clientUid == USE_CALLING_UID) ?
2431 CameraThreadState::getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002432 if (clientPackageNameMaybe.size() <= 0) {
2433 // NDK calls don't come with package names, but we need one for various cases.
2434 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2435 // do exist. For all authentication cases, all packages under the same UID get the
2436 // same permissions, so picking any associated package name is sufficient. For some
2437 // other cases, this may give inaccurate names for clients in logs.
2438 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002439 clientPackageName = getPackageNameFromUid(packageUid);
2440 } else {
2441 clientPackageName = clientPackageNameMaybe;
2442 }
2443
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002444 int originalClientPid = 0;
2445
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002446 int packagePid = (clientPid == USE_CALLING_PID) ?
2447 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002448 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002449 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002450 static_cast<int>(effectiveApiLevel));
2451
Shuzhen Wang316781a2020-08-18 18:11:01 -07002452 nsecs_t openTimeNs = systemTime();
2453
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002454 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002455 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002456 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002457
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002458 {
2459 // Acquire mServiceLock and prevent other clients from connecting
2460 std::unique_ptr<AutoConditionLock> lock =
2461 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2462
2463 if (lock == nullptr) {
2464 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2465 , clientPid);
2466 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2467 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002468 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002469 }
2470
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002471 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002472 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002473 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2474 return ret;
2475 }
2476
2477 // Check the shim parameters after acquiring lock, if they have already been updated and
2478 // we were doing a shim update, return immediately
2479 if (shimUpdateOnly) {
2480 auto cameraState = getCameraState(cameraId);
2481 if (cameraState != nullptr) {
2482 if (!cameraState->getShimParams().isEmpty()) return ret;
2483 }
2484 }
2485
2486 status_t err;
2487
2488 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002489 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002490 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002491 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2492 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002493 switch (err) {
2494 case -ENODEV:
2495 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2496 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002497 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002498 case -EBUSY:
2499 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2500 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002501 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002502 case -EUSERS:
2503 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2504 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002505 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002506 default:
2507 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2508 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002509 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002510 }
2511 }
2512
2513 if (clientTmp.get() != nullptr) {
2514 // Handle special case for API1 MediaRecorder where the existing client is returned
2515 device = static_cast<CLIENT*>(clientTmp.get());
2516 return ret;
2517 }
2518
2519 // give flashlight a chance to close devices if necessary.
2520 mFlashlight->prepareDeviceOpen(cameraId);
2521
Austin Borger18b30a72022-10-27 12:20:29 -07002522 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002523 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002524 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2525 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002526 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002527 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002528 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002529 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002530 }
2531
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002532 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002533 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002534 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002535 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002536 clientFeatureId, cameraId, api1CameraId, facing,
2537 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002538 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002539 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002540 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002541 return ret;
2542 }
2543 client = static_cast<CLIENT*>(tmp.get());
2544
2545 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2546 __FUNCTION__);
2547
Austin Borgered99f642023-06-01 16:51:35 -07002548 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002549 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002550 if (err != OK) {
2551 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002552 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002553 mServiceLock.unlock();
2554 client->disconnect();
2555 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002556 switch(err) {
2557 case BAD_VALUE:
2558 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002559 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002560 case -EBUSY:
2561 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002562 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002563 case -EUSERS:
2564 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2565 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002566 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002567 case PERMISSION_DENIED:
2568 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002569 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002570 case -EACCES:
2571 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002572 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002573 case -ENODEV:
2574 default:
2575 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002576 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002577 strerror(-err), err);
2578 }
2579 }
2580
2581 // Update shim paremeters for legacy clients
2582 if (effectiveApiLevel == API_1) {
2583 // Assume we have always received a Client subclass for API1
2584 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2585 String8 rawParams = shimClient->getParameters();
2586 CameraParameters params(rawParams);
2587
2588 auto cameraState = getCameraState(cameraId);
2589 if (cameraState != nullptr) {
2590 cameraState->setShimParams(params);
2591 } else {
2592 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002593 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002594 }
2595 }
2596
Ravneetaeb20dc2022-03-30 05:33:03 +00002597 // Enable/disable camera service watchdog
2598 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2599
Emilian Peev6d45db82024-01-18 20:11:54 +00002600 CameraMetadata chars;
2601 bool rotateAndCropSupported = true;
2602 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2603 &chars, overrideToPortrait);
2604 if (err == OK) {
2605 auto availableRotateCropEntry = chars.find(
2606 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2607 if (availableRotateCropEntry.count <= 1) {
2608 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002609 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002610 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002611 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2612 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002613 }
2614
Emilian Peev6d45db82024-01-18 20:11:54 +00002615 if (rotateAndCropSupported) {
2616 // Set rotate-and-crop override behavior
2617 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2618 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2619 } else if (overrideToPortrait && portraitRotation != 0) {
2620 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2621 switch (portraitRotation) {
2622 case 90:
2623 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2624 break;
2625 case 180:
2626 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2627 break;
2628 case 270:
2629 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2630 break;
2631 default:
2632 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2633 break;
2634 }
2635 client->setRotateAndCropOverride(rotateAndCropMode);
2636 } else {
2637 client->setRotateAndCropOverride(
2638 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2639 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2640 }
2641 }
2642
2643 bool autoframingSupported = true;
2644 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2645 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2646 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2647 autoframingSupported = false;
2648 }
2649
2650 if (autoframingSupported) {
2651 // Set autoframing override behaviour
2652 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2653 client->setAutoframingOverride(mOverrideAutoframingMode);
2654 } else {
2655 client->setAutoframingOverride(
2656 mCameraServiceProxyWrapper->getAutoframingOverride(
2657 clientPackageName));
2658 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002659 }
2660
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002661 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use
2662 // cases such as rear view and surround view cannot be disabled and are exempt from camera
2663 // privacy policy.
2664 if ((!isAutomotivePrivilegedClient(packageUid) ||
2665 !isAutomotiveExteriorSystemCamera(cameraId))) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002666 // Set camera muting behavior.
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002667 bool isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002668 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002669 if (client->supportsCameraMute()) {
2670 client->setCameraMute(
2671 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2672 } else if (isCameraPrivacyEnabled) {
2673 // no camera mute supported, but privacy is on! => disconnect
2674 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2675 client->getPackageName().c_str(), cameraId.c_str());
2676 // Do not hold mServiceLock while disconnecting clients, but
2677 // retain the condition blocking other clients from connecting
2678 // in mServiceLockWrapper if held.
2679 mServiceLock.unlock();
2680 // Clear caller identity temporarily so client disconnect PID
2681 // checks work correctly
2682 int64_t token = CameraThreadState::clearCallingIdentity();
2683 // Note AppOp to trigger the "Unblock" dialog
2684 client->noteAppOp();
2685 client->disconnect();
2686 CameraThreadState::restoreCallingIdentity(token);
2687 // Reacquire mServiceLock
2688 mServiceLock.lock();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002689
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002690 return STATUS_ERROR_FMT(ERROR_DISABLED,
2691 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
2692 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002693 }
2694
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002695 if (shimUpdateOnly) {
2696 // If only updating legacy shim parameters, immediately disconnect client
2697 mServiceLock.unlock();
2698 client->disconnect();
2699 mServiceLock.lock();
2700 } else {
2701 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002702 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002703 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002704
2705 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002706 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002707 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002708 } // lock is destroyed, allow further connect calls
2709
2710 // Important: release the mutex here so the client can call back into the service from its
2711 // destructor (can be at the end of the call)
2712 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002713
2714 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002715 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002716 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002717
Cliff Wud3a05312021-04-26 23:07:31 +08002718 {
2719 Mutex::Autolock lock(mInjectionParametersLock);
2720 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2721 mInjectionInitPending = false;
2722 status_t res = NO_ERROR;
2723 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2724 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002725 sp<BasicClient> clientSp = clientDescriptor->getValue();
2726 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2727 if(res != OK) {
2728 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2729 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002730 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002731 }
2732 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002733 if (res != OK) {
2734 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2735 }
2736 } else {
2737 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002738 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002739 res = NO_INIT;
2740 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2741 }
2742 }
2743 }
2744
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002745 return ret;
2746}
2747
Austin Borgered99f642023-06-01 16:51:35 -07002748status_t CameraService::addOfflineClient(const std::string &cameraId,
2749 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002750 if (offlineClient.get() == nullptr) {
2751 return BAD_VALUE;
2752 }
2753
2754 {
2755 // Acquire mServiceLock and prevent other clients from connecting
2756 std::unique_ptr<AutoConditionLock> lock =
2757 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2758
2759 if (lock == nullptr) {
2760 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2761 , __FUNCTION__, offlineClient->getClientPid());
2762 return TIMED_OUT;
2763 }
2764
2765 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2766 if (onlineClientDesc.get() == nullptr) {
2767 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2768 cameraId.c_str());
2769 return BAD_VALUE;
2770 }
2771
2772 // Offline clients do not evict or conflict with other online devices. Resource sharing
2773 // conflicts are handled by the camera provider which will either succeed or fail before
2774 // reaching this method.
2775 const auto& onlinePriority = onlineClientDesc->getPriority();
2776 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2777 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002778 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002779 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002780 // native clients don't have offline processing support.
2781 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002782 if (offlineClientDesc == nullptr) {
2783 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2784 return BAD_VALUE;
2785 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002786
2787 // Allow only one offline device per camera
2788 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2789 if (!incompatibleClients.empty()) {
2790 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2791 return BAD_VALUE;
2792 }
2793
Austin Borgered99f642023-06-01 16:51:35 -07002794 std::string monitorTags = isClientWatched(offlineClient.get())
2795 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002796 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002797 if (err != OK) {
2798 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2799 return err;
2800 }
2801
2802 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2803 if (evicted.size() > 0) {
2804 for (auto& i : evicted) {
2805 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002806 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002807 }
2808
2809 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2810 "properly", __FUNCTION__);
2811
2812 return BAD_VALUE;
2813 }
2814
2815 logConnectedOffline(offlineClientDesc->getKey(),
2816 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002817 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002818
2819 sp<IBinder> remoteCallback = offlineClient->getRemote();
2820 if (remoteCallback != nullptr) {
2821 remoteCallback->linkToDeath(this);
2822 }
2823 } // lock is destroyed, allow further connect calls
2824
2825 return OK;
2826}
2827
Austin Borgered99f642023-06-01 16:51:35 -07002828Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger1c1bee02023-06-01 16:51:35 -07002829 int32_t torchStrength, const sp<IBinder>& clientBinder) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002830 Mutex::Autolock lock(mServiceLock);
2831
2832 ATRACE_CALL();
2833 if (clientBinder == nullptr) {
2834 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2835 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2836 "Torch client binder in null.");
2837 }
2838
Rucha Katakwar38284522021-11-10 11:25:21 -08002839 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002840 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002841 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002842 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002843 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002844 }
2845
2846 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002847 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002848 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002849 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002850 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002851 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002852 }
2853
2854 StatusInternal cameraStatus = state->getStatus();
2855 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2856 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002857 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002858 (int)cameraStatus);
2859 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002860 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002861 }
2862
2863 {
2864 Mutex::Autolock al(mTorchStatusMutex);
2865 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002866 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002867 if (err != OK) {
2868 if (err == NAME_NOT_FOUND) {
2869 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002870 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002871 }
2872 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002873 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002874 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2875 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002876 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 }
2878
2879 if (status == TorchModeStatus::NOT_AVAILABLE) {
2880 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2881 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002882 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002883 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2884 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002885 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002886 } else {
2887 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002888 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002889 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2890 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002891 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002892 }
2893 }
2894 }
2895
2896 {
2897 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002898 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002899 }
2900 // Check if the current torch strength level is same as the new one.
2901 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002902 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002903
Austin Borgered99f642023-06-01 16:51:35 -07002904 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002905
2906 if (err != OK) {
2907 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002908 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002909 switch (err) {
2910 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002911 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2912 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002913 errorCode = ERROR_ILLEGAL_ARGUMENT;
2914 break;
2915 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002916 msg = fmt::sprintf("Camera \"%s\" is in use",
2917 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 errorCode = ERROR_CAMERA_IN_USE;
2919 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002920 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002921 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002922 "valid range.", torchStrength);
2923 errorCode = ERROR_ILLEGAL_ARGUMENT;
2924 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002925 default:
Austin Borgered99f642023-06-01 16:51:35 -07002926 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002928 }
Austin Borgered99f642023-06-01 16:51:35 -07002929 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2930 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002931 }
2932
2933 {
2934 // update the link to client's death
2935 // Store the last client that turns on each camera's torch mode.
2936 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002937 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002938 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002939 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002940 } else {
2941 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2942 mTorchClientMap.replaceValueAt(index, clientBinder);
2943 }
2944 clientBinder->linkToDeath(this);
2945 }
2946
2947 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002948 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002949 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002950 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002951 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002952 }
2953 return Status::ok();
2954}
2955
malikakash73125c62023-07-21 22:44:34 +00002956Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002957 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002958 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002959
2960 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002961 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002962 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002963 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2964 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002965 }
2966
Jayant Chowdhary12361932018-08-27 14:46:13 -07002967 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002968 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002969
Austin Borgered99f642023-06-01 16:51:35 -07002970 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002971 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002972 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002973 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002974 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002975 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002976 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002977 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002978 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002979 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002980 }
2981
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002982 StatusInternal cameraStatus = state->getStatus();
2983 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002984 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002985 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2986 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002987 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002988 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002989 }
2990
2991 {
2992 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002993 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002994 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002995 if (err != OK) {
2996 if (err == NAME_NOT_FOUND) {
2997 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002998 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002999 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003000 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003001 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003002 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003003 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003004 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003005 }
3006
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003007 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003008 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003009 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003010 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003011 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3012 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003013 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003014 } else {
3015 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003016 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003017 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3018 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003019 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003020 }
3021 }
3022 }
3023
Ruben Brunk99e69712015-05-26 17:25:07 -07003024 {
3025 // Update UID map - this is used in the torch status changed callbacks, so must be done
3026 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003027 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003028 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003029 }
3030
Austin Borgered99f642023-06-01 16:51:35 -07003031 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003033 if (err != OK) {
3034 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003035 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003036 switch (err) {
3037 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003038 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3039 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003040 errorCode = ERROR_ILLEGAL_ARGUMENT;
3041 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003042 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003043 msg = fmt::sprintf("Camera \"%s\" is in use",
3044 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003045 errorCode = ERROR_CAMERA_IN_USE;
3046 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003047 default:
Austin Borgered99f642023-06-01 16:51:35 -07003048 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003049 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003050 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003051 errorCode = ERROR_INVALID_OPERATION;
3052 }
Austin Borgered99f642023-06-01 16:51:35 -07003053 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3054 logServiceError(msg, errorCode);
3055 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003056 }
3057
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003058 {
3059 // update the link to client's death
3060 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003061 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003062 if (enabled) {
3063 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003064 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003065 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003066 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003067 mTorchClientMap.replaceValueAt(index, clientBinder);
3068 }
3069 clientBinder->linkToDeath(this);
3070 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003071 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003072 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003073 }
3074
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003075 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003076 std::string torchState = enabled ? "on" : "off";
3077 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3078 torchState.c_str(), clientPid);
3079 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003081}
3082
Austin Borgered99f642023-06-01 16:51:35 -07003083void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3084 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3085 mTorchUidMap[cameraId].first = uid;
3086 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003087 } else {
3088 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003089 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003090 }
3091}
3092
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003093Status CameraService::notifySystemEvent(int32_t eventId,
3094 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003095 const int pid = CameraThreadState::getCallingPid();
3096 const int selfPid = getpid();
3097
3098 // Permission checks
3099 if (pid != selfPid) {
3100 // Ensure we're being called by system_server, or similar process with
3101 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003102 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003103 const int uid = CameraThreadState::getCallingUid();
3104 ALOGE("Permission Denial: cannot send updates to camera service about system"
3105 " events from pid=%d, uid=%d", pid, uid);
3106 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003107 "No permission to send updates to camera service about system events"
3108 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003109 }
3110 }
3111
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003112 ATRACE_CALL();
3113
Ruben Brunk36597b22015-03-20 22:15:57 -07003114 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003115 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003116 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003117 // from a system server crash
3118 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003119 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003120 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003121 break;
3122 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003123 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3124 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003125 if (args.size() != 1) {
3126 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3127 "USB Device Event requires 1 argument");
3128 }
3129
Valentin Iftime29e2e152021-08-13 15:17:33 +02003130 // Notify CameraProviderManager for lazy HALs
3131 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3132 std::to_string(args[0]));
3133 break;
3134 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003135 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003136 default: {
3137 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3138 eventId);
3139 break;
3140 }
3141 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003142 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003143}
3144
Emilian Peev53722fa2019-02-22 17:47:20 -08003145void CameraService::notifyMonitoredUids() {
3146 Mutex::Autolock lock(mStatusListenerLock);
3147
3148 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003149 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003150 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3151 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003152 }
3153}
3154
Austin Borgerdddb7552023-03-30 17:53:01 -07003155void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3156 Mutex::Autolock lock(mStatusListenerLock);
3157
3158 for (const auto& it : mListenerList) {
3159 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3160 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3161 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3162 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3163 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3164 }
3165 }
3166}
3167
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003168Status CameraService::notifyDeviceStateChange(int64_t newState) {
3169 const int pid = CameraThreadState::getCallingPid();
3170 const int selfPid = getpid();
3171
3172 // Permission checks
3173 if (pid != selfPid) {
3174 // Ensure we're being called by system_server, or similar process with
3175 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003176 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003177 const int uid = CameraThreadState::getCallingUid();
3178 ALOGE("Permission Denial: cannot send updates to camera service about device"
3179 " state changes from pid=%d, uid=%d", pid, uid);
3180 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3181 "No permission to send updates to camera service about device state"
3182 " changes from pid=%d, uid=%d", pid, uid);
3183 }
3184 }
3185
3186 ATRACE_CALL();
3187
Austin Borger18b30a72022-10-27 12:20:29 -07003188 {
3189 Mutex::Autolock lock(mServiceLock);
3190 mDeviceState = newState;
3191 }
3192
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003193 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003194
3195 return Status::ok();
3196}
3197
Emilian Peev8b64f282021-03-25 16:49:57 -07003198Status CameraService::notifyDisplayConfigurationChange() {
3199 ATRACE_CALL();
3200 const int callingPid = CameraThreadState::getCallingPid();
3201 const int selfPid = getpid();
3202
3203 // Permission checks
3204 if (callingPid != selfPid) {
3205 // Ensure we're being called by system_server, or similar process with
3206 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003207 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07003208 const int uid = CameraThreadState::getCallingUid();
3209 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3210 " changes from pid=%d, uid=%d", callingPid, uid);
3211 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3212 "No permission to send updates to camera service about orientation"
3213 " changes from pid=%d, uid=%d", callingPid, uid);
3214 }
3215 }
3216
3217 Mutex::Autolock lock(mServiceLock);
3218
3219 // Don't do anything if rotate-and-crop override via cmd is active
3220 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3221
3222 const auto clients = mActiveClientManager.getAll();
3223 for (auto& current : clients) {
3224 if (current != nullptr) {
3225 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003226 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3227 basicClient->setRotateAndCropOverride(
3228 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3229 basicClient->getPackageName(),
3230 basicClient->getCameraFacing(),
3231 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003232 }
3233 }
3234 }
3235
3236 return Status::ok();
3237}
3238
3239Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003240 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3241 ATRACE_CALL();
3242 if (!concurrentCameraIds) {
3243 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3244 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3245 }
3246
3247 if (!mInitialized) {
3248 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003249 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003250 return STATUS_ERROR(ERROR_DISCONNECTED,
3251 "Camera subsystem is not available");
3252 }
3253 // First call into the provider and get the set of concurrent camera
3254 // combinations
3255 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003256 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003257 for (auto &combination : concurrentCameraCombinations) {
3258 std::vector<std::string> validCombination;
3259 for (auto &cameraId : combination) {
3260 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003261 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003262 if (state == nullptr) {
3263 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3264 continue;
3265 }
3266 StatusInternal status = state->getStatus();
3267 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3268 continue;
3269 }
Austin Borgered99f642023-06-01 16:51:35 -07003270 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003271 continue;
3272 }
3273 validCombination.push_back(cameraId);
3274 }
3275 if (validCombination.size() != 0) {
3276 concurrentCameraIds->push_back(std::move(validCombination));
3277 }
3278 }
3279 return Status::ok();
3280}
3281
Shuzhen Wang045be6c2023-10-12 10:01:10 -07003282bool CameraService::hasCameraPermissions() const {
3283 int callingPid = CameraThreadState::getCallingPid();
3284 int callingUid = CameraThreadState::getCallingUid();
3285 AttributionSourceState attributionSource{};
3286 attributionSource.pid = callingPid;
3287 attributionSource.uid = callingUid;
3288 bool res = checkPermission(std::string(), sCameraPermission,
3289 attributionSource, std::string(), AppOpsManager::OP_NONE);
3290
3291 bool hasPermission = ((callingPid == getpid()) || res);
3292 if (!hasPermission) {
3293 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
3294 }
3295 return hasPermission;
3296}
3297
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003298Status CameraService::isConcurrentSessionConfigurationSupported(
3299 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003300 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003301 if (!isSupported) {
3302 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3303 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3304 }
3305
3306 if (!mInitialized) {
3307 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3308 return STATUS_ERROR(ERROR_DISCONNECTED,
3309 "Camera subsystem is not available");
3310 }
3311
3312 // Check for camera permissions
Shuzhen Wang045be6c2023-10-12 10:01:10 -07003313 if (!hasCameraPermissions()) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003314 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3315 "android.permission.CAMERA needed to call"
3316 "isConcurrentSessionConfigurationSupported");
3317 }
3318
3319 status_t res =
3320 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003321 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3322 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003323 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003324 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003325 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003326 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3327 "support %s (%d)", strerror(-res), res);
3328 }
3329 return Status::ok();
3330}
3331
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003332Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3333 /*out*/
3334 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003335 return addListenerHelper(listener, cameraStatuses);
3336}
3337
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003338binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3339 std::vector<hardware::CameraStatus>* cameraStatuses) {
3340 return addListenerHelper(listener, cameraStatuses, false, true);
3341}
3342
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003343Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3344 /*out*/
3345 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003346 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003347
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003348 ATRACE_CALL();
3349
Igor Murashkinbfc99152013-02-27 12:55:20 -08003350 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003351
Ruben Brunk3450ba72015-06-16 11:00:37 -07003352 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003353 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003354 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003355 }
3356
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003357 auto clientUid = CameraThreadState::getCallingUid();
3358 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00003359 AttributionSourceState attributionSource{};
3360 attributionSource.uid = clientUid;
3361 attributionSource.pid = clientPid;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07003362
Austin Borger1c1bee02023-06-01 16:51:35 -07003363 bool openCloseCallbackAllowed = checkPermission(std::string(),
3364 sCameraOpenCloseListenerPermission, attributionSource, std::string(),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07003365 AppOpsManager::OP_NONE);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003366
Igor Murashkinbfc99152013-02-27 12:55:20 -08003367 Mutex::Autolock lock(mServiceLock);
3368
Ruben Brunkcc776712015-02-17 20:18:47 -08003369 {
3370 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003371 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003372 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003373 ALOGW("%s: Tried to add listener %p which was already subscribed",
3374 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003375 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003376 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003377 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003378
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003379 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003380 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3381 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003382 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003383 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003384 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003385 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003386 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3387 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3388 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003389 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003390 // The listener still needs to be added to the list of listeners, regardless of what
3391 // permissions the listener process has / whether it is a vendor listener. Since it might be
3392 // eligible to listen to other camera ids.
3393 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003394 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003395 }
3396
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003397 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003398 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003399 Mutex::Autolock lock(mCameraStatesLock);
3400 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003401 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003402 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003403 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003404 }
3405 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003406 // Remove the camera statuses that should be hidden from the client, we do
3407 // this after collecting the states in order to avoid holding
3408 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3409 // the same time.
3410 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3411 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3412 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3413 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3414 ALOGE("%s: Invalid camera id %s, skipping status update",
3415 __FUNCTION__, s.cameraId.c_str());
3416 return true;
3417 }
3418 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3419 clientUid);}), cameraStatuses->end());
3420
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003421 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003422 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003423 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003424 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003425 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003426
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003427 /*
3428 * Immediately signal current torch status to this listener only
3429 * This may be a subset of all the devices, so don't include it in the response directly
3430 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003431 {
3432 Mutex::Autolock al(mTorchStatusMutex);
3433 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003434 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003435 // The camera id is visible to the client. Fine to send torch
3436 // callback.
3437 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3438 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3439 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003440 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003441 }
3442
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003443 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003444}
Ruben Brunkcc776712015-02-17 20:18:47 -08003445
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003446Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003447 ATRACE_CALL();
3448
Igor Murashkinbfc99152013-02-27 12:55:20 -08003449 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3450
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003451 if (listener == 0) {
3452 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003453 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003454 }
3455
Igor Murashkinbfc99152013-02-27 12:55:20 -08003456 Mutex::Autolock lock(mServiceLock);
3457
Ruben Brunkcc776712015-02-17 20:18:47 -08003458 {
3459 Mutex::Autolock lock(mStatusListenerLock);
3460 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003461 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003462 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003463 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003464 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003465 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003466 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003467 }
3468 }
3469
3470 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3471 __FUNCTION__, listener.get());
3472
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003473 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003474}
3475
Austin Borgered99f642023-06-01 16:51:35 -07003476Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003477
3478 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003479 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3480
3481 if (parameters == NULL) {
3482 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003483 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003484 }
3485
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003486 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003487
3488 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003489 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003490 // Error logged by caller
3491 return ret;
3492 }
3493
3494 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003495
Austin Borgered99f642023-06-01 16:51:35 -07003496 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003497
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003498 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003499}
3500
Austin Borgered99f642023-06-01 16:51:35 -07003501Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003502 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003503 ATRACE_CALL();
3504
malikakashedb38962023-09-06 00:03:35 +00003505 const std::string cameraId = resolveCameraId(
3506 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003507
Austin Borgered99f642023-06-01 16:51:35 -07003508 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003509
3510 switch (apiVersion) {
3511 case API_VERSION_1:
3512 case API_VERSION_2:
3513 break;
3514 default:
Austin Borgered99f642023-06-01 16:51:35 -07003515 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3516 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3517 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003518 }
3519
Austin Borger18b30a72022-10-27 12:20:29 -07003520 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003521 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003522 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003523 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3524 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3525 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003526 }
3527 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3528 int deviceVersion = deviceVersionAndTransport.first;
3529 switch (deviceVersion) {
3530 case CAMERA_DEVICE_API_VERSION_1_0:
3531 case CAMERA_DEVICE_API_VERSION_3_0:
3532 case CAMERA_DEVICE_API_VERSION_3_1:
3533 if (apiVersion == API_VERSION_2) {
3534 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003535 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003536 *isSupported = false;
3537 } else { // if (apiVersion == API_VERSION_1) {
3538 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003539 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003540 *isSupported = true;
3541 }
3542 break;
3543 case CAMERA_DEVICE_API_VERSION_3_2:
3544 case CAMERA_DEVICE_API_VERSION_3_3:
3545 case CAMERA_DEVICE_API_VERSION_3_4:
3546 case CAMERA_DEVICE_API_VERSION_3_5:
3547 case CAMERA_DEVICE_API_VERSION_3_6:
3548 case CAMERA_DEVICE_API_VERSION_3_7:
3549 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003550 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003551 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003552 break;
3553 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003554 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3555 deviceVersion, cameraId.c_str());
3556 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3557 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003558 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003559 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003560 } else {
3561 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003562 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003563 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003564}
3565
Austin Borgered99f642023-06-01 16:51:35 -07003566Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003567 /*out*/ bool *isSupported) {
3568 ATRACE_CALL();
3569
malikakashedb38962023-09-06 00:03:35 +00003570 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3571 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003572
Austin Borgered99f642023-06-01 16:51:35 -07003573 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3574 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003575
3576 return Status::ok();
3577}
3578
Cliff Wud8cae102021-03-11 01:37:42 +08003579Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003580 const std::string& packageName, const std::string& internalCamId,
3581 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003582 const sp<ICameraInjectionCallback>& callback,
3583 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003584 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003585 ATRACE_CALL();
3586
Austin Borgered99f642023-06-01 16:51:35 -07003587 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003588 const int pid = CameraThreadState::getCallingPid();
3589 const int uid = CameraThreadState::getCallingUid();
3590 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3591 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3592 "Permission Denial: no permission to inject camera");
3593 }
3594
3595 ALOGV(
3596 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3597 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003598 __FUNCTION__, packageName.c_str(),
3599 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003600
Cliff Wud3a05312021-04-26 23:07:31 +08003601 {
3602 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003603 mInjectionInternalCamId = internalCamId;
3604 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003605 mInjectionStatusListener->addListener(callback);
3606 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003607 status_t res = NO_ERROR;
3608 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3609 // If the client already exists, we can directly connect to the camera device through the
3610 // client's injectCamera(), otherwise we need to wait until the client is established
3611 // (execute connectHelper()) before injecting the camera to the camera device.
3612 if (clientDescriptor != nullptr) {
3613 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003614 sp<BasicClient> clientSp = clientDescriptor->getValue();
3615 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3616 if(res != OK) {
3617 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3618 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003619 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003620 }
3621 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003622 if(res != OK) {
3623 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3624 }
3625 } else {
3626 mInjectionInitPending = true;
3627 }
3628 }
Cliff Wud8cae102021-03-11 01:37:42 +08003629
Cliff Wud3a05312021-04-26 23:07:31 +08003630 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003631}
3632
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003633Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003634 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003635 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3636 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3637 return Status::ok();
3638}
3639
Ruben Brunkcc776712015-02-17 20:18:47 -08003640void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003641 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003642 for (auto& i : mActiveClientManager.getAll()) {
3643 auto clientSp = i->getValue();
3644 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003645 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003646 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003647 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003648 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003649 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003650}
3651
Ruben Brunkcc776712015-02-17 20:18:47 -08003652bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003653 bool ret = false;
3654 {
3655 // Acquire mServiceLock and prevent other clients from connecting
3656 std::unique_ptr<AutoConditionLock> lock =
3657 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003658
Igor Murashkin634a5152013-02-20 17:15:11 -08003659
Ruben Brunkcc776712015-02-17 20:18:47 -08003660 std::vector<sp<BasicClient>> evicted;
3661 for (auto& i : mActiveClientManager.getAll()) {
3662 auto clientSp = i->getValue();
3663 if (clientSp.get() == nullptr) {
3664 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3665 mActiveClientManager.remove(i);
3666 continue;
3667 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003668 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003669 mActiveClientManager.remove(i);
3670 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003671
Ruben Brunkcc776712015-02-17 20:18:47 -08003672 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003673 clientSp->notifyError(
3674 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003675 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003676 }
3677 }
3678
Ruben Brunkcc776712015-02-17 20:18:47 -08003679 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3680 // other clients from connecting in mServiceLockWrapper if held
3681 mServiceLock.unlock();
3682
Ruben Brunk36597b22015-03-20 22:15:57 -07003683 // Do not clear caller identity, remote caller should be client proccess
3684
Ruben Brunkcc776712015-02-17 20:18:47 -08003685 for (auto& i : evicted) {
3686 if (i.get() != nullptr) {
3687 i->disconnect();
3688 ret = true;
3689 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003690 }
3691
Ruben Brunkcc776712015-02-17 20:18:47 -08003692 // Reacquire mServiceLock
3693 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003694
Ruben Brunkcc776712015-02-17 20:18:47 -08003695 } // lock is destroyed, allow further connect calls
3696
3697 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003698}
3699
Ruben Brunkcc776712015-02-17 20:18:47 -08003700std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003701 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003702 std::shared_ptr<CameraState> state;
3703 {
3704 Mutex::Autolock lock(mCameraStatesLock);
3705 auto iter = mCameraStates.find(cameraId);
3706 if (iter != mCameraStates.end()) {
3707 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003708 }
3709 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003710 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003711}
3712
Austin Borgered99f642023-06-01 16:51:35 -07003713sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003714 // Remove from active clients list
3715 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3716 if (clientDescriptorPtr == nullptr) {
3717 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003718 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003719 return sp<BasicClient>{nullptr};
3720 }
3721
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003722 sp<BasicClient> client = clientDescriptorPtr->getValue();
3723 if (client.get() != nullptr) {
3724 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3725 }
3726 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003727}
3728
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003729void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003730 // Acquire mServiceLock and prevent other clients from connecting
3731 std::unique_ptr<AutoConditionLock> lock =
3732 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3733
Ruben Brunk6267b532015-04-30 17:44:07 -07003734 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003735 for (size_t i = 0; i < newUserIds.size(); i++) {
3736 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003737 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003738 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003739 return;
3740 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003741 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003742 }
3743
Ruben Brunka8ca9152015-04-07 14:23:40 -07003744
Ruben Brunk6267b532015-04-30 17:44:07 -07003745 if (newAllowedUsers == mAllowedUsers) {
3746 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3747 return;
3748 }
3749
3750 logUserSwitch(mAllowedUsers, newAllowedUsers);
3751
3752 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003753
3754 // Current user has switched, evict all current clients.
3755 std::vector<sp<BasicClient>> evicted;
3756 for (auto& i : mActiveClientManager.getAll()) {
3757 auto clientSp = i->getValue();
3758
3759 if (clientSp.get() == nullptr) {
3760 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3761 continue;
3762 }
3763
Ruben Brunk6267b532015-04-30 17:44:07 -07003764 // Don't evict clients that are still allowed.
3765 uid_t clientUid = clientSp->getClientUid();
3766 userid_t clientUserId = multiuser_get_user_id(clientUid);
3767 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3768 continue;
3769 }
3770
Ruben Brunk36597b22015-03-20 22:15:57 -07003771 evicted.push_back(clientSp);
3772
Ruben Brunk36597b22015-03-20 22:15:57 -07003773 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003774 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003775
Ruben Brunk36597b22015-03-20 22:15:57 -07003776 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003777 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003778 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003779 " to user switch.", i->getKey().c_str(),
3780 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003781 i->getOwnerId(), i->getPriority().getScore(),
3782 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003783
3784 }
3785
3786 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3787 // blocking other clients from connecting in mServiceLockWrapper if held.
3788 mServiceLock.unlock();
3789
3790 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003791 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003792
3793 for (auto& i : evicted) {
3794 i->disconnect();
3795 }
3796
Jayant Chowdhary12361932018-08-27 14:46:13 -07003797 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003798
3799 // Reacquire mServiceLock
3800 mServiceLock.lock();
3801}
Ruben Brunkcc776712015-02-17 20:18:47 -08003802
Austin Borgered99f642023-06-01 16:51:35 -07003803void CameraService::logEvent(const std::string &event) {
3804 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003805 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003806 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003807 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003808 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003809 mEventLog.add(msg);
3810 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3811 // Error event not added to the dumpsys log before
3812 mEventLog.add(msg);
3813 sServiceErrorEventSet.insert(msg);
3814 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003815}
3816
Austin Borgered99f642023-06-01 16:51:35 -07003817void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3818 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003819 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003820 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3821 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003822}
3823
Austin Borgered99f642023-06-01 16:51:35 -07003824void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3825 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003826 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003827 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3828 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003829}
3830
Austin Borgered99f642023-06-01 16:51:35 -07003831void CameraService::logConnected(const std::string &cameraId, int clientPid,
3832 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003833 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003834 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3835 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003836}
3837
Austin Borgered99f642023-06-01 16:51:35 -07003838void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3839 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003840 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003841 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3842 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003843}
3844
Austin Borgered99f642023-06-01 16:51:35 -07003845void CameraService::logRejected(const std::string &cameraId, int clientPid,
3846 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003847 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003848 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3849 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003850}
3851
Austin Borgered99f642023-06-01 16:51:35 -07003852void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3853 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003854 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003855 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3856 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003857}
3858
Ruben Brunk6267b532015-04-30 17:44:07 -07003859void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3860 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003861 std::string newUsers = toString(newUserIds);
3862 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003863 if (oldUsers.size() == 0) {
3864 oldUsers = "<None>";
3865 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003866 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003867 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3868 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003869}
3870
Austin Borgered99f642023-06-01 16:51:35 -07003871void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003872 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003873 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003874}
3875
Austin Borgered99f642023-06-01 16:51:35 -07003876void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003877 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003878 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003879}
3880
Austin Borgered99f642023-06-01 16:51:35 -07003881void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003882 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003883 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003884}
3885
Austin Borgered99f642023-06-01 16:51:35 -07003886void CameraService::logServiceError(const std::string &msg, int errorCode) {
3887 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3888 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003889}
3890
Ruben Brunk36597b22015-03-20 22:15:57 -07003891status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3892 uint32_t flags) {
3893
Mathias Agopian65ab4712010-07-14 17:59:35 -07003894 // Permission checks
3895 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003896 case SHELL_COMMAND_TRANSACTION: {
3897 int in = data.readFileDescriptor();
3898 int out = data.readFileDescriptor();
3899 int err = data.readFileDescriptor();
3900 int argc = data.readInt32();
3901 Vector<String16> args;
3902 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3903 args.add(data.readString16());
3904 }
3905 sp<IBinder> unusedCallback;
3906 sp<IResultReceiver> resultReceiver;
3907 status_t status;
3908 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3909 return status;
3910 }
3911 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3912 return status;
3913 }
3914 status = shellCommand(in, out, err, args);
3915 if (resultReceiver != nullptr) {
3916 resultReceiver->send(status);
3917 }
3918 return NO_ERROR;
3919 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003920 }
3921
3922 return BnCameraService::onTransact(code, data, reply, flags);
3923}
3924
Mathias Agopian65ab4712010-07-14 17:59:35 -07003925// We share the media players for shutter and recording sound for all clients.
3926// A reference count is kept to determine when we will actually release the
3927// media players.
3928
Jaekyun Seokef498052018-03-23 13:09:44 +09003929sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3930 sp<MediaPlayer> mp = new MediaPlayer();
3931 status_t error;
3932 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003933 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003934 error = mp->prepare();
3935 }
3936 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003937 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003938 mp->disconnect();
3939 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003940 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003941 }
3942 return mp;
3943}
3944
username5755fea2018-12-27 09:48:08 +08003945void CameraService::increaseSoundRef() {
3946 Mutex::Autolock lock(mSoundLock);
3947 mSoundRef++;
3948}
3949
3950void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003951 ATRACE_CALL();
3952
username5755fea2018-12-27 09:48:08 +08003953 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3954 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3955 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3956 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3957 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3958 }
3959 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3960 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3961 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3962 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003963 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003964 }
3965 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3966 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3967 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3968 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3969 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971}
3972
username5755fea2018-12-27 09:48:08 +08003973void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003975 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976 if (--mSoundRef) return;
3977
3978 for (int i = 0; i < NUM_SOUNDS; i++) {
3979 if (mSoundPlayer[i] != 0) {
3980 mSoundPlayer[i]->disconnect();
3981 mSoundPlayer[i].clear();
3982 }
3983 }
3984}
3985
3986void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003987 ATRACE_CALL();
3988
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003990 if (kind < 0 || kind >= NUM_SOUNDS) {
3991 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3992 return;
3993 }
3994
Mathias Agopian65ab4712010-07-14 17:59:35 -07003995 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003996 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997 sp<MediaPlayer> player = mSoundPlayer[kind];
3998 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003999 player->seekTo(0);
4000 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 }
4002}
4003
4004// ----------------------------------------------------------------------------
4005
4006CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004007 const sp<ICameraClient>& cameraClient,
Austin Borgered99f642023-06-01 16:51:35 -07004008 const std::string& clientPackageName, bool systemNativeClient,
4009 const std::optional<std::string>& clientFeatureId,
4010 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004011 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004012 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004013 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004014 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004015 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004016 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004017 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004018 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004019 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004020 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004021{
Jayant Chowdhary12361932018-08-27 14:46:13 -07004022 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004023 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004025 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026
username5755fea2018-12-27 09:48:08 +08004027 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004028
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004029 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030}
4031
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032// tear down the client
4033CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004034 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004035 mDestructionStarted = true;
4036
username5755fea2018-12-27 09:48:08 +08004037 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004038 // unconditionally disconnect. function is idempotent
4039 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040}
4041
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004042sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4043
Igor Murashkin634a5152013-02-20 17:15:11 -08004044CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004045 const sp<IBinder>& remoteCallback,
Austin Borgered99f642023-06-01 16:51:35 -07004046 const std::string& clientPackageName, bool nativeClient,
4047 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004048 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004049 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004050 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004051 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004052 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4053 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004054 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004055 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004056 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004057 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004058 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004059 mRemoteBinder(remoteCallback),
4060 mOpsActive(false),
4061 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004062{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004063 if (sCameraService == nullptr) {
4064 sCameraService = cameraService;
4065 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004066
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004067 // There are 2 scenarios in which a client won't have AppOps operations
4068 // (both scenarios : native clients)
4069 // 1) It's an system native client*, the package name will be empty
4070 // and it will return from this function in the previous if condition
4071 // (This is the same as the previously existing behavior).
4072 // 2) It is a system native client, but its package name has been
4073 // modified for debugging, however it still must not use AppOps since
4074 // the package name is not a real one.
4075 //
4076 // * system native client - native client with UID < AID_APP_START. It
4077 // doesn't exclude clients not on the system partition.
4078 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004079 mAppOpsManager = std::make_unique<AppOpsManager>();
4080 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004081
4082 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004083}
4084
4085CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004086 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004087 mDestructionStarted = true;
4088}
4089
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004090binder::Status CameraService::BasicClient::disconnect() {
4091 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004092 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004093 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004094 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004095 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004096
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004097 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004098 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004099 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004100 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004101
4102 sp<IBinder> remote = getRemote();
4103 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004104 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004105 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004106
4107 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004108 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004109 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004110 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004111 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004112
Igor Murashkincba2c162013-03-20 15:56:31 -07004113 // client shouldn't be able to call into us anymore
4114 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004115
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004116 const auto& mActivityManager = getActivityManager();
4117 if (mActivityManager) {
4118 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
4119 CameraThreadState::getCallingUid(),
4120 CameraThreadState::getCallingPid());
4121 }
4122
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004123 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004124}
4125
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004126status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4127 // No dumping of clients directly over Binder,
4128 // must go through CameraService::dump
4129 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004130 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004131 return OK;
4132}
4133
Austin Borgered99f642023-06-01 16:51:35 -07004134status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004135 // Can't watch tags directly, must go through CameraService::startWatchingTags
4136 return OK;
4137}
4138
4139status_t CameraService::BasicClient::stopWatchingTags(int) {
4140 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4141 return OK;
4142}
4143
4144status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4145 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4146 return OK;
4147}
4148
Austin Borgered99f642023-06-01 16:51:35 -07004149std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004150 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004151}
4152
Emilian Peev8b64f282021-03-25 16:49:57 -07004153int CameraService::BasicClient::getCameraFacing() const {
4154 return mCameraFacing;
4155}
4156
4157int CameraService::BasicClient::getCameraOrientation() const {
4158 return mOrientation;
4159}
Ruben Brunkcc776712015-02-17 20:18:47 -08004160
4161int CameraService::BasicClient::getClientPid() const {
4162 return mClientPid;
4163}
4164
Ruben Brunk6267b532015-04-30 17:44:07 -07004165uid_t CameraService::BasicClient::getClientUid() const {
4166 return mClientUid;
4167}
4168
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004169bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4170 // Defaults to API2.
4171 return level == API_2;
4172}
4173
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004174status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004175 {
4176 Mutex::Autolock l(mAudioRestrictionLock);
4177 mAudioRestriction = mode;
4178 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004179 sCameraService->updateAudioRestriction();
4180 return OK;
4181}
4182
4183int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004184 return sCameraService->updateAudioRestriction();
4185}
4186
4187int32_t CameraService::BasicClient::getAudioRestriction() const {
4188 Mutex::Autolock l(mAudioRestrictionLock);
4189 return mAudioRestriction;
4190}
4191
4192bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4193 switch (mode) {
4194 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4195 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4196 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4197 return true;
4198 default:
4199 return false;
4200 }
4201}
4202
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004203status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4204 if (mode == AppOpsManager::MODE_ERRORED) {
4205 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004206 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004207 return PERMISSION_DENIED;
4208 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4209 // If the calling Uid is trusted (a native service), the AppOpsManager could
4210 // return MODE_IGNORED. Do not treat such case as error.
4211 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4212 mClientPackageName);
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004213 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004214 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004215 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4216 // We prefer to successfully open the camera and perform camera muting
4217 // or blocking in connectHelper as handleAppOpMode can be called before the
4218 // connection has been fully established and at that time camera muting
4219 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004220 if (!isUidActive || !isCameraPrivacyEnabled) {
4221 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004222 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004223 // Return the same error as for device policy manager rejection
4224 return -EACCES;
4225 }
4226 }
4227 return OK;
4228}
4229
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004230status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004231 ATRACE_CALL();
4232
Igor Murashkine6800ce2013-03-04 17:25:57 -08004233 {
4234 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004235 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004236 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004237 if (mAppOpsManager != nullptr) {
4238 // Notify app ops that the camera is not available
4239 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004240 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004241 toString16(mClientPackageName), mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004242
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004243 // Just check for camera acccess here on open - delay startOp until
4244 // camera frames start streaming in startCameraStreamingOps
4245 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004246 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004247 status_t res = handleAppOpMode(mode);
4248 if (res != OK) {
4249 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004250 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004251 }
4252
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004253 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004254
4255 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004256 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004257
Austin Borgerdddb7552023-03-30 17:53:01 -07004258 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004259
Shuzhen Wang695044d2020-03-06 09:02:23 -08004260 // Notify listeners of camera open/close status
4261 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4262
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004263 return OK;
4264}
4265
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004266status_t CameraService::BasicClient::startCameraStreamingOps() {
4267 ATRACE_CALL();
4268
4269 if (!mOpsActive) {
4270 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4271 return INVALID_OPERATION;
4272 }
4273 if (mOpsStreaming) {
4274 ALOGV("%s: Streaming already active!", __FUNCTION__);
4275 return OK;
4276 }
4277
4278 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004279 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004280
4281 if (mAppOpsManager != nullptr) {
4282 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004283 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4284 toString16(mClientFeatureId),
4285 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004286 status_t res = handleAppOpMode(mode);
4287 if (res != OK) {
4288 return res;
4289 }
4290 }
4291
4292 mOpsStreaming = true;
4293
4294 return OK;
4295}
4296
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004297status_t CameraService::BasicClient::noteAppOp() {
4298 ATRACE_CALL();
4299
4300 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004301 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004302
4303 // noteAppOp is only used for when camera mute is not supported, in order
4304 // to trigger the sensor privacy "Unblock" dialog
4305 if (mAppOpsManager != nullptr) {
4306 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004307 toString16(mClientPackageName), toString16(mClientFeatureId),
4308 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004309 status_t res = handleAppOpMode(mode);
4310 if (res != OK) {
4311 return res;
4312 }
4313 }
4314
4315 return OK;
4316}
4317
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004318status_t CameraService::BasicClient::finishCameraStreamingOps() {
4319 ATRACE_CALL();
4320
4321 if (!mOpsActive) {
4322 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4323 return INVALID_OPERATION;
4324 }
4325 if (!mOpsStreaming) {
4326 ALOGV("%s: Streaming not active!", __FUNCTION__);
4327 return OK;
4328 }
4329
4330 if (mAppOpsManager != nullptr) {
4331 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004332 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004333 mOpsStreaming = false;
4334 }
4335
4336 return OK;
4337}
4338
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004339status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004340 ATRACE_CALL();
4341
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004342 if (mOpsStreaming) {
4343 // Make sure we've notified everyone about camera stopping
4344 finishCameraStreamingOps();
4345 }
4346
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004347 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004348 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004349 mOpsActive = false;
4350
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004351 // This function is called when a client disconnects. This should
4352 // release the camera, but actually only if it was in a proper
4353 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004354 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004355 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004356
Ruben Brunkcc776712015-02-17 20:18:47 -08004357 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004358 sCameraService->updateStatus(StatusInternal::PRESENT,
4359 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004360 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004361 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004362 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4363 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004364 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004365 mOpsCallback.clear();
4366
Austin Borgerdddb7552023-03-30 17:53:01 -07004367 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004368
Shuzhen Wang695044d2020-03-06 09:02:23 -08004369 // Notify listeners of camera open/close status
4370 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4371
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004372 return OK;
4373}
4374
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004375void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004376 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004377 if (mAppOpsManager == nullptr) {
4378 return;
4379 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004380 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004381 if (op != AppOpsManager::OP_CAMERA) {
4382 ALOGW("Unexpected app ops notification received: %d", op);
4383 return;
4384 }
4385
4386 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004387 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004388 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004389 ALOGV("checkOp returns: %d, %s ", res,
4390 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4391 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4392 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4393 "UNKNOWN");
4394
Shuzhen Wang64900852021-02-05 09:03:29 -08004395 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004396 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4397 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004398 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004399 } else if (res == AppOpsManager::MODE_IGNORED) {
4400 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004401 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004402 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004403 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
4404 mCameraIdStr.c_str(), mClientPackageName.c_str(),
4405 mUidIsTrusted, isUidActive);
Shuzhen Wang64900852021-02-05 09:03:29 -08004406 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
4407 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
4408 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004409 if (!mUidIsTrusted) {
4410 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4411 setCameraMute(true);
4412 } else if (!isUidActive
4413 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4414 block();
4415 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004416 }
Evan Severson09ab4002021-02-10 14:15:19 -08004417 } else if (res == AppOpsManager::MODE_ALLOWED) {
4418 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004419 }
4420}
4421
Svet Ganova453d0d2018-01-11 15:37:58 -08004422void CameraService::BasicClient::block() {
4423 ATRACE_CALL();
4424
4425 // Reset the client PID to allow server-initiated disconnect,
4426 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004427 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004428 CaptureResultExtras resultExtras; // a dummy result (invalid)
4429 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4430 disconnect();
4431}
4432
Mathias Agopian65ab4712010-07-14 17:59:35 -07004433// ----------------------------------------------------------------------------
4434
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004435void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004436 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004437 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004438 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4439 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4440 api1ErrorCode = CAMERA_ERROR_DISABLED;
4441 }
4442 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004443 } else {
4444 ALOGE("mRemoteCallback is NULL!!");
4445 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004446}
4447
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004448// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004449binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004450 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004451 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004452}
4453
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004454bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4455 return level == API_1;
4456}
4457
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004458CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4459 mClient(client) {
4460}
4461
4462void CameraService::Client::OpsCallback::opChanged(int32_t op,
4463 const String16& packageName) {
4464 sp<BasicClient> client = mClient.promote();
4465 if (client != NULL) {
4466 client->opChanged(op, packageName);
4467 }
4468}
4469
Mathias Agopian65ab4712010-07-14 17:59:35 -07004470// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004471// UidPolicy
4472// ----------------------------------------------------------------------------
4473
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004474void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004475 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004476 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004477
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004478 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004479 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004480 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004481 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004482 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4483 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004484 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004485 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004486 if (res == OK) {
4487 mRegistered = true;
4488 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004489 } else {
4490 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004491 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004492}
4493
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004494void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004495 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004496 return;
4497 }
4498
4499 registerWithActivityManager();
4500}
4501
4502void CameraService::UidPolicy::registerSelf() {
4503 // Use check service to see if the activity service is available
4504 // If not available then register for notifications, instead of blocking
4505 // till the service is ready
4506 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004507 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004508 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004509 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004510 } else {
4511 registerWithActivityManager();
4512 }
4513}
4514
Svet Ganova453d0d2018-01-11 15:37:58 -08004515void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004516 Mutex::Autolock _l(mUidLock);
4517
Steven Moreland2f348142019-07-02 15:59:07 -07004518 mAm.unregisterUidObserver(this);
4519 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004520 mRegistered = false;
4521 mActiveUids.clear();
4522 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004523}
4524
4525void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4526 onUidIdle(uid, disabled);
4527}
4528
4529void CameraService::UidPolicy::onUidActive(uid_t uid) {
4530 Mutex::Autolock _l(mUidLock);
4531 mActiveUids.insert(uid);
4532}
4533
4534void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4535 bool deleted = false;
4536 {
4537 Mutex::Autolock _l(mUidLock);
4538 if (mActiveUids.erase(uid) > 0) {
4539 deleted = true;
4540 }
4541 }
4542 if (deleted) {
4543 sp<CameraService> service = mService.promote();
4544 if (service != nullptr) {
4545 service->blockClientsForUid(uid);
4546 }
4547 }
4548}
4549
Emilian Peev53722fa2019-02-22 17:47:20 -08004550void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004551 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004552 bool procStateChange = false;
4553 {
4554 Mutex::Autolock _l(mUidLock);
4555 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4556 mMonitoredUids[uid].procState != procState) {
4557 mMonitoredUids[uid].procState = procState;
4558 procStateChange = true;
4559 }
4560 }
4561
4562 if (procStateChange) {
4563 sp<CameraService> service = mService.promote();
4564 if (service != nullptr) {
4565 service->notifyMonitoredUids();
4566 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004567 }
4568}
4569
Austin Borgerdddb7552023-03-30 17:53:01 -07004570/**
4571 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4572 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4573 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4574 * monitoredUids. If it is revised above some other monitoredUid, signal
4575 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4576 * foreground apps in split screen - state changes will capture all other cases.
4577 */
4578void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4579 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004580 {
4581 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004582 auto it = mMonitoredUids.find(uid);
4583
4584 if (it != mMonitoredUids.end()) {
4585 if (it->second.hasCamera) {
4586 for (auto &monitoredUid : mMonitoredUids) {
4587 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004588 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004589 notifyUidSet.emplace(monitoredUid.first);
4590 }
4591 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004592 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004593 notifyUidSet.emplace(uid);
4594 } else {
4595 for (auto &monitoredUid : mMonitoredUids) {
4596 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004597 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004598 notifyUidSet.emplace(uid);
4599 }
4600 }
4601 }
4602 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004603 }
4604 }
4605
Austin Borgerdddb7552023-03-30 17:53:01 -07004606 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004607 sp<CameraService> service = mService.promote();
4608 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004609 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004610 }
4611 }
4612}
4613
Austin Borgerdddb7552023-03-30 17:53:01 -07004614/**
4615 * Register a uid for monitoring, and note whether it owns a camera.
4616 */
4617void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004618 Mutex::Autolock _l(mUidLock);
4619 auto it = mMonitoredUids.find(uid);
4620 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004621 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004622 } else {
Austin Borger65577682022-02-17 00:25:43 +00004623 MonitoredUid monitoredUid;
4624 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004625 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004626 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004627 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004628 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004629 if (res != OK) {
4630 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4631 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004632 }
4633
4634 if (openCamera) {
4635 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004636 }
4637}
4638
Austin Borgerdddb7552023-03-30 17:53:01 -07004639/**
4640 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4641 */
4642void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004643 Mutex::Autolock _l(mUidLock);
4644 auto it = mMonitoredUids.find(uid);
4645 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004646 it->second.refCount--;
4647 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004648 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004649 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004650 if (res != OK) {
4651 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4652 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004653 } else if (closeCamera) {
4654 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004655 }
4656 } else {
4657 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4658 }
4659}
4660
Austin Borgered99f642023-06-01 16:51:35 -07004661bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004662 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004663 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004664}
4665
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004666static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4667static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004668
Austin Borgered99f642023-06-01 16:51:35 -07004669bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004670 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004671 // If activity manager is unreachable, assume everything is active
4672 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004673 return true;
4674 }
4675 auto it = mOverrideUids.find(uid);
4676 if (it != mOverrideUids.end()) {
4677 return it->second;
4678 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004679 bool active = mActiveUids.find(uid) != mActiveUids.end();
4680 if (!active) {
4681 // We want active UIDs to always access camera with their first attempt since
4682 // there is no guarantee the app is robustly written and would retry getting
4683 // the camera on failure. The inverse case is not a problem as we would take
4684 // camera away soon once we get the callback that the uid is no longer active.
4685 ActivityManager am;
4686 // Okay to access with a lock held as UID changes are dispatched without
4687 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004688 int64_t startTimeMillis = 0;
4689 do {
4690 // TODO: Fix this b/109950150!
4691 // Okay this is a hack. There is a race between the UID turning active and
4692 // activity being resumed. The proper fix is very risky, so we temporary add
4693 // some polling which should happen pretty rarely anyway as the race is hard
4694 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004695 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004696 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004697 if (active) {
4698 break;
4699 }
4700 if (startTimeMillis <= 0) {
4701 startTimeMillis = uptimeMillis();
4702 }
4703 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004704 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004705 if (remainingTimeMillis <= 0) {
4706 break;
4707 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004708 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4709
4710 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004711 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004712 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004713 } while (true);
4714
Svet Ganov7b4ab782018-03-25 12:48:10 -07004715 if (active) {
4716 // Now that we found out the UID is actually active, cache that
4717 mActiveUids.insert(uid);
4718 }
4719 }
4720 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004721}
4722
Varun Shahb42f1eb2019-04-16 14:45:13 -07004723int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4724 Mutex::Autolock _l(mUidLock);
4725 return getProcStateLocked(uid);
4726}
4727
4728int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4729 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4730 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004731 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004732 }
4733 return procState;
4734}
4735
Austin Borgered99f642023-06-01 16:51:35 -07004736void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4737 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004738 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004739}
4740
Austin Borgered99f642023-06-01 16:51:35 -07004741void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004742 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004743}
4744
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004745void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4746 Mutex::Autolock _l(mUidLock);
4747 ALOGV("UidPolicy: ActivityManager has died");
4748 mRegistered = false;
4749 mActiveUids.clear();
4750}
4751
Austin Borgered99f642023-06-01 16:51:35 -07004752void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004753 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004754 bool wasActive = false;
4755 bool isActive = false;
4756 {
4757 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004758 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004759 mOverrideUids.erase(uid);
4760 if (insert) {
4761 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4762 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004763 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004764 }
4765 if (wasActive != isActive && !isActive) {
4766 sp<CameraService> service = mService.promote();
4767 if (service != nullptr) {
4768 service->blockClientsForUid(uid);
4769 }
4770 }
4771}
4772
4773// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004774// SensorPrivacyPolicy
4775// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004776
4777void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4778{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004779 Mutex::Autolock _l(mSensorPrivacyLock);
4780 if (mRegistered) {
4781 return;
4782 }
Evan Severson09ab4002021-02-10 14:15:19 -08004783 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004784 mSpm.addSensorPrivacyListener(this);
4785 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4786 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004787 if (res == OK) {
4788 mRegistered = true;
4789 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4790 }
4791}
4792
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004793void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4794 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004795 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004796 return;
4797 }
4798
4799 registerWithSensorPrivacyManager();
4800}
4801
4802void CameraService::SensorPrivacyPolicy::registerSelf() {
4803 // Use checkservice to see if the sensor_privacy service is available
4804 // If service is not available then register for notification
4805 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004806 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004807 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004808 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004809 } else {
4810 registerWithSensorPrivacyManager();
4811 }
4812}
4813
Michael Grooverd1d435a2018-12-18 17:39:42 -08004814void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4815 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004816 mSpm.removeSensorPrivacyListener(this);
4817 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004818 mRegistered = false;
4819 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4820}
4821
4822bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004823 if (!mRegistered) {
4824 registerWithSensorPrivacyManager();
4825 }
4826
Michael Grooverd1d435a2018-12-18 17:39:42 -08004827 Mutex::Autolock _l(mSensorPrivacyLock);
4828 return mSensorPrivacyEnabled;
4829}
4830
Evan Seversond0b69922022-01-27 10:47:34 -08004831bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004832 if (!hasCameraPrivacyFeature()) {
4833 return false;
4834 }
Evan Seversond0b69922022-01-27 10:47:34 -08004835 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004836}
4837
Evan Seversond0b69922022-01-27 10:47:34 -08004838binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004839 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004840 {
4841 Mutex::Autolock _l(mSensorPrivacyLock);
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004842 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004843 }
4844 // if sensor privacy is enabled then block all clients from accessing the camera
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004845 if (enabled) {
4846 sp<CameraService> service = mService.promote();
4847 if (service != nullptr) {
4848 service->blockAllClients();
4849 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004850 }
4851 return binder::Status::ok();
4852}
4853
4854void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4855 Mutex::Autolock _l(mSensorPrivacyLock);
4856 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4857 mRegistered = false;
4858}
4859
Evan Severson09ab4002021-02-10 14:15:19 -08004860bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004861 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4862 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4863 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4864 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4865 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004866}
4867
Michael Grooverd1d435a2018-12-18 17:39:42 -08004868// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004869// CameraState
4870// ----------------------------------------------------------------------------
4871
Austin Borgered99f642023-06-01 16:51:35 -07004872CameraService::CameraState::CameraState(const std::string& id, int cost,
4873 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004874 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004875 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004876 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004877
4878CameraService::CameraState::~CameraState() {}
4879
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004880CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004881 Mutex::Autolock lock(mStatusLock);
4882 return mStatus;
4883}
4884
Austin Borgered99f642023-06-01 16:51:35 -07004885std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004886 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004887 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004888 return res;
4889}
4890
Ruben Brunkcc776712015-02-17 20:18:47 -08004891CameraParameters CameraService::CameraState::getShimParams() const {
4892 return mShimParams;
4893}
4894
4895void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4896 mShimParams = params;
4897}
4898
4899int CameraService::CameraState::getCost() const {
4900 return mCost;
4901}
4902
Austin Borgered99f642023-06-01 16:51:35 -07004903std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004904 return mConflicting;
4905}
4906
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004907SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4908 return mSystemCameraKind;
4909}
4910
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004911bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4912 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4913 != mPhysicalCameras.end();
4914}
4915
Austin Borgered99f642023-06-01 16:51:35 -07004916bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004917 Mutex::Autolock lock(mStatusLock);
4918 auto result = mUnavailablePhysicalIds.insert(physicalId);
4919 return result.second;
4920}
4921
Austin Borgered99f642023-06-01 16:51:35 -07004922bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004923 Mutex::Autolock lock(mStatusLock);
4924 auto count = mUnavailablePhysicalIds.erase(physicalId);
4925 return count > 0;
4926}
4927
Austin Borgered99f642023-06-01 16:51:35 -07004928void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004929 Mutex::Autolock lock(mStatusLock);
4930 mClientPackage = clientPackage;
4931}
4932
Austin Borgered99f642023-06-01 16:51:35 -07004933std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004934 Mutex::Autolock lock(mStatusLock);
4935 return mClientPackage;
4936}
4937
Ruben Brunkcc776712015-02-17 20:18:47 -08004938// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004939// ClientEventListener
4940// ----------------------------------------------------------------------------
4941
4942void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004943 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004944 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004945 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004946 if (basicClient.get() != nullptr) {
4947 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004948 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004949 static_cast<int>(basicClient->getClientUid()));
4950 }
4951}
4952
4953void CameraService::ClientEventListener::onClientRemoved(
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.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004960 static_cast<int>(basicClient->getClientUid()));
4961 }
4962}
4963
4964
4965// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004966// CameraClientManager
4967// ----------------------------------------------------------------------------
4968
Ruben Brunk99e69712015-05-26 17:25:07 -07004969CameraService::CameraClientManager::CameraClientManager() {
4970 setListener(std::make_shared<ClientEventListener>());
4971}
4972
Ruben Brunkcc776712015-02-17 20:18:47 -08004973CameraService::CameraClientManager::~CameraClientManager() {}
4974
4975sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004976 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004977 auto descriptor = get(id);
4978 if (descriptor == nullptr) {
4979 return sp<BasicClient>{nullptr};
4980 }
4981 return descriptor->getValue();
4982}
4983
Austin Borgered99f642023-06-01 16:51:35 -07004984std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004985 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004986 std::ostringstream ret;
4987 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004988 bool hasAny = false;
4989 for (auto& i : all) {
4990 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004991 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004992 int32_t cost = i->getCost();
4993 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004994 int32_t score = i->getPriority().getScore();
4995 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004996 auto conflicting = i->getConflicting();
4997 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07004998 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004999 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005000 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005001 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005002 uid_t clientUid = clientSp->getClientUid();
5003 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005004 }
Austin Borgered99f642023-06-01 16:51:35 -07005005 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5006 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005007
Ruben Brunk6267b532015-04-30 17:44:07 -07005008 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005009 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005010 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005011 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005012 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005013 }
5014
Austin Borgered99f642023-06-01 16:51:35 -07005015 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005016 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005017 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005018 }
Austin Borgered99f642023-06-01 16:51:35 -07005019 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005020 }
Austin Borgered99f642023-06-01 16:51:35 -07005021 if (hasAny) ret << "\n";
5022 ret << "]\n";
5023 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005024}
5025
5026CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005027 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5028 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005029 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005030
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005031 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005032 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005033
Austin Borgered99f642023-06-01 16:51:35 -07005034 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005035 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5036 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005037}
5038
5039CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005040 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005041 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005042 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005043 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005044 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5045 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005046}
5047
5048// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005049// InjectionStatusListener
5050// ----------------------------------------------------------------------------
5051
5052void CameraService::InjectionStatusListener::addListener(
5053 const sp<ICameraInjectionCallback>& callback) {
5054 Mutex::Autolock lock(mListenerLock);
5055 if (mCameraInjectionCallback) return;
5056 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5057 if (res == OK) {
5058 mCameraInjectionCallback = callback;
5059 }
5060}
5061
5062void CameraService::InjectionStatusListener::removeListener() {
5063 Mutex::Autolock lock(mListenerLock);
5064 if (mCameraInjectionCallback == nullptr) {
5065 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5066 return;
5067 }
5068 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5069 mCameraInjectionCallback = nullptr;
5070}
5071
5072void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005073 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005074 if (mCameraInjectionCallback == nullptr) {
5075 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5076 return;
5077 }
Cliff Wud3a05312021-04-26 23:07:31 +08005078
5079 switch (err) {
5080 case -ENODEV:
5081 mCameraInjectionCallback->onInjectionError(
5082 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5083 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005084 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005085 break;
5086 case -EBUSY:
5087 mCameraInjectionCallback->onInjectionError(
5088 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5089 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005090 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005091 break;
5092 case DEAD_OBJECT:
5093 mCameraInjectionCallback->onInjectionError(
5094 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5095 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005096 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005097 break;
5098 case INVALID_OPERATION:
5099 mCameraInjectionCallback->onInjectionError(
5100 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5101 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005102 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005103 break;
5104 case UNKNOWN_TRANSACTION:
5105 mCameraInjectionCallback->onInjectionError(
5106 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5107 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005108 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005109 break;
5110 default:
5111 mCameraInjectionCallback->onInjectionError(
5112 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5113 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005114 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005115 }
Cliff Wud8cae102021-03-11 01:37:42 +08005116}
5117
5118void CameraService::InjectionStatusListener::binderDied(
5119 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005120 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5121 auto parent = mParent.promote();
5122 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005123 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5124 if (clientDescriptor != nullptr) {
5125 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5126 baseClientPtr->stopInjection();
5127 }
Cliff Wu3b268182021-07-06 15:44:43 +08005128 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005129 }
5130}
5131
5132// ----------------------------------------------------------------------------
5133// CameraInjectionSession
5134// ----------------------------------------------------------------------------
5135
5136binder::Status CameraService::CameraInjectionSession::stopInjection() {
5137 Mutex::Autolock lock(mInjectionSessionLock);
5138 auto parent = mParent.promote();
5139 if (parent == nullptr) {
5140 ALOGE("CameraInjectionSession: Parent is gone");
5141 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5142 "Camera service encountered error");
5143 }
Cliff Wud3a05312021-04-26 23:07:31 +08005144
5145 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005146 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5147 if (clientDescriptor != nullptr) {
5148 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5149 res = baseClientPtr->stopInjection();
5150 if (res != OK) {
5151 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5152 " ret != NO_ERROR: %d", res);
5153 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5154 "Camera session encountered error");
5155 }
5156 }
Cliff Wu3b268182021-07-06 15:44:43 +08005157 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005158 return binder::Status::ok();
5159}
5160
5161// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005162
5163static const int kDumpLockRetries = 50;
5164static const int kDumpLockSleep = 60000;
5165
5166static bool tryLock(Mutex& mutex)
5167{
5168 bool locked = false;
5169 for (int i = 0; i < kDumpLockRetries; ++i) {
5170 if (mutex.tryLock() == NO_ERROR) {
5171 locked = true;
5172 break;
5173 }
5174 usleep(kDumpLockSleep);
5175 }
5176 return locked;
5177}
5178
Rucha Katakwardf223072021-06-15 10:21:00 -07005179void CameraService::cacheDump() {
5180 if (mMemFd != -1) {
5181 const Vector<String16> args;
5182 ATRACE_CALL();
5183 // Acquiring service lock here will avoid the deadlock since
5184 // cacheDump will not be called during the second disconnect.
5185 Mutex::Autolock lock(mServiceLock);
5186
5187 Mutex::Autolock l(mCameraStatesLock);
5188 // Start collecting the info for open sessions and store it in temp file.
5189 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005190 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005191 auto clientDescriptor = mActiveClientManager.get(cameraId);
5192 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005193 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005194 // Log the current open session info before device is disconnected.
5195 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5196 }
5197 }
5198 }
5199}
5200
Mathias Agopian65ab4712010-07-14 17:59:35 -07005201status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005202 ATRACE_CALL();
5203
Austin Borgered99f642023-06-01 16:51:35 -07005204 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005205 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07005206 CameraThreadState::getCallingPid(),
5207 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005208 return NO_ERROR;
5209 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005210 bool locked = tryLock(mServiceLock);
5211 // failed to lock - CameraService is probably deadlocked
5212 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005213 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005214 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005215
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005216 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005217 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005218
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005219 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005220 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005221
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005222 if (locked) mServiceLock.unlock();
5223 return NO_ERROR;
5224 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005225 dprintf(fd, "\n== Service global info: ==\n\n");
5226 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005227 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005228 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5229 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005230 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5231 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5232 }
Austin Borgered99f642023-06-01 16:51:35 -07005233 std::string activeClientString = mActiveClientManager.toString();
5234 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5235 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005236 if (mStreamUseCaseOverrides.size() > 0) {
5237 dprintf(fd, "Active stream use case overrides:");
5238 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5239 dprintf(fd, " %" PRId64, useCaseOverride);
5240 }
5241 dprintf(fd, "\n");
5242 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005243
5244 dumpEventLog(fd);
5245
5246 bool stateLocked = tryLock(mCameraStatesLock);
5247 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005248 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005249 }
5250
Emilian Peevbd8c5032018-02-14 23:05:40 +00005251 int argSize = args.size();
5252 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005253 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005254 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005255 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005256 }
5257 break;
5258 }
5259 }
5260
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005261 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005262 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005263
Austin Borgered99f642023-06-01 16:51:35 -07005264 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005265
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005266 CameraParameters p = state.second->getShimParams();
5267 if (!p.isEmpty()) {
5268 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5269 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005270 }
5271
5272 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005273 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005274 // log the current open session info
5275 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005276 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005277 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005278 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005279
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005280 }
5281
5282 if (stateLocked) mCameraStatesLock.unlock();
5283
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005284 if (locked) mServiceLock.unlock();
5285
Emilian Peevf53f66e2017-04-11 14:29:43 +01005286 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005287
5288 dprintf(fd, "\n== Vendor tags: ==\n\n");
5289
5290 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5291 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005292 sp<VendorTagDescriptorCache> cache =
5293 VendorTagDescriptorCache::getGlobalVendorTagCache();
5294 if (cache == NULL) {
5295 dprintf(fd, "No vendor tags.\n");
5296 } else {
5297 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5298 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005299 } else {
5300 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5301 }
5302
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005303 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005304 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005305 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005306
5307 // Process dump arguments, if any
5308 int n = args.size();
5309 String16 verboseOption("-v");
5310 String16 unreachableOption("--unreachable");
5311 for (int i = 0; i < n; i++) {
5312 if (args[i] == verboseOption) {
5313 // change logging level
5314 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005315 std::string levelStr = toStdString(args[i+1]);
5316 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005317 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005318 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005319 } else if (args[i] == unreachableOption) {
5320 // Dump memory analysis
5321 // TODO - should limit be an argument parameter?
5322 UnreachableMemoryInfo info;
5323 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5324 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005325 dprintf(fd, "\n== Unable to dump unreachable memory. "
5326 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005327 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005328 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005329 std::string s = info.ToString(/*log_contents*/ true);
5330 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005331 }
5332 }
5333 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005334
5335 bool serviceLocked = tryLock(mServiceLock);
5336
5337 // Dump info from previous open sessions.
5338 // Reposition the offset to beginning of the file before reading
5339
5340 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5341 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5342 ssize_t size_read;
5343 char buf[4096];
5344 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5345 // Read data from file to a small buffer and write it to fd.
5346 write(fd, buf, size_read);
5347 if (size_read == -1) {
5348 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5349 break;
5350 }
5351 }
5352 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5353 } else {
5354 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5355 }
5356
5357 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005358 return NO_ERROR;
5359}
5360
Rucha Katakwardf223072021-06-15 10:21:00 -07005361void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005362 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005363 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005364 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005365 getFormattedCurrentTime().c_str(),
5366 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005367 dprintf(fd, " Client priority score: %d state: %d\n",
5368 clientDescriptor->getPriority().getScore(),
5369 clientDescriptor->getPriority().getState());
5370 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5371
5372 auto client = clientDescriptor->getValue();
5373 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005374 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005375
5376 client->dumpClient(fd, args);
5377}
5378
Austin Borgered99f642023-06-01 16:51:35 -07005379void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005380 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005381 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005382}
5383
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005384void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005385 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005386
5387 Mutex::Autolock l(mLogLock);
5388 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005389 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005390 }
5391
5392 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005393 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005394 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005395 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005396 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005397 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005398}
5399
Austin Borgered99f642023-06-01 16:51:35 -07005400void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005401 Mutex::Autolock lock(mLogLock);
5402 if (!isClientWatchedLocked(client)) { return; }
5403
5404 std::vector<std::string> dumpVector;
5405 client->dumpWatchedEventsToVector(dumpVector);
5406
5407 if (dumpVector.empty()) { return; }
5408
Austin Borgered99f642023-06-01 16:51:35 -07005409 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005410
Austin Borgered99f642023-06-01 16:51:35 -07005411 std::string currentTime = getFormattedCurrentTime();
5412 dumpString << "Cached @ ";
5413 dumpString << currentTime;
5414 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005415
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005416 size_t i = dumpVector.size();
5417
5418 // Store the string in reverse order (latest last)
5419 while (i > 0) {
5420 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005421 dumpString << cameraId;
5422 dumpString << ":";
5423 dumpString << client->getPackageName();
5424 dumpString << " ";
5425 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005426 }
5427
Austin Borgered99f642023-06-01 16:51:35 -07005428 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005429}
5430
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005431void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005432 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005433 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5434 if (mTorchClientMap[i] == who) {
5435 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005436 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005437 status_t res = mFlashlight->setTorchMode(cameraId, false);
5438 if (res) {
5439 ALOGE("%s: torch client died but couldn't turn off torch: "
5440 "%s (%d)", __FUNCTION__, strerror(-res), res);
5441 return;
5442 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005443 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005444 break;
5445 }
5446 }
5447}
5448
Ruben Brunkcc776712015-02-17 20:18:47 -08005449/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005450
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005451 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005452 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5453 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005454 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005455 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005456 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005457
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005458 // check torch client
5459 handleTorchClientBinderDied(who);
5460
5461 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005462 if(!evictClientIdByRemote(who)) {
5463 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005464 return;
5465 }
5466
Ruben Brunkcc776712015-02-17 20:18:47 -08005467 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5468 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005469}
5470
Austin Borgered99f642023-06-01 16:51:35 -07005471void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005472 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005473}
5474
Austin Borgered99f642023-06-01 16:51:35 -07005475void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005476 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005477 // Do not lock mServiceLock here or can get into a deadlock from
5478 // connect() -> disconnect -> updateStatus
5479
5480 auto state = getCameraState(cameraId);
5481
5482 if (state == nullptr) {
5483 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005484 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005485 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005486 }
5487
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005488 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5489 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5490 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005491 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005492 return;
5493 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005494
5495 // Collect the logical cameras without holding mStatusLock in updateStatus
5496 // as that can lead to a deadlock(b/162192331).
5497 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005498 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005499 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005500 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005501 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005502 (const std::string& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005503
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005504 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005505 // Update torch status if it has a flash unit.
5506 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005507 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005508 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5509 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005510 TorchModeStatus newTorchStatus =
5511 status == StatusInternal::PRESENT ?
5512 TorchModeStatus::AVAILABLE_OFF :
5513 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005514 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005515 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005516 }
5517 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005518 }
5519
5520 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005521 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005522 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005523
Ruben Brunkcc776712015-02-17 20:18:47 -08005524 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005525 bool isVendorListener = listener->isVendorListener();
5526 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5527 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07005528 isVendorListener) {
5529 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005530 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005531 continue;
5532 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005533 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005534 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005535 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005536 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005537 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5538 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005539 // Also trigger the callbacks for cameras that were remapped to the current
5540 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005541 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005542 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5543 for (auto& remappedCameraId : remappedCameraIds) {
5544 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005545 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005546 listener->handleBinderStatus(ret,
5547 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5548 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5549 ret.exceptionCode());
5550 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005551 }
5552 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005553}
5554
Austin Borgered99f642023-06-01 16:51:35 -07005555void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5556 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005557 auto state = getCameraState(cameraId);
5558 if (state == nullptr) {
5559 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005560 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005561 return;
5562 }
5563 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005564 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005565 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005566 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005567 }
5568
Shuzhen Wang695044d2020-03-06 09:02:23 -08005569 Mutex::Autolock lock(mStatusListenerLock);
5570
5571 for (const auto& it : mListenerList) {
5572 if (!it->isOpenCloseCallbackAllowed()) {
5573 continue;
5574 }
5575
5576 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005577 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005578 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005579 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005580 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005581 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005582
5583 it->handleBinderStatus(ret,
5584 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5585 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005586 }
5587}
5588
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005589template<class Func>
5590void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005591 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005592 std::initializer_list<StatusInternal> rejectSourceStates,
5593 Func onStatusUpdatedLocked) {
5594 Mutex::Autolock lock(mStatusLock);
5595 StatusInternal oldStatus = mStatus;
5596 mStatus = status;
5597
5598 if (oldStatus == status) {
5599 return;
5600 }
5601
5602 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005603 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005604
5605 if (oldStatus == StatusInternal::NOT_PRESENT &&
5606 (status != StatusInternal::PRESENT &&
5607 status != StatusInternal::ENUMERATING)) {
5608
5609 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5610 __FUNCTION__);
5611 mStatus = oldStatus;
5612 return;
5613 }
5614
5615 /**
5616 * Sometimes we want to conditionally do a transition.
5617 * For example if a client disconnects, we want to go to PRESENT
5618 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5619 */
5620 for (auto& rejectStatus : rejectSourceStates) {
5621 if (oldStatus == rejectStatus) {
5622 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005623 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005624 mStatus = oldStatus;
5625 return;
5626 }
5627 }
5628
5629 onStatusUpdatedLocked(cameraId, status);
5630}
5631
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005632status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005633 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005634 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005635 if (!status) {
5636 return BAD_VALUE;
5637 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005638 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5639 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005640 // invalid camera ID or the camera doesn't have a flash unit
5641 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005642 }
5643
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005644 *status = mTorchStatusMap.valueAt(index);
5645 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005646}
5647
Austin Borgered99f642023-06-01 16:51:35 -07005648status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005649 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005650 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5651 if (index == NAME_NOT_FOUND) {
5652 return BAD_VALUE;
5653 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005654 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005655
5656 return OK;
5657}
5658
Austin Borgered99f642023-06-01 16:51:35 -07005659std::list<std::string> CameraService::getLogicalCameras(
5660 const std::string& physicalCameraId) {
5661 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005662 Mutex::Autolock lock(mCameraStatesLock);
5663 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005664 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5665 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005666 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005667 }
5668 return retList;
5669}
5670
5671void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005672 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005673 SystemCameraKind deviceKind) {
5674 // mStatusListenerLock is expected to be locked
5675 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005676 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005677 // Note: we check only the deviceKind of the physical camera id
5678 // since, logical camera ids and their physical camera ids are
5679 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005680 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5681 listener->getListenerPid(), listener->getListenerUid())) {
5682 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005683 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005684 continue;
5685 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005686 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005687 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005688 listener->handleBinderStatus(ret,
5689 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5690 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5691 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005692 }
5693 }
5694}
5695
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005696
Svet Ganova453d0d2018-01-11 15:37:58 -08005697void CameraService::blockClientsForUid(uid_t uid) {
5698 const auto clients = mActiveClientManager.getAll();
5699 for (auto& current : clients) {
5700 if (current != nullptr) {
5701 const auto basicClient = current->getValue();
5702 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5703 basicClient->block();
5704 }
5705 }
5706 }
5707}
5708
Michael Grooverd1d435a2018-12-18 17:39:42 -08005709void CameraService::blockAllClients() {
5710 const auto clients = mActiveClientManager.getAll();
5711 for (auto& current : clients) {
5712 if (current != nullptr) {
5713 const auto basicClient = current->getValue();
5714 if (basicClient.get() != nullptr) {
5715 basicClient->block();
5716 }
5717 }
5718 }
5719}
5720
Svet Ganova453d0d2018-01-11 15:37:58 -08005721// NOTE: This is a remote API - make sure all args are validated
5722status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005723 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005724 return PERMISSION_DENIED;
5725 }
5726 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5727 return BAD_VALUE;
5728 }
Austin Borgered99f642023-06-01 16:51:35 -07005729 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005730 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005731 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005732 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005733 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005734 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005735 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005736 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005737 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005738 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005739 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005740 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005741 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005742 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005743 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005744 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005745 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005746 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005747 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005748 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005749 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005750 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005751 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005752 handleClearStreamUseCaseOverrides();
5753 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005754 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005755 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005756 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005757 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005758 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005759 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005760 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005761 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005762 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005763 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005764 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005765 }
5766 printHelp(err);
5767 return BAD_VALUE;
5768}
5769
malikakash82ed4352023-07-21 22:44:34 +00005770status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5771 uid_t uid = IPCThreadState::self()->getCallingUid();
5772 if (uid != AID_ROOT) {
5773 dprintf(err, "Must be adb root\n");
5774 return PERMISSION_DENIED;
5775 }
5776 if (args.size() != 4) {
5777 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5778 return BAD_VALUE;
5779 }
Austin Borgered99f642023-06-01 16:51:35 -07005780 std::string packageName = toStdString(args[1]);
5781 std::string cameraIdToReplace = toStdString(args[2]);
5782 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005783 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5784 return OK;
5785}
5786
Svet Ganova453d0d2018-01-11 15:37:58 -08005787status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005788 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005789
Svet Ganova453d0d2018-01-11 15:37:58 -08005790 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005791 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005792 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005793 } else if ((args[2] != toString16("idle"))) {
5794 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005795 return BAD_VALUE;
5796 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005797
5798 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005799 if (args.size() >= 5 && args[3] == toString16("--user")) {
5800 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005801 }
5802
5803 uid_t uid;
5804 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5805 return BAD_VALUE;
5806 }
5807
5808 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005809 return NO_ERROR;
5810}
5811
5812status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005813 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005814
5815 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005816 if (args.size() >= 4 && args[2] == toString16("--user")) {
5817 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005818 }
5819
5820 uid_t uid;
5821 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005822 return BAD_VALUE;
5823 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005824
5825 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005826 return NO_ERROR;
5827}
5828
5829status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005830 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005831
5832 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005833 if (args.size() >= 4 && args[2] == toString16("--user")) {
5834 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005835 }
5836
5837 uid_t uid;
5838 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005839 return BAD_VALUE;
5840 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005841
5842 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005843 return dprintf(out, "active\n");
5844 } else {
5845 return dprintf(out, "idle\n");
5846 }
5847}
5848
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005849status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005850 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005851 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5852 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5853 Mutex::Autolock lock(mServiceLock);
5854
5855 mOverrideRotateAndCropMode = rotateValue;
5856
5857 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5858
5859 const auto clients = mActiveClientManager.getAll();
5860 for (auto& current : clients) {
5861 if (current != nullptr) {
5862 const auto basicClient = current->getValue();
5863 if (basicClient.get() != nullptr) {
5864 basicClient->setRotateAndCropOverride(rotateValue);
5865 }
5866 }
5867 }
5868
5869 return OK;
5870}
5871
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005872status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5873 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005874 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005875 if ((*end != '\0') ||
5876 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5877 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5878 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5879 return BAD_VALUE;
5880 }
5881
5882 Mutex::Autolock lock(mServiceLock);
5883 mOverrideAutoframingMode = autoframingValue;
5884
5885 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5886
5887 const auto clients = mActiveClientManager.getAll();
5888 for (auto& current : clients) {
5889 if (current != nullptr) {
5890 const auto basicClient = current->getValue();
5891 if (basicClient.get() != nullptr) {
5892 basicClient->setAutoframingOverride(autoframingValue);
5893 }
5894 }
5895 }
5896
5897 return OK;
5898}
5899
Ravneetaeb20dc2022-03-30 05:33:03 +00005900status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005901 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005902
5903 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5904
5905 Mutex::Autolock lock(mServiceLock);
5906
5907 mCameraServiceWatchdogEnabled = enableWatchdog;
5908
5909 const auto clients = mActiveClientManager.getAll();
5910 for (auto& current : clients) {
5911 if (current != nullptr) {
5912 const auto basicClient = current->getValue();
5913 if (basicClient.get() != nullptr) {
5914 basicClient->setCameraServiceWatchdog(enableWatchdog);
5915 }
5916 }
5917 }
5918
5919 return OK;
5920}
5921
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005922status_t CameraService::handleGetRotateAndCrop(int out) {
5923 Mutex::Autolock lock(mServiceLock);
5924
5925 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5926}
5927
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005928status_t CameraService::handleGetAutoframing(int out) {
5929 Mutex::Autolock lock(mServiceLock);
5930
5931 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5932}
5933
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005934status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5935 char *endPtr;
5936 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005937 std::string maskString = toStdString(args[1]);
5938 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005939
5940 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005941 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005942 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5943
5944 Mutex::Autolock lock(mServiceLock);
5945
5946 mImageDumpMask = maskValue;
5947
5948 return OK;
5949}
5950
5951status_t CameraService::handleGetImageDumpMask(int out) {
5952 Mutex::Autolock lock(mServiceLock);
5953
5954 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5955}
5956
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005957status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005958 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005959 if (errno != 0) return BAD_VALUE;
5960
5961 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5962 Mutex::Autolock lock(mServiceLock);
5963
5964 mOverrideCameraMuteMode = (muteValue == 1);
5965
5966 const auto clients = mActiveClientManager.getAll();
5967 for (auto& current : clients) {
5968 if (current != nullptr) {
5969 const auto basicClient = current->getValue();
5970 if (basicClient.get() != nullptr) {
5971 if (basicClient->supportsCameraMute()) {
5972 basicClient->setCameraMute(mOverrideCameraMuteMode);
5973 }
5974 }
5975 }
5976 }
5977
5978 return OK;
5979}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005980
Shuzhen Wang16610a62022-12-15 22:38:07 -08005981status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5982 std::vector<int64_t> useCasesOverride;
5983 for (size_t i = 1; i < args.size(); i++) {
5984 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005985 std::string arg = toStdString(args[i]);
5986 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005987 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005988 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005989 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07005990 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005991 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07005992 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005993 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07005994 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005995 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07005996 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005997 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07005998 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005999 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6000 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006001 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006002 return BAD_VALUE;
6003 }
6004 useCasesOverride.push_back(useCase);
6005 }
6006
6007 Mutex::Autolock lock(mServiceLock);
6008 mStreamUseCaseOverrides = std::move(useCasesOverride);
6009
6010 return OK;
6011}
6012
6013void CameraService::handleClearStreamUseCaseOverrides() {
6014 Mutex::Autolock lock(mServiceLock);
6015 mStreamUseCaseOverrides.clear();
6016}
6017
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006018status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6019 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006020 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006021 if ((*end != '\0') ||
6022 (zoomOverrideValue != -1 &&
6023 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6024 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6025 return BAD_VALUE;
6026 }
6027
6028 Mutex::Autolock lock(mServiceLock);
6029 mZoomOverrideValue = zoomOverrideValue;
6030
6031 const auto clients = mActiveClientManager.getAll();
6032 for (auto& current : clients) {
6033 if (current != nullptr) {
6034 const auto basicClient = current->getValue();
6035 if (basicClient.get() != nullptr) {
6036 if (basicClient->supportsZoomOverride()) {
6037 basicClient->setZoomOverride(mZoomOverrideValue);
6038 }
6039 }
6040 }
6041 }
6042
6043 return OK;
6044}
6045
Avichal Rakesh84147132021-11-11 17:47:11 -08006046status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006047 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006048 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006049 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006050 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006051 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006052 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006053 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006054 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006055 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006056 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006057 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006058 dprintf(outFd, "Camera service watch commands:\n"
6059 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6060 " starts watching the provided tags for clients with provided package\n"
6061 " recognizes tag shorthands like '3a'\n"
6062 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006063 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006064 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006065 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006066 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006067 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006068 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006069 return BAD_VALUE;
6070}
6071
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006072status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6073 Mutex::Autolock lock(mLogLock);
6074 size_t tagsIdx; // index of '-m'
6075 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006076 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006077 if (tagsIdx < args.size() - 1) {
6078 tags = args[tagsIdx + 1];
6079 } else {
6080 dprintf(outFd, "No tags provided.\n");
6081 return BAD_VALUE;
6082 }
6083
6084 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006085 // watch all clients if no clients are provided
6086 String16 clients = toString16(kWatchAllClientsFlag);
6087 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006088 clientsIdx++);
6089 if (clientsIdx < args.size() - 1) {
6090 clients = args[clientsIdx + 1];
6091 }
Austin Borgered99f642023-06-01 16:51:35 -07006092 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006093
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006094 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006095 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006096
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006097 bool serviceLock = tryLock(mServiceLock);
6098 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006099 auto cameraClients = mActiveClientManager.getAll();
6100 for (const auto &clientDescriptor: cameraClients) {
6101 if (clientDescriptor == nullptr) { continue; }
6102 sp<BasicClient> client = clientDescriptor->getValue();
6103 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006104
6105 if (isClientWatchedLocked(client.get())) {
6106 client->startWatchingTags(mMonitorTags, outFd);
6107 numWatchedClients++;
6108 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006109 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006110 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6111
6112 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006113 return OK;
6114}
6115
6116status_t CameraService::stopWatchingTags(int outFd) {
6117 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006118 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006119 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006120
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006121 mWatchedClientPackages.clear();
6122 mWatchedClientsDumpCache.clear();
6123
6124 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006125 auto cameraClients = mActiveClientManager.getAll();
6126 for (const auto &clientDescriptor : cameraClients) {
6127 if (clientDescriptor == nullptr) { continue; }
6128 sp<BasicClient> client = clientDescriptor->getValue();
6129 if (client.get() == nullptr) { continue; }
6130 client->stopWatchingTags(outFd);
6131 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006132 dprintf(outFd, "Stopped watching all clients.\n");
6133 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006134 return OK;
6135}
6136
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006137status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6138 Mutex::Autolock lock(mLogLock);
6139 size_t clearedSize = mWatchedClientsDumpCache.size();
6140 mWatchedClientsDumpCache.clear();
6141 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6142 return OK;
6143}
6144
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006145status_t CameraService::printWatchedTags(int outFd) {
6146 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006147 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006148
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006149 bool printedSomething = false; // tracks if any monitoring information was printed
6150 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006151
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006152 bool serviceLock = tryLock(mServiceLock);
6153 // get all watched clients that are currently connected
6154 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6155 if (clientDescriptor == nullptr) { continue; }
6156
6157 sp<BasicClient> client = clientDescriptor->getValue();
6158 if (client.get() == nullptr) { continue; }
6159 if (!isClientWatchedLocked(client.get())) { continue; }
6160
6161 std::vector<std::string> dumpVector;
6162 client->dumpWatchedEventsToVector(dumpVector);
6163
6164 size_t printIdx = dumpVector.size();
6165 if (printIdx == 0) {
6166 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006167 }
6168
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006169 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006170 const std::string &cameraId = clientDescriptor->getKey();
6171 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006172 while(printIdx > 0) {
6173 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006174 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006175 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006176 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006177 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006178 printedSomething = true;
6179
6180 connectedMonitoredClients.emplace(client->getPackageName());
6181 }
6182 if (serviceLock) { mServiceLock.unlock(); }
6183
6184 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6185 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006186 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006187 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6188 continue;
6189 }
6190
Austin Borgered99f642023-06-01 16:51:35 -07006191 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006192 dprintf(outFd, "%s\n", kv.second.c_str());
6193 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006194 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006195
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006196 if (!printedSomething) {
6197 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006198 }
6199
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006200 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006201}
6202
Avichal Rakesh84147132021-11-11 17:47:11 -08006203// Print all events in vector `events' that came after lastPrintedEvent
6204void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006205 const std::string &cameraId,
6206 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006207 const std::vector<std::string> &events,
6208 const std::string &lastPrintedEvent) {
6209 if (events.empty()) { return; }
6210
6211 // index of lastPrintedEvent in events.
6212 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6213 size_t lastPrintedIdx;
6214 for (lastPrintedIdx = 0;
6215 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6216 lastPrintedIdx++);
6217
6218 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6219
Avichal Rakesh84147132021-11-11 17:47:11 -08006220 // print events in chronological order (latest event last)
6221 size_t idxToPrint = lastPrintedIdx;
6222 do {
6223 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006224 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6225 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006226 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006227}
6228
6229// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6230// command should be interrupted if the user presses the return key, or if user loses any way to
6231// signal interrupt.
6232// If timeoutMs == 0, this function will always return false
6233bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6234 struct timeval startTime;
6235 int startTimeError = gettimeofday(&startTime, nullptr);
6236 if (startTimeError) {
6237 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6238 return true;
6239 }
6240
6241 const nfds_t numFds = 1;
6242 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6243
6244 struct timeval currTime;
6245 char buffer[2];
6246 while(true) {
6247 int currTimeError = gettimeofday(&currTime, nullptr);
6248 if (currTimeError) {
6249 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6250 return true;
6251 }
6252
6253 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6254 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6255 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6256
6257 if (remainingTimeMs <= 0) {
6258 // No user interrupt within timeoutMs, don't interrupt watch command
6259 return false;
6260 }
6261
6262 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6263 if (numFdsUpdated < 0) {
6264 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6265 return true;
6266 }
6267
6268 if (numFdsUpdated == 0) {
6269 // No user input within timeoutMs, don't interrupt watch command
6270 return false;
6271 }
6272
6273 if (!(pollFd.revents & POLLIN)) {
6274 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6275 return true;
6276 }
6277
6278 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6279 if (sizeRead < 0) {
6280 dprintf(outFd, "Error reading user input. Exiting.\n");
6281 return true;
6282 }
6283
6284 if (sizeRead == 0) {
6285 // Reached end of input fd (can happen if input is piped)
6286 // User has no way to signal an interrupt, so interrupt here
6287 return true;
6288 }
6289
6290 if (buffer[0] == '\n') {
6291 // User pressed return, interrupt watch command.
6292 return true;
6293 }
6294 }
6295}
6296
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006297status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6298 int inFd, int outFd) {
6299 // Figure out refresh interval, if present in args
6300 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006301 if (args.size() > 2) {
6302 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006303 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006304 intervalIdx++);
6305
6306 size_t intervalValIdx = intervalIdx + 1;
6307 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006308 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006309 if (errno) { return BAD_VALUE; }
6310 }
6311 }
6312
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006313 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6314 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006315
Avichal Rakesh84147132021-11-11 17:47:11 -08006316 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006317 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006318
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006319 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006320 bool serviceLock = tryLock(mServiceLock);
6321 auto cameraClients = mActiveClientManager.getAll();
6322 if (serviceLock) { mServiceLock.unlock(); }
6323
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006324 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006325 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006326 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006327
6328 sp<BasicClient> client = clientDescriptor->getValue();
6329 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006330 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006331
Austin Borgered99f642023-06-01 16:51:35 -07006332 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006333 // This also initializes the map entries with an empty string
6334 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6335
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006336 std::vector<std::string> latestEvents;
6337 client->dumpWatchedEventsToVector(latestEvents);
6338
6339 if (!latestEvents.empty()) {
6340 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006341 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006342 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006343 latestEvents,
6344 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006345 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006346 }
6347 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006348 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006349 break;
6350 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006351 }
6352 return OK;
6353}
6354
Austin Borgered99f642023-06-01 16:51:35 -07006355void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006356 mWatchedClientPackages.clear();
6357
Austin Borgered99f642023-06-01 16:51:35 -07006358 std::istringstream iss(clients);
6359 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006360
Austin Borgered99f642023-06-01 16:51:35 -07006361 while (std::getline(iss, nextClient, ',')) {
6362 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006363 // Don't need to track any other package if 'all' is present
6364 mWatchedClientPackages.clear();
6365 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6366 break;
6367 }
6368
6369 // track package names
6370 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006371 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006372}
6373
Svet Ganova453d0d2018-01-11 15:37:58 -08006374status_t CameraService::printHelp(int out) {
6375 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006376 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6377 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6378 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006379 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6380 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6381 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006382 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6383 " Valid values 0=false, 1=true, 2=auto\n"
6384 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006385 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6386 " Valid values 0=OFF, 1=ON for JPEG\n"
6387 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006388 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006389 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6390 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6391 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6392 " on. In case the number of usecases is smaller than the number of streams, the\n"
6393 " last use case is assigned to all the remaining streams. In case of multiple\n"
6394 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6395 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6396 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6397 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006398 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6399 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006400 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6401 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006402 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006403 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006404 " help print this message\n");
6405}
6406
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006407bool CameraService::isClientWatched(const BasicClient *client) {
6408 Mutex::Autolock lock(mLogLock);
6409 return isClientWatchedLocked(client);
6410}
6411
6412bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6413 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6414 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6415}
6416
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006417int32_t CameraService::updateAudioRestriction() {
6418 Mutex::Autolock lock(mServiceLock);
6419 return updateAudioRestrictionLocked();
6420}
6421
6422int32_t CameraService::updateAudioRestrictionLocked() {
6423 int32_t mode = 0;
6424 // iterate through all active client
6425 for (const auto& i : mActiveClientManager.getAll()) {
6426 const auto clientSp = i->getValue();
6427 mode |= clientSp->getAudioRestriction();
6428 }
6429
6430 bool modeChanged = (mAudioRestriction != mode);
6431 mAudioRestriction = mode;
6432 if (modeChanged) {
6433 mAppOps.setCameraAudioRestriction(mode);
6434 }
6435 return mode;
6436}
6437
Austin Borgered99f642023-06-01 16:51:35 -07006438status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006439 sp<BasicClient> clientSp) {
6440 std::unique_ptr<AutoConditionLock> lock =
6441 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6442 status_t res = NO_ERROR;
6443 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006444 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006445 mInjectionStatusListener->notifyInjectionError(
6446 externalCamId, UNKNOWN_TRANSACTION);
6447 clientSp->notifyError(
6448 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6449 CaptureResultExtras());
6450
6451 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6452 // other clients from connecting in mServiceLockWrapper if held
6453 mServiceLock.unlock();
6454
6455 // Clear caller identity temporarily so client disconnect PID checks work correctly
6456 int64_t token = CameraThreadState::clearCallingIdentity();
6457 clientSp->disconnect();
6458 CameraThreadState::restoreCallingIdentity(token);
6459
6460 // Reacquire mServiceLock
6461 mServiceLock.lock();
6462 }
6463
6464 return res;
6465}
6466
Cliff Wud3a05312021-04-26 23:07:31 +08006467void CameraService::clearInjectionParameters() {
6468 {
6469 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006470 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006471 mInjectionInternalCamId = "";
6472 }
6473 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006474 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006475}
6476
Mathias Agopian65ab4712010-07-14 17:59:35 -07006477}; // namespace android