blob: 4545efc4283ad8f18b9e559e294e15fd6a11d7f7 [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
malikakash82ed4352023-07-21 22:44:34 +0000987Status CameraService::parseCameraIdRemapping(
988 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +0000989 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -0700990 std::string packageName;
991 std::string cameraIdToReplace, updatedCameraId;
malikakash214f6e62023-08-10 23:50:56 +0000992 for(const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +0000993 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +0000994 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +0000995 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
996 "CameraIdRemapping: Package name cannot be empty");
997 }
malikakash214f6e62023-08-10 23:50:56 +0000998 if (packageIdRemapping.cameraIdsToReplace.size()
999 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001000 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1001 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001002 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001003 }
malikakash214f6e62023-08-10 23:50:56 +00001004 for(size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001005 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1006 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001007 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001008 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1009 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001010 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001011 }
1012 if (cameraIdToReplace == updatedCameraId) {
1013 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1014 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1015 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001016 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001017 }
1018 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001019 }
1020 }
1021 return Status::ok();
1022}
1023
1024void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1025 // Acquire mServiceLock and prevent other clients from connecting
1026 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1027 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1028
malikakashedb38962023-09-06 00:03:35 +00001029 // Collect all existing clients for camera Ids that are being
1030 // remapped in the new cameraIdRemapping, but only if they were being used by a
1031 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001032 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001033 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001034 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1035 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001036 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001037 id0.c_str(), id1.c_str());
1038 auto clientDescriptor = mActiveClientManager.get(id0);
1039 if (clientDescriptor != nullptr) {
1040 sp<BasicClient> clientSp = clientDescriptor->getValue();
1041 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001042 // This camera is being used by a targeted packageName and
1043 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001044 clientsToDisconnect.push_back(clientSp);
1045 cameraIdsToUpdate.push_back(id0);
1046 }
1047 }
1048 }
1049 }
1050
malikakashedb38962023-09-06 00:03:35 +00001051 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001052 // Notify the clients about the disconnection.
1053 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001054 CaptureResultExtras{});
1055 }
malikakash82ed4352023-07-21 22:44:34 +00001056
1057 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1058 // blocking other clients from connecting in mServiceLockWrapper if held.
1059 mServiceLock.unlock();
1060
malikakashedb38962023-09-06 00:03:35 +00001061 // Clear calling identity for disconnect() PID checks.
1062 int64_t token = CameraThreadState::clearCallingIdentity();
1063
malikakash82ed4352023-07-21 22:44:34 +00001064 // Disconnect clients.
1065 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001066 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1067 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001068 clientSp->disconnect();
1069 }
1070
malikakashedb38962023-09-06 00:03:35 +00001071 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1072 clientsToDisconnect.clear();
1073
1074 CameraThreadState::restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001075 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001076
1077 {
1078 Mutex::Autolock lock(mCameraIdRemappingLock);
1079 // Update mCameraIdRemapping.
1080 mCameraIdRemapping.clear();
1081 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1082 }
malikakash82ed4352023-07-21 22:44:34 +00001083}
1084
malikakash22af94c2023-12-04 18:13:14 +00001085Status CameraService::injectSessionParams(
1086 const std::string& cameraId,
1087 const CameraMetadata& sessionParams) {
1088 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
1089 const int pid = CameraThreadState::getCallingPid();
1090 const int uid = CameraThreadState::getCallingUid();
1091 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1092 __FUNCTION__, pid, uid);
1093 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1094 "Permission Denial: no permission to inject session params");
1095 }
1096
1097 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1098 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1099
1100 auto clientDescriptor = mActiveClientManager.get(cameraId);
1101 if (clientDescriptor == nullptr) {
1102 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1103 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1104 "No active client for camera id %s", cameraId.c_str());
1105 }
1106
1107 sp<BasicClient> clientSp = clientDescriptor->getValue();
1108 status_t res = clientSp->injectSessionParams(sessionParams);
1109
1110 if (res != OK) {
1111 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1112 "Error injecting session params into camera \"%s\": %s (%d)",
1113 cameraId.c_str(), strerror(-res), res);
1114 }
1115 return Status::ok();
1116}
1117
Austin Borgered99f642023-06-01 16:51:35 -07001118std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1119 const std::string& inputCameraId, int clientUid) {
1120 std::string packageName = getPackageNameFromUid(clientUid);
1121 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001122 Mutex::Autolock lock(mCameraIdRemappingLock);
1123 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1124 packageMapIter != mCameraIdRemapping.end()) {
1125 for (auto& [id0, id1]: packageMapIter->second) {
1126 if (id1 == inputCameraId) {
1127 cameraIds.push_back(id0);
1128 }
1129 }
1130 }
1131 return cameraIds;
1132}
1133
Austin Borgered99f642023-06-01 16:51:35 -07001134std::string CameraService::resolveCameraId(
1135 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001136 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001137 const std::string& packageName) {
1138 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001139 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001140 packageNameVal = getPackageNameFromUid(clientUid);
1141 }
malikakash65d20692023-09-07 01:06:33 +00001142 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001143 // We shouldn't remap cameras for processes with system/vendor UIDs.
1144 return inputCameraId;
1145 }
malikakash82ed4352023-07-21 22:44:34 +00001146 Mutex::Autolock lock(mCameraIdRemappingLock);
1147 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1148 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001149 auto packageMap = packageMapIter->second;
1150 if (auto replacementIdIter = packageMap.find(inputCameraId);
1151 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001152 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001153 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001154 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001155 replacementIdIter->second.c_str());
1156 return replacementIdIter->second;
1157 }
1158 }
1159 return inputCameraId;
1160}
1161
Austin Borger18b30a72022-10-27 12:20:29 -07001162Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait,
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001163 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001164 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001165 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001166 std::string unresolvedCameraId = cameraIdIntToStrLocked(cameraId);
1167 std::string cameraIdStr = resolveCameraId(
1168 unresolvedCameraId, CameraThreadState::getCallingUid());
1169
Austin Borgered99f642023-06-01 16:51:35 -07001170 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001171 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1172 "characteristics for system only device %s: ", cameraIdStr.c_str());
1173 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001174
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001175 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001176 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001177 return STATUS_ERROR(ERROR_DISCONNECTED,
1178 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001179 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001180 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001181 CameraThreadState::getCallingPid(), CameraThreadState::getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001182 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1183 if (hasSystemCameraPermissions) {
1184 cameraIdBound = mNumberOfCameras;
1185 }
1186 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001187 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1188 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001189 }
1190
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001191 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001192 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001193 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001194 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001195 if (err != OK) {
1196 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1197 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1198 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001199 logServiceError(std::string("Error retrieving camera info from device ")
1200 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001201 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001202
Ruben Brunkcc776712015-02-17 20:18:47 -08001203 return ret;
1204}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001205
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001206std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001207 const std::vector<std::string> *deviceIds = &mNormalDeviceIdsWithoutSystemCamera;
1208 auto callingPid = CameraThreadState::getCallingPid();
1209 auto callingUid = CameraThreadState::getCallingUid();
Joanne Chung02c13d02023-01-16 12:58:05 +00001210 AttributionSourceState attributionSource{};
1211 attributionSource.pid = callingPid;
1212 attributionSource.uid = callingUid;
Austin Borger1c1bee02023-06-01 16:51:35 -07001213 bool checkPermissionForSystemCamera = checkPermission(std::to_string(cameraIdInt),
1214 sSystemCameraPermission, attributionSource, std::string(),
1215 AppOpsManager::OP_NONE);
Joanne Chung02c13d02023-01-16 12:58:05 +00001216 if (checkPermissionForSystemCamera || getpid() == callingPid) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001217 deviceIds = &mNormalDeviceIds;
1218 }
1219 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(deviceIds->size())) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001220 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001221 __FUNCTION__, cameraIdInt, deviceIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001222 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001223 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001224
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001225 return (*deviceIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001226}
1227
Austin Borgered99f642023-06-01 16:51:35 -07001228std::string CameraService::cameraIdIntToStr(int cameraIdInt) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001229 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001230 return cameraIdIntToStrLocked(cameraIdInt);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001231}
1232
Austin Borgered99f642023-06-01 16:51:35 -07001233Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001234 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001235 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001236
malikakashedb38962023-09-06 00:03:35 +00001237 const std::string cameraId = resolveCameraId(unresolvedCameraId,
1238 CameraThreadState::getCallingUid());
Austin Borgered99f642023-06-01 16:51:35 -07001239
Zhijun He2b59be82013-09-25 10:14:30 -07001240 if (!cameraInfo) {
1241 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001243 }
1244
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001245 if (!mInitialized) {
1246 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001247 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001248 return STATUS_ERROR(ERROR_DISCONNECTED,
1249 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001250 }
1251
Austin Borgered99f642023-06-01 16:51:35 -07001252 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001253 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001254 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001255 }
1256
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001257 Status ret{};
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001258
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001259 bool overrideForPerfClass =
1260 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001261 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001262 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001263 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001264 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001265 if (res == NAME_NOT_FOUND) {
1266 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001267 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001268 strerror(-res), res);
1269 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001270 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1271 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001272 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001273 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001274 strerror(-res), res);
1275 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001276 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001277 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Austin Borgered99f642023-06-01 16:51:35 -07001278 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1279 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001280 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera kind "
Austin Borgered99f642023-06-01 16:51:35 -07001281 "for device %s", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001282 }
Jayant Chowdhary12361932018-08-27 14:46:13 -07001283 int callingPid = CameraThreadState::getCallingPid();
1284 int callingUid = CameraThreadState::getCallingUid();
Emilian Peeve20c6372018-08-14 18:45:53 +01001285 std::vector<int32_t> tagsRemoved;
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001286 // If it's not calling from cameraserver, check the permission only if
1287 // android.permission.CAMERA is required. If android.permission.SYSTEM_CAMERA was needed,
1288 // it would've already been checked in shouldRejectSystemCameraConnection.
Joanne Chung02c13d02023-01-16 12:58:05 +00001289 AttributionSourceState attributionSource{};
1290 attributionSource.pid = callingPid;
1291 attributionSource.uid = callingUid;
Austin Borger1c1bee02023-06-01 16:51:35 -07001292 bool checkPermissionForCamera = checkPermission(cameraId, sCameraPermission,
1293 attributionSource, std::string(), AppOpsManager::OP_NONE);
Emilian Peeve20c6372018-08-14 18:45:53 +01001294 if ((callingPid != getpid()) &&
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001295 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001296 !checkPermissionForCamera) {
Emilian Peeve20c6372018-08-14 18:45:53 +01001297 res = cameraInfo->removePermissionEntries(
Austin Borgered99f642023-06-01 16:51:35 -07001298 mCameraProviderManager->getProviderTagIdLocked(cameraId),
Emilian Peeve20c6372018-08-14 18:45:53 +01001299 &tagsRemoved);
1300 if (res != OK) {
1301 cameraInfo->clear();
1302 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to remove camera"
1303 " characteristics needing camera permission for device %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07001304 cameraId.c_str(), strerror(-res), res);
Emilian Peeve20c6372018-08-14 18:45:53 +01001305 }
1306 }
1307
1308 if (!tagsRemoved.empty()) {
1309 res = cameraInfo->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1310 tagsRemoved.data(), tagsRemoved.size());
1311 if (res != OK) {
1312 cameraInfo->clear();
1313 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Failed to insert camera "
Austin Borgered99f642023-06-01 16:51:35 -07001314 "keys needing permission for device %s: %s (%d)", cameraId.c_str(),
Emilian Peeve20c6372018-08-14 18:45:53 +01001315 strerror(-res), res);
1316 }
1317 }
1318
Zhijun He2b59be82013-09-25 10:14:30 -07001319 return ret;
1320}
1321
malikakashedb38962023-09-06 00:03:35 +00001322Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -08001323 int32_t* torchStrength) {
1324 ATRACE_CALL();
1325 Mutex::Autolock l(mServiceLock);
malikakashedb38962023-09-06 00:03:35 +00001326 const std::string cameraId = resolveCameraId(
malikakash65d20692023-09-07 01:06:33 +00001327 unresolvedCameraId, CameraThreadState::getCallingUid());
Rucha Katakwar38284522021-11-10 11:25:21 -08001328 if (!mInitialized) {
1329 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1330 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1331 }
1332
1333 if(torchStrength == NULL) {
1334 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1335 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1336 }
1337
Austin Borgered99f642023-06-01 16:51:35 -07001338 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001339 if (res != OK) {
1340 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001341 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001342 strerror(-res), res);
1343 }
1344 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1345 return Status::ok();
1346}
1347
Austin Borgered99f642023-06-01 16:51:35 -07001348std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001349 time_t now = time(nullptr);
1350 char formattedTime[64];
1351 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001352 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001353}
1354
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001355Status CameraService::getCameraVendorTagDescriptor(
1356 /*out*/
1357 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001358 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001359 if (!mInitialized) {
1360 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001361 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001362 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001363 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1364 if (globalDescriptor != nullptr) {
1365 *desc = *(globalDescriptor.get());
1366 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001367 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001368}
1369
Emilian Peev71c73a22017-03-21 16:35:51 +00001370Status CameraService::getCameraVendorTagCache(
1371 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1372 ATRACE_CALL();
1373 if (!mInitialized) {
1374 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1375 return STATUS_ERROR(ERROR_DISCONNECTED,
1376 "Camera subsystem not available");
1377 }
1378 sp<VendorTagDescriptorCache> globalCache =
1379 VendorTagDescriptorCache::getGlobalVendorTagCache();
1380 if (globalCache != nullptr) {
1381 *cache = *(globalCache.get());
1382 }
1383 return Status::ok();
1384}
1385
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001386void CameraService::clearCachedVariables() {
1387 BasicClient::BasicClient::sCameraService = nullptr;
1388}
1389
Austin Borgered99f642023-06-01 16:51:35 -07001390std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001391 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001392 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001393
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001394 int deviceVersion = 0;
1395
Emilian Peevf53f66e2017-04-11 14:29:43 +01001396 status_t res;
1397 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001398 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001399 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001400 if (res != OK || transport == IPCTransport::INVALID) {
1401 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001402 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001403 return std::make_pair(-1, IPCTransport::INVALID) ;
1404 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001405 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001406
Emilian Peevf53f66e2017-04-11 14:29:43 +01001407 hardware::CameraInfo info;
1408 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001409 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001410 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001411 if (res != OK) {
1412 return std::make_pair(-1, IPCTransport::INVALID);
1413 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001414 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001415 if (orientation) {
1416 *orientation = info.orientation;
1417 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001418 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001419
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001420 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001421}
1422
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001423Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001424 switch(err) {
1425 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001426 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001427 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001428 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1429 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001430 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001431 return STATUS_ERROR(ERROR_DISCONNECTED,
1432 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001433 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001434 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1435 "Camera HAL encountered error %d: %s",
1436 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001437 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001438}
1439
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001440Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001441 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1442 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001443 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001444 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001445 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001446 bool forceSlowJpegMode, const std::string& originalCameraId,
1447 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001448 // For HIDL devices
1449 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1450 // Create CameraClient based on device version reported by the HAL.
1451 int deviceVersion = deviceVersionAndTransport.first;
1452 switch(deviceVersion) {
1453 case CAMERA_DEVICE_API_VERSION_1_0:
1454 ALOGE("Camera using old HAL version: %d", deviceVersion);
1455 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1456 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001457 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001458 break;
1459 case CAMERA_DEVICE_API_VERSION_3_0:
1460 case CAMERA_DEVICE_API_VERSION_3_1:
1461 case CAMERA_DEVICE_API_VERSION_3_2:
1462 case CAMERA_DEVICE_API_VERSION_3_3:
1463 case CAMERA_DEVICE_API_VERSION_3_4:
1464 case CAMERA_DEVICE_API_VERSION_3_5:
1465 case CAMERA_DEVICE_API_VERSION_3_6:
1466 case CAMERA_DEVICE_API_VERSION_3_7:
1467 break;
1468 default:
1469 // Should not be reachable
1470 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1471 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1472 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001473 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001474 }
1475 }
1476 if (effectiveApiLevel == API_1) { // Camera1 API route
1477 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001478 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borgered99f642023-06-01 16:51:35 -07001479 packageName, featureId, cameraId,
1480 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001481 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1482 forceSlowJpegMode);
1483 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1484 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001485 } else { // Camera2 API route
1486 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1487 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001488 *client = new CameraDeviceClient(cameraService, tmp,
1489 cameraService->mCameraServiceProxyWrapper, packageName, systemNativeClient,
1490 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001491 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001492 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001493 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001494 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001495}
1496
Austin Borgered99f642023-06-01 16:51:35 -07001497std::string CameraService::toString(std::set<userid_t> intSet) {
1498 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001499 bool first = true;
1500 for (userid_t i : intSet) {
1501 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001502 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001503 first = false;
1504 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001505 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001506 }
1507 }
Austin Borgered99f642023-06-01 16:51:35 -07001508 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001509}
1510
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001511int32_t CameraService::mapToInterface(TorchModeStatus status) {
1512 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1513 switch (status) {
1514 case TorchModeStatus::NOT_AVAILABLE:
1515 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1516 break;
1517 case TorchModeStatus::AVAILABLE_OFF:
1518 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1519 break;
1520 case TorchModeStatus::AVAILABLE_ON:
1521 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1522 break;
1523 default:
1524 ALOGW("Unknown new flash status: %d", status);
1525 }
1526 return serviceStatus;
1527}
1528
1529CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1530 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1531 switch (status) {
1532 case CameraDeviceStatus::NOT_PRESENT:
1533 serviceStatus = StatusInternal::NOT_PRESENT;
1534 break;
1535 case CameraDeviceStatus::PRESENT:
1536 serviceStatus = StatusInternal::PRESENT;
1537 break;
1538 case CameraDeviceStatus::ENUMERATING:
1539 serviceStatus = StatusInternal::ENUMERATING;
1540 break;
1541 default:
1542 ALOGW("Unknown new HAL device status: %d", status);
1543 }
1544 return serviceStatus;
1545}
1546
1547int32_t CameraService::mapToInterface(StatusInternal status) {
1548 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1549 switch (status) {
1550 case StatusInternal::NOT_PRESENT:
1551 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1552 break;
1553 case StatusInternal::PRESENT:
1554 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1555 break;
1556 case StatusInternal::ENUMERATING:
1557 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1558 break;
1559 case StatusInternal::NOT_AVAILABLE:
1560 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1561 break;
1562 case StatusInternal::UNKNOWN:
1563 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1564 break;
1565 default:
1566 ALOGW("Unknown new internal device status: %d", status);
1567 }
1568 return serviceStatus;
1569}
1570
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001571Status CameraService::initializeShimMetadata(int cameraId) {
Jayant Chowdhary12361932018-08-27 14:46:13 -07001572 int uid = CameraThreadState::getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001573
Austin Borgered99f642023-06-01 16:51:35 -07001574 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001575 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001576 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001577 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001578 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1579 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001580 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001581 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001582 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001583 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001584 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001585 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001586 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001587}
1588
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001589Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001590 /*out*/
1591 CameraParameters* parameters) {
1592
1593 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1594
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001595 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001596
1597 if (parameters == NULL) {
1598 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001600 }
1601
malikakashedb38962023-09-06 00:03:35 +00001602 std::string unresolvedCameraId = std::to_string(cameraId);
1603 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
1604 CameraThreadState::getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001605
1606 // Check if we already have parameters
1607 {
1608 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001609 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001610 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001611 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001612 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001613 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001614 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001615 }
1616 CameraParameters p = cameraState->getShimParams();
1617 if (!p.isEmpty()) {
1618 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001619 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001620 }
1621 }
1622
Jayant Chowdhary12361932018-08-27 14:46:13 -07001623 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001624 ret = initializeShimMetadata(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001625 CameraThreadState::restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001627 // Error already logged by callee
1628 return ret;
1629 }
1630
1631 // Check for parameters again
1632 {
1633 // Scope for service lock
1634 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001635 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001636 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001637 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001638 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001639 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001640 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001641 CameraParameters p = cameraState->getShimParams();
1642 if (!p.isEmpty()) {
1643 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001645 }
1646 }
1647
Ruben Brunkcc776712015-02-17 20:18:47 -08001648 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1649 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651}
1652
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001653// Can camera service trust the caller based on the calling UID?
1654static bool isTrustedCallingUid(uid_t uid) {
1655 switch (uid) {
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001656 case AID_MEDIA: // mediaserver
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001657 case AID_CAMERASERVER: // cameraserver
Eino-Ville Talvalaaf9d0302016-06-29 14:40:10 -07001658 case AID_RADIO: // telephony
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001659 return true;
1660 default:
1661 return false;
1662 }
1663}
1664
Austin Borgered99f642023-06-01 16:51:35 -07001665static status_t getUidForPackage(const std::string &packageName, int userId, /*inout*/uid_t& uid,
1666 int err) {
Nicholas Sauera3620332019-04-03 14:05:17 -07001667 PermissionController pc;
Austin Borgered99f642023-06-01 16:51:35 -07001668 uid = pc.getPackageUid(toString16(packageName), 0);
Nicholas Sauera3620332019-04-03 14:05:17 -07001669 if (uid <= 0) {
Austin Borgered99f642023-06-01 16:51:35 -07001670 ALOGE("Unknown package: '%s'", packageName.c_str());
1671 dprintf(err, "Unknown package: '%s'\n", packageName.c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07001672 return BAD_VALUE;
1673 }
1674
1675 if (userId < 0) {
1676 ALOGE("Invalid user: %d", userId);
1677 dprintf(err, "Invalid user: %d\n", userId);
1678 return BAD_VALUE;
1679 }
1680
1681 uid = multiuser_get_uid(userId, uid);
1682 return NO_ERROR;
1683}
1684
Austin Borgered99f642023-06-01 16:51:35 -07001685Status CameraService::validateConnectLocked(const std::string& cameraId,
1686 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001687 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001688
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001689#ifdef __BRILLO__
1690 UNUSED(clientName8);
1691 UNUSED(clientUid);
1692 UNUSED(clientPid);
1693 UNUSED(originalClientPid);
1694#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001695 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1696 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001697 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001698 return allowed;
1699 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001700#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001701
Jayant Chowdhary12361932018-08-27 14:46:13 -07001702 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001703
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001704 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001705 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1706 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001707 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001708 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001709 }
1710
Ruben Brunkcc776712015-02-17 20:18:47 -08001711 if (getCameraState(cameraId) == nullptr) {
1712 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001713 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001714 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001715 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001716 }
1717
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001718 status_t err = checkIfDeviceIsUsable(cameraId);
1719 if (err != NO_ERROR) {
1720 switch(err) {
1721 case -ENODEV:
1722 case -EBUSY:
1723 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001724 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001725 default:
1726 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001727 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001728 }
1729 }
1730 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001731}
1732
Austin Borgered99f642023-06-01 16:51:35 -07001733Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1734 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001735 /*out*/int& originalClientPid) const {
Joanne Chung02c13d02023-01-16 12:58:05 +00001736 AttributionSourceState attributionSource{};
1737
Jayant Chowdhary12361932018-08-27 14:46:13 -07001738 int callingPid = CameraThreadState::getCallingPid();
1739 int callingUid = CameraThreadState::getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001741 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001742 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001743 clientUid = callingUid;
1744 } else if (!isTrustedCallingUid(callingUid)) {
1745 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1746 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001747 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1748 "Untrusted caller (calling PID %d, UID %d) trying to "
1749 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001750 callingPid, callingUid, cameraId.c_str(),
1751 clientName.c_str(), clientUid, clientPid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001752 }
1753
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001754 // Check if we can trust clientPid
1755 if (clientPid == USE_CALLING_PID) {
1756 clientPid = callingPid;
1757 } else if (!isTrustedCallingUid(callingUid)) {
1758 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1759 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001760 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1761 "Untrusted caller (calling PID %d, UID %d) trying to "
1762 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001763 callingPid, callingUid, cameraId.c_str(),
1764 clientName.c_str(), clientUid, clientPid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001765 }
1766
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001767 if (shouldRejectSystemCameraConnection(cameraId)) {
1768 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1769 cameraId.c_str());
1770 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001771 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001772 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001773 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1774 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001775 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001776 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001777 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001778
1779 }
1780
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001781 // If it's not calling from cameraserver, check the permission if the
1782 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1783 // android.permission.SYSTEM_CAMERA for system only camera devices).
Joanne Chung02c13d02023-01-16 12:58:05 +00001784 attributionSource.pid = clientPid;
1785 attributionSource.uid = clientUid;
Austin Borgered99f642023-06-01 16:51:35 -07001786 attributionSource.packageName = clientName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001787 bool checkPermissionForCamera = checkPermission(cameraId, sCameraPermission, attributionSource,
Austin Borger1c1bee02023-06-01 16:51:35 -07001788 std::string(), AppOpsManager::OP_NONE);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001789 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001790 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001791 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1793 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borgered99f642023-06-01 16:51:35 -07001794 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001795 }
1796
Svet Ganova453d0d2018-01-11 15:37:58 -08001797 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001798 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001799 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001800 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1801 clientPid, clientUid);
1802 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001803 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1804 "calling UID %d proc state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001805 clientName.c_str(), clientUid, clientPid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001806 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001807 }
1808
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001809 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1810 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1811 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1812 if ((!isAutomotivePrivilegedClient(callingUid) ||
1813 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1814 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001815 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1816 return STATUS_ERROR_FMT(ERROR_DISABLED,
1817 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borgered99f642023-06-01 16:51:35 -07001818 "is enabled", clientName.c_str(), clientUid, clientPid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001819 }
1820
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001821 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1822 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001823 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001824 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825
Ruben Brunk6267b532015-04-30 17:44:07 -07001826 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001827
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001828 // For non-system clients : Only allow clients who are being used by the current foreground
1829 // device user, unless calling from our own process.
1830 if (!doesClientHaveSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001831 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001832 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1833 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001834 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001835 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1836 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001837 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001838 }
1839
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001840 if (flags::camera_hsum_permission()) {
1841 // If the System User tries to access the camera when the device is running in
1842 // headless system user mode, ensure that client has the required permission
1843 // CAMERA_HEADLESS_SYSTEM_USER.
1844 if (isHeadlessSystemUserMode() && (clientUserId == USER_SYSTEM) &&
1845 !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
1846 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1847 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1848 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1849 User without camera headless system user permission",
1850 clientName.c_str(), clientUid, clientPid, cameraId.c_str());
1851 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001852 }
1853
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001854 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001855}
1856
Austin Borgered99f642023-06-01 16:51:35 -07001857status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001858 auto cameraState = getCameraState(cameraId);
Jayant Chowdhary12361932018-08-27 14:46:13 -07001859 int callingPid = CameraThreadState::getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001860 if (cameraState == nullptr) {
1861 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001862 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001863 return -ENODEV;
1864 }
1865
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001866 StatusInternal currentStatus = cameraState->getStatus();
1867 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001868 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001869 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001870 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001871 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001872 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001873 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001874 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001875 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001876
Ruben Brunkcc776712015-02-17 20:18:47 -08001877 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001878}
1879
Ruben Brunkcc776712015-02-17 20:18:47 -08001880void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001881 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001882
Ruben Brunkcc776712015-02-17 20:18:47 -08001883 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001884 auto clientDescriptor =
1885 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001886 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001887 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1888
1889 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001890 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001891
1892 if (evicted.size() > 0) {
1893 // This should never happen - clients should already have been removed in disconnect
1894 for (auto& i : evicted) {
1895 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001896 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001897 }
1898
1899 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1900 __FUNCTION__);
1901 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001902
1903 // And register a death notification for the client callback. Do
1904 // this last to avoid Binder policy where a nested Binder
1905 // transaction might be pre-empted to service the client death
1906 // notification if the client process dies before linkToDeath is
1907 // invoked.
1908 sp<IBinder> remoteCallback = client->getRemote();
1909 if (remoteCallback != nullptr) {
1910 remoteCallback->linkToDeath(this);
1911 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001912}
1913
Austin Borgered99f642023-06-01 16:51:35 -07001914status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1915 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1916 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001917 /*out*/
1918 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001919 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001920 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001921 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001922 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001923 DescriptorPtr clientDescriptor;
1924 {
1925 if (effectiveApiLevel == API_1) {
1926 // If we are using API1, any existing client for this camera ID with the same remote
1927 // should be returned rather than evicted to allow MediaRecorder to work properly.
1928
1929 auto current = mActiveClientManager.get(cameraId);
1930 if (current != nullptr) {
1931 auto clientSp = current->getValue();
1932 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001933 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001934 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001935 " API level, evicting prior client...");
1936 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001937 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001938 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001939 *client = clientSp;
1940 return NO_ERROR;
1941 }
1942 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001943 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001944 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001945
Ruben Brunkcc776712015-02-17 20:18:47 -08001946 // Get state for the given cameraId
1947 auto state = getCameraState(cameraId);
1948 if (state == nullptr) {
1949 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001950 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001951 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001952 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001953 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001954
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001955 sp<IServiceManager> sm = defaultServiceManager();
1956 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
1957 if (!binder && isAutomotivePrivilegedClient(CameraThreadState::getCallingUid())) {
1958 // If processinfo service is not available and the client is automotive privileged
1959 // client used for safety critical uses cases such as rear-view and surround-view which
1960 // needs to be available before android boot completes, then use the hardcoded values
1961 // for the process state and priority score. As this scenario is before android system
1962 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1963 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1964 // visible on the top.
1965 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1966 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1967 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1968 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1969 } else {
1970 // Get current active client PIDs
1971 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1972 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001973
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001974 std::vector<int> priorityScores(ownerPids.size());
1975 std::vector<int> states(ownerPids.size());
1976
1977 // Get priority scores of all active PIDs
1978 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1979 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1980 if (err != OK) {
1981 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1982 return err;
1983 }
1984
1985 // Update all active clients' priorities
1986 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1987 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1988 pidToPriorityMap.emplace(ownerPids[i],
1989 resource_policy::ClientPriority(priorityScores[i], states[i],
1990 /* isVendorClient won't get copied over*/ false,
1991 /* oomScoreOffset won't get copied over*/ 0));
1992 }
1993 mActiveClientManager.updatePriorities(pidToPriorityMap);
1994
1995 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1996 int32_t actualState = states[states.size() - 1];
1997
1998 // Make descriptor for incoming client. We store the oomScoreOffset
1999 // since we might need it later on new handleEvictionsLocked and
2000 // ProcessInfoService would not take that into account.
2001 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2002 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2003 state->getConflicting(), actualScore, clientPid, actualState,
2004 oomScoreOffset, systemNativeClient);
2005 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002006
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002007 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2008
Ruben Brunkcc776712015-02-17 20:18:47 -08002009 // Find clients that would be evicted
2010 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2011
2012 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2013 // background, so we cannot do evictions
2014 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2015 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2016 " priority).", clientPid);
2017
2018 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002019 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002020 auto incompatibleClients =
2021 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2022
Austin Borgered99f642023-06-01 16:51:35 -07002023 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2024 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2025 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002026 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002027
2028 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002029 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002030 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002031 i->getKey().c_str(),
2032 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002033 i->getOwnerId(), i->getPriority().getScore(),
2034 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002035 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002036 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2037 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002038 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 }
2040
2041 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002042 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 mEventLog.add(msg);
2044
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002045 auto current = mActiveClientManager.get(cameraId);
2046 if (current != nullptr) {
2047 return -EBUSY; // CAMERA_IN_USE
2048 } else {
2049 return -EUSERS; // MAX_CAMERAS_IN_USE
2050 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002051 }
2052
2053 for (auto& i : evicted) {
2054 sp<BasicClient> clientSp = i->getValue();
2055 if (clientSp.get() == nullptr) {
2056 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2057
2058 // TODO: Remove this
2059 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2060 __FUNCTION__);
2061 mActiveClientManager.remove(i);
2062 continue;
2063 }
2064
2065 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002066 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002067 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002068
Ruben Brunkcc776712015-02-17 20:18:47 -08002069 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002070 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002071 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2072 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002073 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002074 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002075 i->getPriority().getState(), cameraId.c_str(),
2076 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002077 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002078
2079 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002080 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002081 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002082 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002083 }
2084
Ruben Brunkcc776712015-02-17 20:18:47 -08002085 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2086 // other clients from connecting in mServiceLockWrapper if held
2087 mServiceLock.unlock();
2088
2089 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07002090 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002091
2092 // Destroy evicted clients
2093 for (auto& i : evictedClients) {
2094 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002095 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002096 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002097
Jayant Chowdhary12361932018-08-27 14:46:13 -07002098 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002099
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002100 for (const auto& i : evictedClients) {
2101 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002102 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002103 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2104 if (ret == TIMED_OUT) {
2105 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002106 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2107 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002108 return -EBUSY;
2109 }
2110 if (ret != NO_ERROR) {
2111 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002112 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2113 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002114 return ret;
2115 }
2116 }
2117
2118 evictedClients.clear();
2119
Ruben Brunkcc776712015-02-17 20:18:47 -08002120 // Once clients have been disconnected, relock
2121 mServiceLock.lock();
2122
2123 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2124 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2125 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002126 }
2127
Ruben Brunkcc776712015-02-17 20:18:47 -08002128 *partial = clientDescriptor;
2129 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002130}
2131
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002132Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002133 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002134 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002135 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002136 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002137 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002138 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002139 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002140 bool forceSlowJpegMode,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002141 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002142 sp<ICamera>* device) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002143
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002144 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002145 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002146
malikakashedb38962023-09-06 00:03:35 +00002147 std::string unresolvedCameraId = cameraIdIntToStr(api1CameraId);
2148 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
2149 CameraThreadState::getCallingUid());
2150
Ruben Brunkcc776712015-02-17 20:18:47 -08002151 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002152 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2153 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002154 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002155 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002156
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002157 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002158 logRejected(cameraIdStr, CameraThreadState::getCallingPid(), clientPackageName,
2159 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002160 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002161 }
2162
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002163 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002164
2165 const sp<IServiceManager> sm(defaultServiceManager());
2166 const auto& mActivityManager = getActivityManager();
2167 if (mActivityManager) {
2168 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2169 CameraThreadState::getCallingUid(),
2170 CameraThreadState::getCallingPid());
2171 }
2172
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002173 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002174}
2175
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002176bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2177 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002178 // If the client is not a vendor client, don't add listener if
2179 // a) the camera is a publicly hidden secure camera OR
2180 // b) the camera is a system only camera and the client doesn't
2181 // have android.permission.SYSTEM_CAMERA permissions.
2182 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2183 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002184 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002185 return true;
2186 }
2187 return false;
2188}
2189
Austin Borgered99f642023-06-01 16:51:35 -07002190bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002191 // Rules for rejection:
2192 // 1) If cameraserver tries to access this camera device, accept the
2193 // connection.
2194 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002195 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002196 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2197 // and the serving thread is a non hwbinder thread, the client must have
2198 // android.permission.SYSTEM_CAMERA permissions to connect.
2199
2200 int cPid = CameraThreadState::getCallingPid();
2201 int cUid = CameraThreadState::getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002202 bool systemClient = doesClientHaveSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002203 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2204 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002205 // This isn't a known camera ID, so it's not a system camera
2206 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2207 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002208 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002209
2210 // (1) Cameraserver trying to connect, accept.
2211 if (CameraThreadState::getCallingPid() == getpid()) {
2212 return false;
2213 }
2214 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002215 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002216 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2217 return true;
2218 }
2219 // (3) Here we only check for permissions if it is a system only camera device. This is since
2220 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2221 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2222 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002223 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002224 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002225 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2226 cameraId.c_str());
2227 return true;
2228 }
2229
2230 return false;
2231}
2232
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002233Status CameraService::connectDevice(
2234 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002235 const std::string& unresolvedCameraId,
2236 const std::string& clientPackageName,
2237 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002238 int clientUid, int oomScoreOffset, int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002239 bool overrideToPortrait,
Ruben Brunkcc776712015-02-17 20:18:47 -08002240 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002241 sp<hardware::camera2::ICameraDeviceUser>* device) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002242
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002243 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002244 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002246 std::string clientPackageNameAdj = clientPackageName;
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002247 int callingPid = CameraThreadState::getCallingPid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002248 bool systemNativeClient = false;
2249 if (doesClientHaveSystemUid() && (clientPackageNameAdj.size() == 0)) {
2250 std::string systemClient =
Austin Borgered99f642023-06-01 16:51:35 -07002251 fmt::sprintf("client.pid<%d>", CameraThreadState::getCallingPid());
2252 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002253 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002254 }
malikakashedb38962023-09-06 00:03:35 +00002255 const std::string cameraId = resolveCameraId(
2256 unresolvedCameraId,
2257 CameraThreadState::getCallingUid(),
2258 clientPackageNameAdj);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002259
2260 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002261 std::string msg =
2262 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2263 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2264 cameraId.c_str());
2265 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2266 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002267 }
2268
Austin Borger9bfa0a72022-08-03 17:50:40 -07002269 userid_t clientUserId = multiuser_get_user_id(clientUid);
2270 int callingUid = CameraThreadState::getCallingUid();
2271 if (clientUid == USE_CALLING_UID) {
2272 clientUserId = multiuser_get_user_id(callingUid);
2273 }
2274
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002275 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2276 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002277 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2278 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002279 std::string msg = "Camera disabled by device policy";
2280 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2281 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002282 }
2283
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002284 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002285 if (oomScoreOffset > 0
2286 && !hasPermissionsForSystemCamera(cameraId, callingPid,
2287 CameraThreadState::getCallingUid())
2288 && !isTrustedCallingUid(CameraThreadState::getCallingUid())) {
Austin Borgered99f642023-06-01 16:51:35 -07002289 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002290 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002291 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2292 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2293 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002294 }
2295
Austin Borgered99f642023-06-01 16:51:35 -07002296 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2297 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002298 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002299 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002300 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002301
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002302 if(!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002303 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002304 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002305 }
2306
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002307 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002308 Mutex::Autolock lock(mServiceLock);
2309
2310 // Clear the previous cached logs and reposition the
2311 // file offset to beginning of the file to log new data.
2312 // If either truncate or lseek fails, close the previous file and create a new one.
2313 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2314 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2315 // Close the previous memfd.
2316 close(mMemFd);
2317 // If failure to wipe the data, then create a new file and
2318 // assign the new value to mMemFd.
2319 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2320 if (mMemFd == -1) {
2321 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2322 }
2323 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002324 const sp<IServiceManager> sm(defaultServiceManager());
2325 const auto& mActivityManager = getActivityManager();
2326 if (mActivityManager) {
2327 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
2328 CameraThreadState::getCallingUid(),
2329 CameraThreadState::getCallingPid());
2330 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002331 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002332}
2333
Austin Borgered99f642023-06-01 16:51:35 -07002334std::string CameraService::getPackageNameFromUid(int clientUid) {
2335 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002336
2337 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07002338 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002339 if (binder == 0) {
2340 ALOGE("Cannot get permission service");
2341 // Return empty package name and the further interaction
2342 // with camera will likely fail
2343 return packageName;
2344 }
2345
2346 sp<IPermissionController> permCtrl = interface_cast<IPermissionController>(binder);
2347 Vector<String16> packages;
2348
2349 permCtrl->getPackagesForUid(clientUid, packages);
2350
2351 if (packages.isEmpty()) {
2352 ALOGE("No packages for calling UID %d", clientUid);
2353 // Return empty package name and the further interaction
2354 // with camera will likely fail
2355 return packageName;
2356 }
2357
2358 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002359 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002360
2361 return packageName;
2362}
2363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002364template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002365Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2366 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2367 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002368 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002369 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002370 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002371 binder::Status ret = binder::Status::ok();
2372
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002373 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002374 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002375 int packageUid = (clientUid == USE_CALLING_UID) ?
2376 CameraThreadState::getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002377 if (clientPackageNameMaybe.size() <= 0) {
2378 // NDK calls don't come with package names, but we need one for various cases.
2379 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2380 // do exist. For all authentication cases, all packages under the same UID get the
2381 // same permissions, so picking any associated package name is sufficient. For some
2382 // other cases, this may give inaccurate names for clients in logs.
2383 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002384 clientPackageName = getPackageNameFromUid(packageUid);
2385 } else {
2386 clientPackageName = clientPackageNameMaybe;
2387 }
2388
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002389 int originalClientPid = 0;
2390
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002391 int packagePid = (clientPid == USE_CALLING_PID) ?
2392 CameraThreadState::getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002393 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002394 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002395 static_cast<int>(effectiveApiLevel));
2396
Shuzhen Wang316781a2020-08-18 18:11:01 -07002397 nsecs_t openTimeNs = systemTime();
2398
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002399 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002400 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002401 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002402
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002403 {
2404 // Acquire mServiceLock and prevent other clients from connecting
2405 std::unique_ptr<AutoConditionLock> lock =
2406 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2407
2408 if (lock == nullptr) {
2409 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2410 , clientPid);
2411 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2412 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002413 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002414 }
2415
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002416 // Enforce client permissions and do basic validity checks
Austin Borgered99f642023-06-01 16:51:35 -07002417 if(!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002418 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2419 return ret;
2420 }
2421
2422 // Check the shim parameters after acquiring lock, if they have already been updated and
2423 // we were doing a shim update, return immediately
2424 if (shimUpdateOnly) {
2425 auto cameraState = getCameraState(cameraId);
2426 if (cameraState != nullptr) {
2427 if (!cameraState->getShimParams().isEmpty()) return ret;
2428 }
2429 }
2430
2431 status_t err;
2432
2433 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002434 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002435 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002436 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2437 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002438 switch (err) {
2439 case -ENODEV:
2440 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2441 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002442 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002443 case -EBUSY:
2444 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2445 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002446 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002447 case -EUSERS:
2448 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2449 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002450 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002451 default:
2452 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2453 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002454 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002455 }
2456 }
2457
2458 if (clientTmp.get() != nullptr) {
2459 // Handle special case for API1 MediaRecorder where the existing client is returned
2460 device = static_cast<CLIENT*>(clientTmp.get());
2461 return ret;
2462 }
2463
2464 // give flashlight a chance to close devices if necessary.
2465 mFlashlight->prepareDeviceOpen(cameraId);
2466
Austin Borger18b30a72022-10-27 12:20:29 -07002467 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002468 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002469 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2470 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002471 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002472 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002473 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002474 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002475 }
2476
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002477 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002478 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002479 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002480 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002481 clientFeatureId, cameraId, api1CameraId, facing,
2482 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002483 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002484 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002485 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002486 return ret;
2487 }
2488 client = static_cast<CLIENT*>(tmp.get());
2489
2490 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2491 __FUNCTION__);
2492
Austin Borgered99f642023-06-01 16:51:35 -07002493 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002494 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002495 if (err != OK) {
2496 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002497 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002498 mServiceLock.unlock();
2499 client->disconnect();
2500 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002501 switch(err) {
2502 case BAD_VALUE:
2503 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002504 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002505 case -EBUSY:
2506 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002507 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002508 case -EUSERS:
2509 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2510 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002511 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002512 case PERMISSION_DENIED:
2513 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002514 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002515 case -EACCES:
2516 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002517 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002518 case -ENODEV:
2519 default:
2520 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002521 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002522 strerror(-err), err);
2523 }
2524 }
2525
2526 // Update shim paremeters for legacy clients
2527 if (effectiveApiLevel == API_1) {
2528 // Assume we have always received a Client subclass for API1
2529 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2530 String8 rawParams = shimClient->getParameters();
2531 CameraParameters params(rawParams);
2532
2533 auto cameraState = getCameraState(cameraId);
2534 if (cameraState != nullptr) {
2535 cameraState->setShimParams(params);
2536 } else {
2537 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002538 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002539 }
2540 }
2541
Ravneetaeb20dc2022-03-30 05:33:03 +00002542 // Enable/disable camera service watchdog
2543 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2544
Emilian Peev6d45db82024-01-18 20:11:54 +00002545 CameraMetadata chars;
2546 bool rotateAndCropSupported = true;
2547 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2548 &chars, overrideToPortrait);
2549 if (err == OK) {
2550 auto availableRotateCropEntry = chars.find(
2551 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2552 if (availableRotateCropEntry.count <= 1) {
2553 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002554 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002555 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002556 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2557 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002558 }
2559
Emilian Peev6d45db82024-01-18 20:11:54 +00002560 if (rotateAndCropSupported) {
2561 // Set rotate-and-crop override behavior
2562 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2563 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2564 } else if (overrideToPortrait && portraitRotation != 0) {
2565 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2566 switch (portraitRotation) {
2567 case 90:
2568 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2569 break;
2570 case 180:
2571 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2572 break;
2573 case 270:
2574 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2575 break;
2576 default:
2577 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2578 break;
2579 }
2580 client->setRotateAndCropOverride(rotateAndCropMode);
2581 } else {
2582 client->setRotateAndCropOverride(
2583 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2584 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2585 }
2586 }
2587
2588 bool autoframingSupported = true;
2589 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2590 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2591 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2592 autoframingSupported = false;
2593 }
2594
2595 if (autoframingSupported) {
2596 // Set autoframing override behaviour
2597 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2598 client->setAutoframingOverride(mOverrideAutoframingMode);
2599 } else {
2600 client->setAutoframingOverride(
2601 mCameraServiceProxyWrapper->getAutoframingOverride(
2602 clientPackageName));
2603 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002604 }
2605
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002606 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use
2607 // cases such as rear view and surround view cannot be disabled and are exempt from camera
2608 // privacy policy.
2609 if ((!isAutomotivePrivilegedClient(packageUid) ||
2610 !isAutomotiveExteriorSystemCamera(cameraId))) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002611 // Set camera muting behavior.
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002612 bool isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002613 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002614 if (client->supportsCameraMute()) {
2615 client->setCameraMute(
2616 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2617 } else if (isCameraPrivacyEnabled) {
2618 // no camera mute supported, but privacy is on! => disconnect
2619 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2620 client->getPackageName().c_str(), cameraId.c_str());
2621 // Do not hold mServiceLock while disconnecting clients, but
2622 // retain the condition blocking other clients from connecting
2623 // in mServiceLockWrapper if held.
2624 mServiceLock.unlock();
2625 // Clear caller identity temporarily so client disconnect PID
2626 // checks work correctly
2627 int64_t token = CameraThreadState::clearCallingIdentity();
2628 // Note AppOp to trigger the "Unblock" dialog
2629 client->noteAppOp();
2630 client->disconnect();
2631 CameraThreadState::restoreCallingIdentity(token);
2632 // Reacquire mServiceLock
2633 mServiceLock.lock();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002634
Priyanka Advani1a09fd92024-02-10 01:28:37 +00002635 return STATUS_ERROR_FMT(ERROR_DISABLED,
2636 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
2637 }
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002638 }
2639
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002640 if (shimUpdateOnly) {
2641 // If only updating legacy shim parameters, immediately disconnect client
2642 mServiceLock.unlock();
2643 client->disconnect();
2644 mServiceLock.lock();
2645 } else {
2646 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002647 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002648 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002649
2650 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002651 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002652 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002653 } // lock is destroyed, allow further connect calls
2654
2655 // Important: release the mutex here so the client can call back into the service from its
2656 // destructor (can be at the end of the call)
2657 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002658
2659 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002660 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002661 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002662
Cliff Wud3a05312021-04-26 23:07:31 +08002663 {
2664 Mutex::Autolock lock(mInjectionParametersLock);
2665 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2666 mInjectionInitPending = false;
2667 status_t res = NO_ERROR;
2668 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2669 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002670 sp<BasicClient> clientSp = clientDescriptor->getValue();
2671 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2672 if(res != OK) {
2673 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2674 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002675 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002676 }
2677 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002678 if (res != OK) {
2679 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2680 }
2681 } else {
2682 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002683 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002684 res = NO_INIT;
2685 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2686 }
2687 }
2688 }
2689
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002690 return ret;
2691}
2692
Austin Borgered99f642023-06-01 16:51:35 -07002693status_t CameraService::addOfflineClient(const std::string &cameraId,
2694 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002695 if (offlineClient.get() == nullptr) {
2696 return BAD_VALUE;
2697 }
2698
2699 {
2700 // Acquire mServiceLock and prevent other clients from connecting
2701 std::unique_ptr<AutoConditionLock> lock =
2702 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2703
2704 if (lock == nullptr) {
2705 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2706 , __FUNCTION__, offlineClient->getClientPid());
2707 return TIMED_OUT;
2708 }
2709
2710 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2711 if (onlineClientDesc.get() == nullptr) {
2712 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2713 cameraId.c_str());
2714 return BAD_VALUE;
2715 }
2716
2717 // Offline clients do not evict or conflict with other online devices. Resource sharing
2718 // conflicts are handled by the camera provider which will either succeed or fail before
2719 // reaching this method.
2720 const auto& onlinePriority = onlineClientDesc->getPriority();
2721 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2722 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002723 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002724 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002725 // native clients don't have offline processing support.
2726 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002727 if (offlineClientDesc == nullptr) {
2728 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2729 return BAD_VALUE;
2730 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002731
2732 // Allow only one offline device per camera
2733 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2734 if (!incompatibleClients.empty()) {
2735 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2736 return BAD_VALUE;
2737 }
2738
Austin Borgered99f642023-06-01 16:51:35 -07002739 std::string monitorTags = isClientWatched(offlineClient.get())
2740 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002741 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002742 if (err != OK) {
2743 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2744 return err;
2745 }
2746
2747 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2748 if (evicted.size() > 0) {
2749 for (auto& i : evicted) {
2750 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002751 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002752 }
2753
2754 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2755 "properly", __FUNCTION__);
2756
2757 return BAD_VALUE;
2758 }
2759
2760 logConnectedOffline(offlineClientDesc->getKey(),
2761 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002762 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002763
2764 sp<IBinder> remoteCallback = offlineClient->getRemote();
2765 if (remoteCallback != nullptr) {
2766 remoteCallback->linkToDeath(this);
2767 }
2768 } // lock is destroyed, allow further connect calls
2769
2770 return OK;
2771}
2772
Austin Borgered99f642023-06-01 16:51:35 -07002773Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger1c1bee02023-06-01 16:51:35 -07002774 int32_t torchStrength, const sp<IBinder>& clientBinder) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002775 Mutex::Autolock lock(mServiceLock);
2776
2777 ATRACE_CALL();
2778 if (clientBinder == nullptr) {
2779 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2780 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2781 "Torch client binder in null.");
2782 }
2783
Rucha Katakwar38284522021-11-10 11:25:21 -08002784 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002785 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Austin Borgered99f642023-06-01 16:51:35 -07002786 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002787 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002788 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002789 }
2790
2791 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002792 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002793 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002794 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002795 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002796 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002797 }
2798
2799 StatusInternal cameraStatus = state->getStatus();
2800 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2801 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002802 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002803 (int)cameraStatus);
2804 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002805 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002806 }
2807
2808 {
2809 Mutex::Autolock al(mTorchStatusMutex);
2810 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002811 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002812 if (err != OK) {
2813 if (err == NAME_NOT_FOUND) {
2814 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002815 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002816 }
2817 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002818 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002819 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2820 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002821 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002822 }
2823
2824 if (status == TorchModeStatus::NOT_AVAILABLE) {
2825 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2826 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002827 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002828 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2829 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002830 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002831 } else {
2832 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002833 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002834 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2835 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002836 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002837 }
2838 }
2839 }
2840
2841 {
2842 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002843 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002844 }
2845 // Check if the current torch strength level is same as the new one.
2846 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002847 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002848
Austin Borgered99f642023-06-01 16:51:35 -07002849 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002850
2851 if (err != OK) {
2852 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002853 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002854 switch (err) {
2855 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002856 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2857 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002858 errorCode = ERROR_ILLEGAL_ARGUMENT;
2859 break;
2860 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002861 msg = fmt::sprintf("Camera \"%s\" is in use",
2862 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002863 errorCode = ERROR_CAMERA_IN_USE;
2864 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002865 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002866 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002867 "valid range.", torchStrength);
2868 errorCode = ERROR_ILLEGAL_ARGUMENT;
2869 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002870 default:
Austin Borgered99f642023-06-01 16:51:35 -07002871 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002872 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002873 }
Austin Borgered99f642023-06-01 16:51:35 -07002874 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2875 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002876 }
2877
2878 {
2879 // update the link to client's death
2880 // Store the last client that turns on each camera's torch mode.
2881 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002882 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002883 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002884 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002885 } else {
2886 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2887 mTorchClientMap.replaceValueAt(index, clientBinder);
2888 }
2889 clientBinder->linkToDeath(this);
2890 }
2891
2892 int clientPid = CameraThreadState::getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002893 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002894 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002895 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002896 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002897 }
2898 return Status::ok();
2899}
2900
malikakash73125c62023-07-21 22:44:34 +00002901Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002902 const sp<IBinder>& clientBinder) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002903 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002904
2905 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002906 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002907 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002908 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2909 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002910 }
2911
Jayant Chowdhary12361932018-08-27 14:46:13 -07002912 int uid = CameraThreadState::getCallingUid();
malikakashedb38962023-09-06 00:03:35 +00002913 const std::string cameraId = resolveCameraId(unresolvedCameraId, uid);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002914
Austin Borgered99f642023-06-01 16:51:35 -07002915 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002916 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002917 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002918 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002919 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002920 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002921 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002922 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002923 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002924 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002925 }
2926
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002927 StatusInternal cameraStatus = state->getStatus();
2928 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002929 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002930 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2931 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002932 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002933 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002934 }
2935
2936 {
2937 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002938 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002939 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002940 if (err != OK) {
2941 if (err == NAME_NOT_FOUND) {
2942 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002943 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002944 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002945 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002946 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002947 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002948 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002949 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002950 }
2951
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002952 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002953 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002954 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002955 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002956 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2957 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002958 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002959 } else {
2960 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002961 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002962 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2963 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002964 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002965 }
2966 }
2967 }
2968
Ruben Brunk99e69712015-05-26 17:25:07 -07002969 {
2970 // Update UID map - this is used in the torch status changed callbacks, so must be done
2971 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002972 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002973 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002974 }
2975
Austin Borgered99f642023-06-01 16:51:35 -07002976 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002977
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002978 if (err != OK) {
2979 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002980 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002981 switch (err) {
2982 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002983 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2984 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002985 errorCode = ERROR_ILLEGAL_ARGUMENT;
2986 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08002987 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002988 msg = fmt::sprintf("Camera \"%s\" is in use",
2989 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08002990 errorCode = ERROR_CAMERA_IN_USE;
2991 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002992 default:
Austin Borgered99f642023-06-01 16:51:35 -07002993 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002994 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002995 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002996 errorCode = ERROR_INVALID_OPERATION;
2997 }
Austin Borgered99f642023-06-01 16:51:35 -07002998 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2999 logServiceError(msg, errorCode);
3000 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003001 }
3002
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003003 {
3004 // update the link to client's death
3005 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003006 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003007 if (enabled) {
3008 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003009 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003010 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003011 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003012 mTorchClientMap.replaceValueAt(index, clientBinder);
3013 }
3014 clientBinder->linkToDeath(this);
3015 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003016 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003017 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003018 }
3019
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003020 int clientPid = CameraThreadState::getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003021 std::string torchState = enabled ? "on" : "off";
3022 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3023 torchState.c_str(), clientPid);
3024 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003025 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003026}
3027
Austin Borgered99f642023-06-01 16:51:35 -07003028void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3029 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3030 mTorchUidMap[cameraId].first = uid;
3031 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003032 } else {
3033 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003034 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003035 }
3036}
3037
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003038Status CameraService::notifySystemEvent(int32_t eventId,
3039 const std::vector<int32_t>& args) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003040 const int pid = CameraThreadState::getCallingPid();
3041 const int selfPid = getpid();
3042
3043 // Permission checks
3044 if (pid != selfPid) {
3045 // Ensure we're being called by system_server, or similar process with
3046 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003047 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003048 const int uid = CameraThreadState::getCallingUid();
3049 ALOGE("Permission Denial: cannot send updates to camera service about system"
3050 " events from pid=%d, uid=%d", pid, uid);
3051 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003052 "No permission to send updates to camera service about system events"
3053 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003054 }
3055 }
3056
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003057 ATRACE_CALL();
3058
Ruben Brunk36597b22015-03-20 22:15:57 -07003059 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003060 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003061 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003062 // from a system server crash
3063 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003064 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003065 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003066 break;
3067 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003068 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3069 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003070 if (args.size() != 1) {
3071 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3072 "USB Device Event requires 1 argument");
3073 }
3074
Valentin Iftime29e2e152021-08-13 15:17:33 +02003075 // Notify CameraProviderManager for lazy HALs
3076 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3077 std::to_string(args[0]));
3078 break;
3079 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003080 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003081 default: {
3082 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3083 eventId);
3084 break;
3085 }
3086 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003087 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003088}
3089
Emilian Peev53722fa2019-02-22 17:47:20 -08003090void CameraService::notifyMonitoredUids() {
3091 Mutex::Autolock lock(mStatusListenerLock);
3092
3093 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003094 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003095 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3096 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003097 }
3098}
3099
Austin Borgerdddb7552023-03-30 17:53:01 -07003100void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3101 Mutex::Autolock lock(mStatusListenerLock);
3102
3103 for (const auto& it : mListenerList) {
3104 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3105 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3106 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3107 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3108 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3109 }
3110 }
3111}
3112
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003113Status CameraService::notifyDeviceStateChange(int64_t newState) {
3114 const int pid = CameraThreadState::getCallingPid();
3115 const int selfPid = getpid();
3116
3117 // Permission checks
3118 if (pid != selfPid) {
3119 // Ensure we're being called by system_server, or similar process with
3120 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003121 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003122 const int uid = CameraThreadState::getCallingUid();
3123 ALOGE("Permission Denial: cannot send updates to camera service about device"
3124 " state changes from pid=%d, uid=%d", pid, uid);
3125 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3126 "No permission to send updates to camera service about device state"
3127 " changes from pid=%d, uid=%d", pid, uid);
3128 }
3129 }
3130
3131 ATRACE_CALL();
3132
Austin Borger18b30a72022-10-27 12:20:29 -07003133 {
3134 Mutex::Autolock lock(mServiceLock);
3135 mDeviceState = newState;
3136 }
3137
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003138 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003139
3140 return Status::ok();
3141}
3142
Emilian Peev8b64f282021-03-25 16:49:57 -07003143Status CameraService::notifyDisplayConfigurationChange() {
3144 ATRACE_CALL();
3145 const int callingPid = CameraThreadState::getCallingPid();
3146 const int selfPid = getpid();
3147
3148 // Permission checks
3149 if (callingPid != selfPid) {
3150 // Ensure we're being called by system_server, or similar process with
3151 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003152 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Emilian Peev8b64f282021-03-25 16:49:57 -07003153 const int uid = CameraThreadState::getCallingUid();
3154 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3155 " changes from pid=%d, uid=%d", callingPid, uid);
3156 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3157 "No permission to send updates to camera service about orientation"
3158 " changes from pid=%d, uid=%d", callingPid, uid);
3159 }
3160 }
3161
3162 Mutex::Autolock lock(mServiceLock);
3163
3164 // Don't do anything if rotate-and-crop override via cmd is active
3165 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3166
3167 const auto clients = mActiveClientManager.getAll();
3168 for (auto& current : clients) {
3169 if (current != nullptr) {
3170 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003171 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3172 basicClient->setRotateAndCropOverride(
3173 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3174 basicClient->getPackageName(),
3175 basicClient->getCameraFacing(),
3176 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003177 }
3178 }
3179 }
3180
3181 return Status::ok();
3182}
3183
3184Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003185 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3186 ATRACE_CALL();
3187 if (!concurrentCameraIds) {
3188 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3189 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3190 }
3191
3192 if (!mInitialized) {
3193 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003194 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003195 return STATUS_ERROR(ERROR_DISCONNECTED,
3196 "Camera subsystem is not available");
3197 }
3198 // First call into the provider and get the set of concurrent camera
3199 // combinations
3200 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003201 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003202 for (auto &combination : concurrentCameraCombinations) {
3203 std::vector<std::string> validCombination;
3204 for (auto &cameraId : combination) {
3205 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003206 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003207 if (state == nullptr) {
3208 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3209 continue;
3210 }
3211 StatusInternal status = state->getStatus();
3212 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3213 continue;
3214 }
Austin Borgered99f642023-06-01 16:51:35 -07003215 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003216 continue;
3217 }
3218 validCombination.push_back(cameraId);
3219 }
3220 if (validCombination.size() != 0) {
3221 concurrentCameraIds->push_back(std::move(validCombination));
3222 }
3223 }
3224 return Status::ok();
3225}
3226
Shuzhen Wang045be6c2023-10-12 10:01:10 -07003227bool CameraService::hasCameraPermissions() const {
3228 int callingPid = CameraThreadState::getCallingPid();
3229 int callingUid = CameraThreadState::getCallingUid();
3230 AttributionSourceState attributionSource{};
3231 attributionSource.pid = callingPid;
3232 attributionSource.uid = callingUid;
3233 bool res = checkPermission(std::string(), sCameraPermission,
3234 attributionSource, std::string(), AppOpsManager::OP_NONE);
3235
3236 bool hasPermission = ((callingPid == getpid()) || res);
3237 if (!hasPermission) {
3238 ALOGE("%s: pid %d doesn't have camera permissions", __FUNCTION__, callingPid);
3239 }
3240 return hasPermission;
3241}
3242
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003243Status CameraService::isConcurrentSessionConfigurationSupported(
3244 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003245 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003246 if (!isSupported) {
3247 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3248 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3249 }
3250
3251 if (!mInitialized) {
3252 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3253 return STATUS_ERROR(ERROR_DISCONNECTED,
3254 "Camera subsystem is not available");
3255 }
3256
3257 // Check for camera permissions
Shuzhen Wang045be6c2023-10-12 10:01:10 -07003258 if (!hasCameraPermissions()) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003259 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3260 "android.permission.CAMERA needed to call"
3261 "isConcurrentSessionConfigurationSupported");
3262 }
3263
3264 status_t res =
3265 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003266 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3267 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003268 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003269 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003270 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003271 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3272 "support %s (%d)", strerror(-res), res);
3273 }
3274 return Status::ok();
3275}
3276
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003277Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3278 /*out*/
3279 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003280 return addListenerHelper(listener, cameraStatuses);
3281}
3282
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003283binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3284 std::vector<hardware::CameraStatus>* cameraStatuses) {
3285 return addListenerHelper(listener, cameraStatuses, false, true);
3286}
3287
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003288Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3289 /*out*/
3290 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003291 bool isVendorListener, bool isProcessLocalTest) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003292
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003293 ATRACE_CALL();
3294
Igor Murashkinbfc99152013-02-27 12:55:20 -08003295 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003296
Ruben Brunk3450ba72015-06-16 11:00:37 -07003297 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003298 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003299 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003300 }
3301
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003302 auto clientUid = CameraThreadState::getCallingUid();
3303 auto clientPid = CameraThreadState::getCallingPid();
Joanne Chung02c13d02023-01-16 12:58:05 +00003304 AttributionSourceState attributionSource{};
3305 attributionSource.uid = clientUid;
3306 attributionSource.pid = clientPid;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07003307
Austin Borger1c1bee02023-06-01 16:51:35 -07003308 bool openCloseCallbackAllowed = checkPermission(std::string(),
3309 sCameraOpenCloseListenerPermission, attributionSource, std::string(),
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07003310 AppOpsManager::OP_NONE);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003311
Igor Murashkinbfc99152013-02-27 12:55:20 -08003312 Mutex::Autolock lock(mServiceLock);
3313
Ruben Brunkcc776712015-02-17 20:18:47 -08003314 {
3315 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003316 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003317 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003318 ALOGW("%s: Tried to add listener %p which was already subscribed",
3319 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003320 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003321 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003322 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003323
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003324 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003325 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3326 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003327 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003328 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003329 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003330 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003331 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3332 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3333 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003334 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003335 // The listener still needs to be added to the list of listeners, regardless of what
3336 // permissions the listener process has / whether it is a vendor listener. Since it might be
3337 // eligible to listen to other camera ids.
3338 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003339 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003340 }
3341
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003342 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003343 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003344 Mutex::Autolock lock(mCameraStatesLock);
3345 for (auto& i : mCameraStates) {
Shuzhen Wang43858162020-01-10 13:42:15 -08003346 cameraStatuses->emplace_back(i.first,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003347 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Austin Borgered99f642023-06-01 16:51:35 -07003348 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string());
Igor Murashkincba2c162013-03-20 15:56:31 -07003349 }
3350 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003351 // Remove the camera statuses that should be hidden from the client, we do
3352 // this after collecting the states in order to avoid holding
3353 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3354 // the same time.
3355 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3356 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
3357 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3358 if (getSystemCameraKind(s.cameraId, &deviceKind) != OK) {
3359 ALOGE("%s: Invalid camera id %s, skipping status update",
3360 __FUNCTION__, s.cameraId.c_str());
3361 return true;
3362 }
3363 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3364 clientUid);}), cameraStatuses->end());
3365
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003366 //cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003367 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003368 for (const auto &s : *cameraStatuses) {
Austin Borgered99f642023-06-01 16:51:35 -07003369 idsChosenForCallback.insert(s.cameraId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003370 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003371
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003372 /*
3373 * Immediately signal current torch status to this listener only
3374 * This may be a subset of all the devices, so don't include it in the response directly
3375 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003376 {
3377 Mutex::Autolock al(mTorchStatusMutex);
3378 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003379 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003380 // The camera id is visible to the client. Fine to send torch
3381 // callback.
3382 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
3383 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id);
3384 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003385 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003386 }
3387
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003388 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003389}
Ruben Brunkcc776712015-02-17 20:18:47 -08003390
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003391Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003392 ATRACE_CALL();
3393
Igor Murashkinbfc99152013-02-27 12:55:20 -08003394 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3395
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003396 if (listener == 0) {
3397 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003398 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003399 }
3400
Igor Murashkinbfc99152013-02-27 12:55:20 -08003401 Mutex::Autolock lock(mServiceLock);
3402
Ruben Brunkcc776712015-02-17 20:18:47 -08003403 {
3404 Mutex::Autolock lock(mStatusListenerLock);
3405 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003406 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003407 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003408 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003409 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003410 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003411 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003412 }
3413 }
3414
3415 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3416 __FUNCTION__, listener.get());
3417
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003418 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003419}
3420
Austin Borgered99f642023-06-01 16:51:35 -07003421Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003422
3423 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003424 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3425
3426 if (parameters == NULL) {
3427 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003428 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003429 }
3430
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003431 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003432
3433 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003434 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003435 // Error logged by caller
3436 return ret;
3437 }
3438
3439 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003440
Austin Borgered99f642023-06-01 16:51:35 -07003441 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003442
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003443 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003444}
3445
Austin Borgered99f642023-06-01 16:51:35 -07003446Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003447 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003448 ATRACE_CALL();
3449
malikakashedb38962023-09-06 00:03:35 +00003450 const std::string cameraId = resolveCameraId(
3451 unresolvedCameraId, CameraThreadState::getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003452
Austin Borgered99f642023-06-01 16:51:35 -07003453 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003454
3455 switch (apiVersion) {
3456 case API_VERSION_1:
3457 case API_VERSION_2:
3458 break;
3459 default:
Austin Borgered99f642023-06-01 16:51:35 -07003460 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3461 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3462 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003463 }
3464
Austin Borger18b30a72022-10-27 12:20:29 -07003465 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003466 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003467 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003468 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3469 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3470 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003471 }
3472 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3473 int deviceVersion = deviceVersionAndTransport.first;
3474 switch (deviceVersion) {
3475 case CAMERA_DEVICE_API_VERSION_1_0:
3476 case CAMERA_DEVICE_API_VERSION_3_0:
3477 case CAMERA_DEVICE_API_VERSION_3_1:
3478 if (apiVersion == API_VERSION_2) {
3479 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003480 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003481 *isSupported = false;
3482 } else { // if (apiVersion == API_VERSION_1) {
3483 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003484 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003485 *isSupported = true;
3486 }
3487 break;
3488 case CAMERA_DEVICE_API_VERSION_3_2:
3489 case CAMERA_DEVICE_API_VERSION_3_3:
3490 case CAMERA_DEVICE_API_VERSION_3_4:
3491 case CAMERA_DEVICE_API_VERSION_3_5:
3492 case CAMERA_DEVICE_API_VERSION_3_6:
3493 case CAMERA_DEVICE_API_VERSION_3_7:
3494 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003495 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003496 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003497 break;
3498 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003499 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3500 deviceVersion, cameraId.c_str());
3501 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3502 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003503 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003504 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003505 } else {
3506 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003507 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003508 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003509}
3510
Austin Borgered99f642023-06-01 16:51:35 -07003511Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003512 /*out*/ bool *isSupported) {
3513 ATRACE_CALL();
3514
malikakashedb38962023-09-06 00:03:35 +00003515 const std::string cameraId = resolveCameraId(unresolvedCameraId,
3516 CameraThreadState::getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003517
Austin Borgered99f642023-06-01 16:51:35 -07003518 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3519 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003520
3521 return Status::ok();
3522}
3523
Cliff Wud8cae102021-03-11 01:37:42 +08003524Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003525 const std::string& packageName, const std::string& internalCamId,
3526 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003527 const sp<ICameraInjectionCallback>& callback,
3528 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003529 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003530 ATRACE_CALL();
3531
Austin Borgered99f642023-06-01 16:51:35 -07003532 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Cliff Wud8cae102021-03-11 01:37:42 +08003533 const int pid = CameraThreadState::getCallingPid();
3534 const int uid = CameraThreadState::getCallingUid();
3535 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3536 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3537 "Permission Denial: no permission to inject camera");
3538 }
3539
3540 ALOGV(
3541 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3542 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003543 __FUNCTION__, packageName.c_str(),
3544 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003545
Cliff Wud3a05312021-04-26 23:07:31 +08003546 {
3547 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003548 mInjectionInternalCamId = internalCamId;
3549 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003550 mInjectionStatusListener->addListener(callback);
3551 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003552 status_t res = NO_ERROR;
3553 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3554 // If the client already exists, we can directly connect to the camera device through the
3555 // client's injectCamera(), otherwise we need to wait until the client is established
3556 // (execute connectHelper()) before injecting the camera to the camera device.
3557 if (clientDescriptor != nullptr) {
3558 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003559 sp<BasicClient> clientSp = clientDescriptor->getValue();
3560 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3561 if(res != OK) {
3562 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3563 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003564 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003565 }
3566 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08003567 if(res != OK) {
3568 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3569 }
3570 } else {
3571 mInjectionInitPending = true;
3572 }
3573 }
Cliff Wud8cae102021-03-11 01:37:42 +08003574
Cliff Wud3a05312021-04-26 23:07:31 +08003575 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003576}
3577
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003578Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003579 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003580 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3581 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3582 return Status::ok();
3583}
3584
Ruben Brunkcc776712015-02-17 20:18:47 -08003585void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003586 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003587 for (auto& i : mActiveClientManager.getAll()) {
3588 auto clientSp = i->getValue();
3589 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003590 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003591 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003592 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003593 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003594 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003595}
3596
Ruben Brunkcc776712015-02-17 20:18:47 -08003597bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003598 bool ret = false;
3599 {
3600 // Acquire mServiceLock and prevent other clients from connecting
3601 std::unique_ptr<AutoConditionLock> lock =
3602 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003603
Igor Murashkin634a5152013-02-20 17:15:11 -08003604
Ruben Brunkcc776712015-02-17 20:18:47 -08003605 std::vector<sp<BasicClient>> evicted;
3606 for (auto& i : mActiveClientManager.getAll()) {
3607 auto clientSp = i->getValue();
3608 if (clientSp.get() == nullptr) {
3609 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3610 mActiveClientManager.remove(i);
3611 continue;
3612 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003613 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003614 mActiveClientManager.remove(i);
3615 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003616
Ruben Brunkcc776712015-02-17 20:18:47 -08003617 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003618 clientSp->notifyError(
3619 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003620 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003621 }
3622 }
3623
Ruben Brunkcc776712015-02-17 20:18:47 -08003624 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3625 // other clients from connecting in mServiceLockWrapper if held
3626 mServiceLock.unlock();
3627
Ruben Brunk36597b22015-03-20 22:15:57 -07003628 // Do not clear caller identity, remote caller should be client proccess
3629
Ruben Brunkcc776712015-02-17 20:18:47 -08003630 for (auto& i : evicted) {
3631 if (i.get() != nullptr) {
3632 i->disconnect();
3633 ret = true;
3634 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003635 }
3636
Ruben Brunkcc776712015-02-17 20:18:47 -08003637 // Reacquire mServiceLock
3638 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003639
Ruben Brunkcc776712015-02-17 20:18:47 -08003640 } // lock is destroyed, allow further connect calls
3641
3642 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003643}
3644
Ruben Brunkcc776712015-02-17 20:18:47 -08003645std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003646 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003647 std::shared_ptr<CameraState> state;
3648 {
3649 Mutex::Autolock lock(mCameraStatesLock);
3650 auto iter = mCameraStates.find(cameraId);
3651 if (iter != mCameraStates.end()) {
3652 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003653 }
3654 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003655 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003656}
3657
Austin Borgered99f642023-06-01 16:51:35 -07003658sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003659 // Remove from active clients list
3660 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3661 if (clientDescriptorPtr == nullptr) {
3662 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003663 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003664 return sp<BasicClient>{nullptr};
3665 }
3666
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003667 sp<BasicClient> client = clientDescriptorPtr->getValue();
3668 if (client.get() != nullptr) {
3669 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3670 }
3671 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003672}
3673
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003674void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003675 // Acquire mServiceLock and prevent other clients from connecting
3676 std::unique_ptr<AutoConditionLock> lock =
3677 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3678
Ruben Brunk6267b532015-04-30 17:44:07 -07003679 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003680 for (size_t i = 0; i < newUserIds.size(); i++) {
3681 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003682 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003683 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003684 return;
3685 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003686 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003687 }
3688
Ruben Brunka8ca9152015-04-07 14:23:40 -07003689
Ruben Brunk6267b532015-04-30 17:44:07 -07003690 if (newAllowedUsers == mAllowedUsers) {
3691 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3692 return;
3693 }
3694
3695 logUserSwitch(mAllowedUsers, newAllowedUsers);
3696
3697 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003698
3699 // Current user has switched, evict all current clients.
3700 std::vector<sp<BasicClient>> evicted;
3701 for (auto& i : mActiveClientManager.getAll()) {
3702 auto clientSp = i->getValue();
3703
3704 if (clientSp.get() == nullptr) {
3705 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3706 continue;
3707 }
3708
Ruben Brunk6267b532015-04-30 17:44:07 -07003709 // Don't evict clients that are still allowed.
3710 uid_t clientUid = clientSp->getClientUid();
3711 userid_t clientUserId = multiuser_get_user_id(clientUid);
3712 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3713 continue;
3714 }
3715
Ruben Brunk36597b22015-03-20 22:15:57 -07003716 evicted.push_back(clientSp);
3717
Ruben Brunk36597b22015-03-20 22:15:57 -07003718 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003719 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003720
Ruben Brunk36597b22015-03-20 22:15:57 -07003721 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003722 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003723 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003724 " to user switch.", i->getKey().c_str(),
3725 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003726 i->getOwnerId(), i->getPriority().getScore(),
3727 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003728
3729 }
3730
3731 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3732 // blocking other clients from connecting in mServiceLockWrapper if held.
3733 mServiceLock.unlock();
3734
3735 // Clear caller identity temporarily so client disconnect PID checks work correctly
Jayant Chowdhary12361932018-08-27 14:46:13 -07003736 int64_t token = CameraThreadState::clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003737
3738 for (auto& i : evicted) {
3739 i->disconnect();
3740 }
3741
Jayant Chowdhary12361932018-08-27 14:46:13 -07003742 CameraThreadState::restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003743
3744 // Reacquire mServiceLock
3745 mServiceLock.lock();
3746}
Ruben Brunkcc776712015-02-17 20:18:47 -08003747
Austin Borgered99f642023-06-01 16:51:35 -07003748void CameraService::logEvent(const std::string &event) {
3749 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003750 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003751 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003752 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003753 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003754 mEventLog.add(msg);
3755 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3756 // Error event not added to the dumpsys log before
3757 mEventLog.add(msg);
3758 sServiceErrorEventSet.insert(msg);
3759 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003760}
3761
Austin Borgered99f642023-06-01 16:51:35 -07003762void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3763 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003764 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003765 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3766 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003767}
3768
Austin Borgered99f642023-06-01 16:51:35 -07003769void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3770 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003771 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003772 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3773 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003774}
3775
Austin Borgered99f642023-06-01 16:51:35 -07003776void CameraService::logConnected(const std::string &cameraId, int clientPid,
3777 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003778 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003779 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3780 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003781}
3782
Austin Borgered99f642023-06-01 16:51:35 -07003783void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3784 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003785 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003786 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3787 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003788}
3789
Austin Borgered99f642023-06-01 16:51:35 -07003790void CameraService::logRejected(const std::string &cameraId, int clientPid,
3791 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003792 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003793 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3794 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003795}
3796
Austin Borgered99f642023-06-01 16:51:35 -07003797void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3798 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003799 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003800 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3801 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003802}
3803
Ruben Brunk6267b532015-04-30 17:44:07 -07003804void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3805 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003806 std::string newUsers = toString(newUserIds);
3807 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003808 if (oldUsers.size() == 0) {
3809 oldUsers = "<None>";
3810 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003811 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003812 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3813 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003814}
3815
Austin Borgered99f642023-06-01 16:51:35 -07003816void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003817 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003818 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003819}
3820
Austin Borgered99f642023-06-01 16:51:35 -07003821void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003822 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003823 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003824}
3825
Austin Borgered99f642023-06-01 16:51:35 -07003826void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003827 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003828 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003829}
3830
Austin Borgered99f642023-06-01 16:51:35 -07003831void CameraService::logServiceError(const std::string &msg, int errorCode) {
3832 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3833 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003834}
3835
Ruben Brunk36597b22015-03-20 22:15:57 -07003836status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3837 uint32_t flags) {
3838
Mathias Agopian65ab4712010-07-14 17:59:35 -07003839 // Permission checks
3840 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003841 case SHELL_COMMAND_TRANSACTION: {
3842 int in = data.readFileDescriptor();
3843 int out = data.readFileDescriptor();
3844 int err = data.readFileDescriptor();
3845 int argc = data.readInt32();
3846 Vector<String16> args;
3847 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3848 args.add(data.readString16());
3849 }
3850 sp<IBinder> unusedCallback;
3851 sp<IResultReceiver> resultReceiver;
3852 status_t status;
3853 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3854 return status;
3855 }
3856 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3857 return status;
3858 }
3859 status = shellCommand(in, out, err, args);
3860 if (resultReceiver != nullptr) {
3861 resultReceiver->send(status);
3862 }
3863 return NO_ERROR;
3864 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003865 }
3866
3867 return BnCameraService::onTransact(code, data, reply, flags);
3868}
3869
Mathias Agopian65ab4712010-07-14 17:59:35 -07003870// We share the media players for shutter and recording sound for all clients.
3871// A reference count is kept to determine when we will actually release the
3872// media players.
3873
Jaekyun Seokef498052018-03-23 13:09:44 +09003874sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3875 sp<MediaPlayer> mp = new MediaPlayer();
3876 status_t error;
3877 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003878 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003879 error = mp->prepare();
3880 }
3881 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003882 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003883 mp->disconnect();
3884 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003885 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003886 }
3887 return mp;
3888}
3889
username5755fea2018-12-27 09:48:08 +08003890void CameraService::increaseSoundRef() {
3891 Mutex::Autolock lock(mSoundLock);
3892 mSoundRef++;
3893}
3894
3895void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003896 ATRACE_CALL();
3897
username5755fea2018-12-27 09:48:08 +08003898 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3899 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3900 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3901 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3902 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3903 }
3904 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3905 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3906 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3907 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003908 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003909 }
3910 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3911 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3912 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3913 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3914 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003915 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003916}
3917
username5755fea2018-12-27 09:48:08 +08003918void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003919 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003920 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921 if (--mSoundRef) return;
3922
3923 for (int i = 0; i < NUM_SOUNDS; i++) {
3924 if (mSoundPlayer[i] != 0) {
3925 mSoundPlayer[i]->disconnect();
3926 mSoundPlayer[i].clear();
3927 }
3928 }
3929}
3930
3931void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003932 ATRACE_CALL();
3933
Mathias Agopian65ab4712010-07-14 17:59:35 -07003934 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003935 if (kind < 0 || kind >= NUM_SOUNDS) {
3936 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3937 return;
3938 }
3939
Mathias Agopian65ab4712010-07-14 17:59:35 -07003940 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003941 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003942 sp<MediaPlayer> player = mSoundPlayer[kind];
3943 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003944 player->seekTo(0);
3945 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003946 }
3947}
3948
3949// ----------------------------------------------------------------------------
3950
3951CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07003952 const sp<ICameraClient>& cameraClient,
Austin Borgered99f642023-06-01 16:51:35 -07003953 const std::string& clientPackageName, bool systemNativeClient,
3954 const std::optional<std::string>& clientFeatureId,
3955 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07003956 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003957 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003958 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08003959 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08003960 IInterface::asBinder(cameraClient),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003961 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07003962 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003963 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003964 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08003965 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08003966{
Jayant Chowdhary12361932018-08-27 14:46:13 -07003967 int callingPid = CameraThreadState::getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003968 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003969
Igor Murashkin44cfcf02013-03-01 16:22:28 -08003970 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971
username5755fea2018-12-27 09:48:08 +08003972 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003973
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003974 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003975}
3976
Mathias Agopian65ab4712010-07-14 17:59:35 -07003977// tear down the client
3978CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07003979 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08003980 mDestructionStarted = true;
3981
username5755fea2018-12-27 09:48:08 +08003982 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07003983 // unconditionally disconnect. function is idempotent
3984 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985}
3986
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003987sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
3988
Igor Murashkin634a5152013-02-20 17:15:11 -08003989CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08003990 const sp<IBinder>& remoteCallback,
Austin Borgered99f642023-06-01 16:51:35 -07003991 const std::string& clientPackageName, bool nativeClient,
3992 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003993 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07003994 int servicePid, bool overrideToPortrait):
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07003995 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07003996 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08003997 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
3998 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08003999 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004000 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004001 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004002 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004003 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004004 mRemoteBinder(remoteCallback),
4005 mOpsActive(false),
4006 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004007{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004008 if (sCameraService == nullptr) {
4009 sCameraService = cameraService;
4010 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004011
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004012 // There are 2 scenarios in which a client won't have AppOps operations
4013 // (both scenarios : native clients)
4014 // 1) It's an system native client*, the package name will be empty
4015 // and it will return from this function in the previous if condition
4016 // (This is the same as the previously existing behavior).
4017 // 2) It is a system native client, but its package name has been
4018 // modified for debugging, however it still must not use AppOps since
4019 // the package name is not a real one.
4020 //
4021 // * system native client - native client with UID < AID_APP_START. It
4022 // doesn't exclude clients not on the system partition.
4023 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004024 mAppOpsManager = std::make_unique<AppOpsManager>();
4025 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004026
4027 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004028}
4029
4030CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004031 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004032 mDestructionStarted = true;
4033}
4034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004035binder::Status CameraService::BasicClient::disconnect() {
4036 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004037 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004038 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004039 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004040 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004041
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004042 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004043 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004044 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004045 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004046
4047 sp<IBinder> remote = getRemote();
4048 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004049 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004050 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004051
4052 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004053 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004054 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004055 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004056 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004057
Igor Murashkincba2c162013-03-20 15:56:31 -07004058 // client shouldn't be able to call into us anymore
4059 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004060
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004061 const auto& mActivityManager = getActivityManager();
4062 if (mActivityManager) {
4063 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
4064 CameraThreadState::getCallingUid(),
4065 CameraThreadState::getCallingPid());
4066 }
4067
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004068 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004069}
4070
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004071status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4072 // No dumping of clients directly over Binder,
4073 // must go through CameraService::dump
4074 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Jayant Chowdhary12361932018-08-27 14:46:13 -07004075 CameraThreadState::getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004076 return OK;
4077}
4078
Austin Borgered99f642023-06-01 16:51:35 -07004079status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004080 // Can't watch tags directly, must go through CameraService::startWatchingTags
4081 return OK;
4082}
4083
4084status_t CameraService::BasicClient::stopWatchingTags(int) {
4085 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4086 return OK;
4087}
4088
4089status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4090 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4091 return OK;
4092}
4093
Austin Borgered99f642023-06-01 16:51:35 -07004094std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004095 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004096}
4097
Emilian Peev8b64f282021-03-25 16:49:57 -07004098int CameraService::BasicClient::getCameraFacing() const {
4099 return mCameraFacing;
4100}
4101
4102int CameraService::BasicClient::getCameraOrientation() const {
4103 return mOrientation;
4104}
Ruben Brunkcc776712015-02-17 20:18:47 -08004105
4106int CameraService::BasicClient::getClientPid() const {
4107 return mClientPid;
4108}
4109
Ruben Brunk6267b532015-04-30 17:44:07 -07004110uid_t CameraService::BasicClient::getClientUid() const {
4111 return mClientUid;
4112}
4113
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004114bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4115 // Defaults to API2.
4116 return level == API_2;
4117}
4118
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004119status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004120 {
4121 Mutex::Autolock l(mAudioRestrictionLock);
4122 mAudioRestriction = mode;
4123 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004124 sCameraService->updateAudioRestriction();
4125 return OK;
4126}
4127
4128int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004129 return sCameraService->updateAudioRestriction();
4130}
4131
4132int32_t CameraService::BasicClient::getAudioRestriction() const {
4133 Mutex::Autolock l(mAudioRestrictionLock);
4134 return mAudioRestriction;
4135}
4136
4137bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4138 switch (mode) {
4139 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4140 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4141 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4142 return true;
4143 default:
4144 return false;
4145 }
4146}
4147
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004148status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4149 if (mode == AppOpsManager::MODE_ERRORED) {
4150 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004151 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004152 return PERMISSION_DENIED;
4153 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4154 // If the calling Uid is trusted (a native service), the AppOpsManager could
4155 // return MODE_IGNORED. Do not treat such case as error.
4156 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4157 mClientPackageName);
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004158 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004159 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004160 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4161 // We prefer to successfully open the camera and perform camera muting
4162 // or blocking in connectHelper as handleAppOpMode can be called before the
4163 // connection has been fully established and at that time camera muting
4164 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004165 if (!isUidActive || !isCameraPrivacyEnabled) {
4166 ALOGI("Camera %s: Access for \"%s\" has been restricted",
Austin Borgered99f642023-06-01 16:51:35 -07004167 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004168 // Return the same error as for device policy manager rejection
4169 return -EACCES;
4170 }
4171 }
4172 return OK;
4173}
4174
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004175status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004176 ATRACE_CALL();
4177
Igor Murashkine6800ce2013-03-04 17:25:57 -08004178 {
4179 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004180 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004181 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004182 if (mAppOpsManager != nullptr) {
4183 // Notify app ops that the camera is not available
4184 mOpsCallback = new OpsCallback(this);
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004185 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004186 toString16(mClientPackageName), mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004187
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004188 // Just check for camera acccess here on open - delay startOp until
4189 // camera frames start streaming in startCameraStreamingOps
4190 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004191 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004192 status_t res = handleAppOpMode(mode);
4193 if (res != OK) {
4194 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004195 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004196 }
4197
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004198 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004199
4200 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004201 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004202
Austin Borgerdddb7552023-03-30 17:53:01 -07004203 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004204
Shuzhen Wang695044d2020-03-06 09:02:23 -08004205 // Notify listeners of camera open/close status
4206 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4207
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004208 return OK;
4209}
4210
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004211status_t CameraService::BasicClient::startCameraStreamingOps() {
4212 ATRACE_CALL();
4213
4214 if (!mOpsActive) {
4215 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4216 return INVALID_OPERATION;
4217 }
4218 if (mOpsStreaming) {
4219 ALOGV("%s: Streaming already active!", __FUNCTION__);
4220 return OK;
4221 }
4222
4223 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004224 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004225
4226 if (mAppOpsManager != nullptr) {
4227 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004228 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4229 toString16(mClientFeatureId),
4230 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004231 status_t res = handleAppOpMode(mode);
4232 if (res != OK) {
4233 return res;
4234 }
4235 }
4236
4237 mOpsStreaming = true;
4238
4239 return OK;
4240}
4241
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004242status_t CameraService::BasicClient::noteAppOp() {
4243 ATRACE_CALL();
4244
4245 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004246 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004247
4248 // noteAppOp is only used for when camera mute is not supported, in order
4249 // to trigger the sensor privacy "Unblock" dialog
4250 if (mAppOpsManager != nullptr) {
4251 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004252 toString16(mClientPackageName), toString16(mClientFeatureId),
4253 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004254 status_t res = handleAppOpMode(mode);
4255 if (res != OK) {
4256 return res;
4257 }
4258 }
4259
4260 return OK;
4261}
4262
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004263status_t CameraService::BasicClient::finishCameraStreamingOps() {
4264 ATRACE_CALL();
4265
4266 if (!mOpsActive) {
4267 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4268 return INVALID_OPERATION;
4269 }
4270 if (!mOpsStreaming) {
4271 ALOGV("%s: Streaming not active!", __FUNCTION__);
4272 return OK;
4273 }
4274
4275 if (mAppOpsManager != nullptr) {
4276 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004277 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004278 mOpsStreaming = false;
4279 }
4280
4281 return OK;
4282}
4283
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004284status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004285 ATRACE_CALL();
4286
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004287 if (mOpsStreaming) {
4288 // Make sure we've notified everyone about camera stopping
4289 finishCameraStreamingOps();
4290 }
4291
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004292 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004293 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004294 mOpsActive = false;
4295
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004296 // This function is called when a client disconnects. This should
4297 // release the camera, but actually only if it was in a proper
4298 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004299 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004300 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004301
Ruben Brunkcc776712015-02-17 20:18:47 -08004302 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004303 sCameraService->updateStatus(StatusInternal::PRESENT,
4304 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004305 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004306 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004307 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4308 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004309 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004310 mOpsCallback.clear();
4311
Austin Borgerdddb7552023-03-30 17:53:01 -07004312 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004313
Shuzhen Wang695044d2020-03-06 09:02:23 -08004314 // Notify listeners of camera open/close status
4315 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4316
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004317 return OK;
4318}
4319
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004320void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004321 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004322 if (mAppOpsManager == nullptr) {
4323 return;
4324 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004325 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004326 if (op != AppOpsManager::OP_CAMERA) {
4327 ALOGW("Unexpected app ops notification received: %d", op);
4328 return;
4329 }
4330
4331 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004332 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004333 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004334 ALOGV("checkOp returns: %d, %s ", res,
4335 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4336 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4337 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4338 "UNKNOWN");
4339
Shuzhen Wang64900852021-02-05 09:03:29 -08004340 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004341 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4342 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004343 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004344 } else if (res == AppOpsManager::MODE_IGNORED) {
4345 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004346 bool isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004347 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004348 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d",
4349 mCameraIdStr.c_str(), mClientPackageName.c_str(),
4350 mUidIsTrusted, isUidActive);
Shuzhen Wang64900852021-02-05 09:03:29 -08004351 // If the calling Uid is trusted (a native service), or the client Uid is active (WAR for
4352 // b/175320666), the AppOpsManager could return MODE_IGNORED. Do not treat such cases as
4353 // error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004354 if (!mUidIsTrusted) {
4355 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4356 setCameraMute(true);
4357 } else if (!isUidActive
4358 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4359 block();
4360 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004361 }
Evan Severson09ab4002021-02-10 14:15:19 -08004362 } else if (res == AppOpsManager::MODE_ALLOWED) {
4363 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004364 }
4365}
4366
Svet Ganova453d0d2018-01-11 15:37:58 -08004367void CameraService::BasicClient::block() {
4368 ATRACE_CALL();
4369
4370 // Reset the client PID to allow server-initiated disconnect,
4371 // and to prevent further calls by client.
Jayant Chowdhary12361932018-08-27 14:46:13 -07004372 mClientPid = CameraThreadState::getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004373 CaptureResultExtras resultExtras; // a dummy result (invalid)
4374 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4375 disconnect();
4376}
4377
Mathias Agopian65ab4712010-07-14 17:59:35 -07004378// ----------------------------------------------------------------------------
4379
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004380void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004381 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004382 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004383 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4384 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4385 api1ErrorCode = CAMERA_ERROR_DISABLED;
4386 }
4387 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004388 } else {
4389 ALOGE("mRemoteCallback is NULL!!");
4390 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004391}
4392
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004393// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004394binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004395 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004396 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004397}
4398
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004399bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4400 return level == API_1;
4401}
4402
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004403CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4404 mClient(client) {
4405}
4406
4407void CameraService::Client::OpsCallback::opChanged(int32_t op,
4408 const String16& packageName) {
4409 sp<BasicClient> client = mClient.promote();
4410 if (client != NULL) {
4411 client->opChanged(op, packageName);
4412 }
4413}
4414
Mathias Agopian65ab4712010-07-14 17:59:35 -07004415// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004416// UidPolicy
4417// ----------------------------------------------------------------------------
4418
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004419void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004420 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004421 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004422
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004423 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004424 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004425 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004426 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004427 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4428 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004429 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004430 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004431 if (res == OK) {
4432 mRegistered = true;
4433 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004434 } else {
4435 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004436 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004437}
4438
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004439void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004440 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004441 return;
4442 }
4443
4444 registerWithActivityManager();
4445}
4446
4447void CameraService::UidPolicy::registerSelf() {
4448 // Use check service to see if the activity service is available
4449 // If not available then register for notifications, instead of blocking
4450 // till the service is ready
4451 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004452 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004453 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004454 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004455 } else {
4456 registerWithActivityManager();
4457 }
4458}
4459
Svet Ganova453d0d2018-01-11 15:37:58 -08004460void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004461 Mutex::Autolock _l(mUidLock);
4462
Steven Moreland2f348142019-07-02 15:59:07 -07004463 mAm.unregisterUidObserver(this);
4464 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004465 mRegistered = false;
4466 mActiveUids.clear();
4467 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004468}
4469
4470void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4471 onUidIdle(uid, disabled);
4472}
4473
4474void CameraService::UidPolicy::onUidActive(uid_t uid) {
4475 Mutex::Autolock _l(mUidLock);
4476 mActiveUids.insert(uid);
4477}
4478
4479void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4480 bool deleted = false;
4481 {
4482 Mutex::Autolock _l(mUidLock);
4483 if (mActiveUids.erase(uid) > 0) {
4484 deleted = true;
4485 }
4486 }
4487 if (deleted) {
4488 sp<CameraService> service = mService.promote();
4489 if (service != nullptr) {
4490 service->blockClientsForUid(uid);
4491 }
4492 }
4493}
4494
Emilian Peev53722fa2019-02-22 17:47:20 -08004495void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004496 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004497 bool procStateChange = false;
4498 {
4499 Mutex::Autolock _l(mUidLock);
4500 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4501 mMonitoredUids[uid].procState != procState) {
4502 mMonitoredUids[uid].procState = procState;
4503 procStateChange = true;
4504 }
4505 }
4506
4507 if (procStateChange) {
4508 sp<CameraService> service = mService.promote();
4509 if (service != nullptr) {
4510 service->notifyMonitoredUids();
4511 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004512 }
4513}
4514
Austin Borgerdddb7552023-03-30 17:53:01 -07004515/**
4516 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4517 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4518 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4519 * monitoredUids. If it is revised above some other monitoredUid, signal
4520 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4521 * foreground apps in split screen - state changes will capture all other cases.
4522 */
4523void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4524 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004525 {
4526 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004527 auto it = mMonitoredUids.find(uid);
4528
4529 if (it != mMonitoredUids.end()) {
4530 if (it->second.hasCamera) {
4531 for (auto &monitoredUid : mMonitoredUids) {
4532 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004533 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004534 notifyUidSet.emplace(monitoredUid.first);
4535 }
4536 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004537 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004538 notifyUidSet.emplace(uid);
4539 } else {
4540 for (auto &monitoredUid : mMonitoredUids) {
4541 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004542 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004543 notifyUidSet.emplace(uid);
4544 }
4545 }
4546 }
4547 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004548 }
4549 }
4550
Austin Borgerdddb7552023-03-30 17:53:01 -07004551 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004552 sp<CameraService> service = mService.promote();
4553 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004554 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004555 }
4556 }
4557}
4558
Austin Borgerdddb7552023-03-30 17:53:01 -07004559/**
4560 * Register a uid for monitoring, and note whether it owns a camera.
4561 */
4562void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004563 Mutex::Autolock _l(mUidLock);
4564 auto it = mMonitoredUids.find(uid);
4565 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004566 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004567 } else {
Austin Borger65577682022-02-17 00:25:43 +00004568 MonitoredUid monitoredUid;
4569 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004570 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004571 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004572 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004573 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004574 if (res != OK) {
4575 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4576 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004577 }
4578
4579 if (openCamera) {
4580 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004581 }
4582}
4583
Austin Borgerdddb7552023-03-30 17:53:01 -07004584/**
4585 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4586 */
4587void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004588 Mutex::Autolock _l(mUidLock);
4589 auto it = mMonitoredUids.find(uid);
4590 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004591 it->second.refCount--;
4592 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004593 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004594 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004595 if (res != OK) {
4596 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4597 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004598 } else if (closeCamera) {
4599 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004600 }
4601 } else {
4602 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4603 }
4604}
4605
Austin Borgered99f642023-06-01 16:51:35 -07004606bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004607 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004608 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004609}
4610
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004611static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4612static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004613
Austin Borgered99f642023-06-01 16:51:35 -07004614bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004615 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004616 // If activity manager is unreachable, assume everything is active
4617 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004618 return true;
4619 }
4620 auto it = mOverrideUids.find(uid);
4621 if (it != mOverrideUids.end()) {
4622 return it->second;
4623 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004624 bool active = mActiveUids.find(uid) != mActiveUids.end();
4625 if (!active) {
4626 // We want active UIDs to always access camera with their first attempt since
4627 // there is no guarantee the app is robustly written and would retry getting
4628 // the camera on failure. The inverse case is not a problem as we would take
4629 // camera away soon once we get the callback that the uid is no longer active.
4630 ActivityManager am;
4631 // Okay to access with a lock held as UID changes are dispatched without
4632 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004633 int64_t startTimeMillis = 0;
4634 do {
4635 // TODO: Fix this b/109950150!
4636 // Okay this is a hack. There is a race between the UID turning active and
4637 // activity being resumed. The proper fix is very risky, so we temporary add
4638 // some polling which should happen pretty rarely anyway as the race is hard
4639 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004640 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004641 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004642 if (active) {
4643 break;
4644 }
4645 if (startTimeMillis <= 0) {
4646 startTimeMillis = uptimeMillis();
4647 }
4648 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004649 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004650 if (remainingTimeMillis <= 0) {
4651 break;
4652 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004653 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4654
4655 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004656 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004657 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004658 } while (true);
4659
Svet Ganov7b4ab782018-03-25 12:48:10 -07004660 if (active) {
4661 // Now that we found out the UID is actually active, cache that
4662 mActiveUids.insert(uid);
4663 }
4664 }
4665 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004666}
4667
Varun Shahb42f1eb2019-04-16 14:45:13 -07004668int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4669 Mutex::Autolock _l(mUidLock);
4670 return getProcStateLocked(uid);
4671}
4672
4673int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4674 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4675 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004676 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004677 }
4678 return procState;
4679}
4680
Austin Borgered99f642023-06-01 16:51:35 -07004681void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4682 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004683 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004684}
4685
Austin Borgered99f642023-06-01 16:51:35 -07004686void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004687 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004688}
4689
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004690void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4691 Mutex::Autolock _l(mUidLock);
4692 ALOGV("UidPolicy: ActivityManager has died");
4693 mRegistered = false;
4694 mActiveUids.clear();
4695}
4696
Austin Borgered99f642023-06-01 16:51:35 -07004697void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004698 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004699 bool wasActive = false;
4700 bool isActive = false;
4701 {
4702 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004703 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004704 mOverrideUids.erase(uid);
4705 if (insert) {
4706 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4707 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004708 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004709 }
4710 if (wasActive != isActive && !isActive) {
4711 sp<CameraService> service = mService.promote();
4712 if (service != nullptr) {
4713 service->blockClientsForUid(uid);
4714 }
4715 }
4716}
4717
4718// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004719// SensorPrivacyPolicy
4720// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004721
4722void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4723{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004724 Mutex::Autolock _l(mSensorPrivacyLock);
4725 if (mRegistered) {
4726 return;
4727 }
Evan Severson09ab4002021-02-10 14:15:19 -08004728 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004729 mSpm.addSensorPrivacyListener(this);
4730 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
4731 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004732 if (res == OK) {
4733 mRegistered = true;
4734 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4735 }
4736}
4737
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004738void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4739 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004740 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004741 return;
4742 }
4743
4744 registerWithSensorPrivacyManager();
4745}
4746
4747void CameraService::SensorPrivacyPolicy::registerSelf() {
4748 // Use checkservice to see if the sensor_privacy service is available
4749 // If service is not available then register for notification
4750 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004751 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004752 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004753 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004754 } else {
4755 registerWithSensorPrivacyManager();
4756 }
4757}
4758
Michael Grooverd1d435a2018-12-18 17:39:42 -08004759void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4760 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004761 mSpm.removeSensorPrivacyListener(this);
4762 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004763 mRegistered = false;
4764 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4765}
4766
4767bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004768 if (!mRegistered) {
4769 registerWithSensorPrivacyManager();
4770 }
4771
Michael Grooverd1d435a2018-12-18 17:39:42 -08004772 Mutex::Autolock _l(mSensorPrivacyLock);
4773 return mSensorPrivacyEnabled;
4774}
4775
Evan Seversond0b69922022-01-27 10:47:34 -08004776bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004777 if (!hasCameraPrivacyFeature()) {
4778 return false;
4779 }
Evan Seversond0b69922022-01-27 10:47:34 -08004780 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004781}
4782
Evan Seversond0b69922022-01-27 10:47:34 -08004783binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004784 int toggleType __unused, int sensor __unused, bool enabled) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08004785 {
4786 Mutex::Autolock _l(mSensorPrivacyLock);
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004787 mSensorPrivacyEnabled = enabled;
Michael Grooverd1d435a2018-12-18 17:39:42 -08004788 }
4789 // if sensor privacy is enabled then block all clients from accessing the camera
Priyanka Advani1a09fd92024-02-10 01:28:37 +00004790 if (enabled) {
4791 sp<CameraService> service = mService.promote();
4792 if (service != nullptr) {
4793 service->blockAllClients();
4794 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004795 }
4796 return binder::Status::ok();
4797}
4798
4799void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4800 Mutex::Autolock _l(mSensorPrivacyLock);
4801 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4802 mRegistered = false;
4803}
4804
Evan Severson09ab4002021-02-10 14:15:19 -08004805bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004806 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4807 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4808 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4809 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4810 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004811}
4812
Michael Grooverd1d435a2018-12-18 17:39:42 -08004813// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004814// CameraState
4815// ----------------------------------------------------------------------------
4816
Austin Borgered99f642023-06-01 16:51:35 -07004817CameraService::CameraState::CameraState(const std::string& id, int cost,
4818 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004819 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004820 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004821 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004822
4823CameraService::CameraState::~CameraState() {}
4824
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004825CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004826 Mutex::Autolock lock(mStatusLock);
4827 return mStatus;
4828}
4829
Austin Borgered99f642023-06-01 16:51:35 -07004830std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004831 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004832 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004833 return res;
4834}
4835
Ruben Brunkcc776712015-02-17 20:18:47 -08004836CameraParameters CameraService::CameraState::getShimParams() const {
4837 return mShimParams;
4838}
4839
4840void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4841 mShimParams = params;
4842}
4843
4844int CameraService::CameraState::getCost() const {
4845 return mCost;
4846}
4847
Austin Borgered99f642023-06-01 16:51:35 -07004848std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004849 return mConflicting;
4850}
4851
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004852SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4853 return mSystemCameraKind;
4854}
4855
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004856bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4857 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4858 != mPhysicalCameras.end();
4859}
4860
Austin Borgered99f642023-06-01 16:51:35 -07004861bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004862 Mutex::Autolock lock(mStatusLock);
4863 auto result = mUnavailablePhysicalIds.insert(physicalId);
4864 return result.second;
4865}
4866
Austin Borgered99f642023-06-01 16:51:35 -07004867bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004868 Mutex::Autolock lock(mStatusLock);
4869 auto count = mUnavailablePhysicalIds.erase(physicalId);
4870 return count > 0;
4871}
4872
Austin Borgered99f642023-06-01 16:51:35 -07004873void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004874 Mutex::Autolock lock(mStatusLock);
4875 mClientPackage = clientPackage;
4876}
4877
Austin Borgered99f642023-06-01 16:51:35 -07004878std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07004879 Mutex::Autolock lock(mStatusLock);
4880 return mClientPackage;
4881}
4882
Ruben Brunkcc776712015-02-17 20:18:47 -08004883// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07004884// ClientEventListener
4885// ----------------------------------------------------------------------------
4886
4887void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07004888 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004889 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004890 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004891 if (basicClient.get() != nullptr) {
4892 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004893 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004894 static_cast<int>(basicClient->getClientUid()));
4895 }
4896}
4897
4898void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07004899 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07004900 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07004901 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07004902 if (basicClient.get() != nullptr) {
4903 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07004904 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07004905 static_cast<int>(basicClient->getClientUid()));
4906 }
4907}
4908
4909
4910// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004911// CameraClientManager
4912// ----------------------------------------------------------------------------
4913
Ruben Brunk99e69712015-05-26 17:25:07 -07004914CameraService::CameraClientManager::CameraClientManager() {
4915 setListener(std::make_shared<ClientEventListener>());
4916}
4917
Ruben Brunkcc776712015-02-17 20:18:47 -08004918CameraService::CameraClientManager::~CameraClientManager() {}
4919
4920sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07004921 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004922 auto descriptor = get(id);
4923 if (descriptor == nullptr) {
4924 return sp<BasicClient>{nullptr};
4925 }
4926 return descriptor->getValue();
4927}
4928
Austin Borgered99f642023-06-01 16:51:35 -07004929std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004930 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07004931 std::ostringstream ret;
4932 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08004933 bool hasAny = false;
4934 for (auto& i : all) {
4935 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07004936 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08004937 int32_t cost = i->getCost();
4938 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00004939 int32_t score = i->getPriority().getScore();
4940 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08004941 auto conflicting = i->getConflicting();
4942 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07004943 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07004944 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08004945 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004946 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07004947 uid_t clientUid = clientSp->getClientUid();
4948 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004949 }
Austin Borgered99f642023-06-01 16:51:35 -07004950 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
4951 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08004952
Ruben Brunk6267b532015-04-30 17:44:07 -07004953 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07004954 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07004955 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004956 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07004957 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004958 }
4959
Austin Borgered99f642023-06-01 16:51:35 -07004960 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08004961 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07004962 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004963 }
Austin Borgered99f642023-06-01 16:51:35 -07004964 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08004965 }
Austin Borgered99f642023-06-01 16:51:35 -07004966 if (hasAny) ret << "\n";
4967 ret << "]\n";
4968 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08004969}
4970
4971CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07004972 const std::string& key, const sp<BasicClient>& value, int32_t cost,
4973 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004974 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004975
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004976 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07004977 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07004978
Austin Borgered99f642023-06-01 16:51:35 -07004979 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004980 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
4981 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08004982}
4983
4984CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00004985 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004986 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004987 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00004988 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004989 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
4990 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08004991}
4992
4993// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08004994// InjectionStatusListener
4995// ----------------------------------------------------------------------------
4996
4997void CameraService::InjectionStatusListener::addListener(
4998 const sp<ICameraInjectionCallback>& callback) {
4999 Mutex::Autolock lock(mListenerLock);
5000 if (mCameraInjectionCallback) return;
5001 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5002 if (res == OK) {
5003 mCameraInjectionCallback = callback;
5004 }
5005}
5006
5007void CameraService::InjectionStatusListener::removeListener() {
5008 Mutex::Autolock lock(mListenerLock);
5009 if (mCameraInjectionCallback == nullptr) {
5010 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5011 return;
5012 }
5013 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5014 mCameraInjectionCallback = nullptr;
5015}
5016
5017void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005018 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005019 if (mCameraInjectionCallback == nullptr) {
5020 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5021 return;
5022 }
Cliff Wud3a05312021-04-26 23:07:31 +08005023
5024 switch (err) {
5025 case -ENODEV:
5026 mCameraInjectionCallback->onInjectionError(
5027 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5028 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005029 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005030 break;
5031 case -EBUSY:
5032 mCameraInjectionCallback->onInjectionError(
5033 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5034 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005035 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005036 break;
5037 case DEAD_OBJECT:
5038 mCameraInjectionCallback->onInjectionError(
5039 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5040 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005041 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005042 break;
5043 case INVALID_OPERATION:
5044 mCameraInjectionCallback->onInjectionError(
5045 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5046 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005047 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005048 break;
5049 case UNKNOWN_TRANSACTION:
5050 mCameraInjectionCallback->onInjectionError(
5051 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5052 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005053 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005054 break;
5055 default:
5056 mCameraInjectionCallback->onInjectionError(
5057 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5058 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005059 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005060 }
Cliff Wud8cae102021-03-11 01:37:42 +08005061}
5062
5063void CameraService::InjectionStatusListener::binderDied(
5064 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005065 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5066 auto parent = mParent.promote();
5067 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005068 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5069 if (clientDescriptor != nullptr) {
5070 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5071 baseClientPtr->stopInjection();
5072 }
Cliff Wu3b268182021-07-06 15:44:43 +08005073 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005074 }
5075}
5076
5077// ----------------------------------------------------------------------------
5078// CameraInjectionSession
5079// ----------------------------------------------------------------------------
5080
5081binder::Status CameraService::CameraInjectionSession::stopInjection() {
5082 Mutex::Autolock lock(mInjectionSessionLock);
5083 auto parent = mParent.promote();
5084 if (parent == nullptr) {
5085 ALOGE("CameraInjectionSession: Parent is gone");
5086 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5087 "Camera service encountered error");
5088 }
Cliff Wud3a05312021-04-26 23:07:31 +08005089
5090 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005091 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5092 if (clientDescriptor != nullptr) {
5093 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5094 res = baseClientPtr->stopInjection();
5095 if (res != OK) {
5096 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5097 " ret != NO_ERROR: %d", res);
5098 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5099 "Camera session encountered error");
5100 }
5101 }
Cliff Wu3b268182021-07-06 15:44:43 +08005102 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005103 return binder::Status::ok();
5104}
5105
5106// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005107
5108static const int kDumpLockRetries = 50;
5109static const int kDumpLockSleep = 60000;
5110
5111static bool tryLock(Mutex& mutex)
5112{
5113 bool locked = false;
5114 for (int i = 0; i < kDumpLockRetries; ++i) {
5115 if (mutex.tryLock() == NO_ERROR) {
5116 locked = true;
5117 break;
5118 }
5119 usleep(kDumpLockSleep);
5120 }
5121 return locked;
5122}
5123
Rucha Katakwardf223072021-06-15 10:21:00 -07005124void CameraService::cacheDump() {
5125 if (mMemFd != -1) {
5126 const Vector<String16> args;
5127 ATRACE_CALL();
5128 // Acquiring service lock here will avoid the deadlock since
5129 // cacheDump will not be called during the second disconnect.
5130 Mutex::Autolock lock(mServiceLock);
5131
5132 Mutex::Autolock l(mCameraStatesLock);
5133 // Start collecting the info for open sessions and store it in temp file.
5134 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005135 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005136 auto clientDescriptor = mActiveClientManager.get(cameraId);
5137 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005138 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005139 // Log the current open session info before device is disconnected.
5140 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5141 }
5142 }
5143 }
5144}
5145
Mathias Agopian65ab4712010-07-14 17:59:35 -07005146status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005147 ATRACE_CALL();
5148
Austin Borgered99f642023-06-01 16:51:35 -07005149 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005150 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Jayant Chowdhary12361932018-08-27 14:46:13 -07005151 CameraThreadState::getCallingPid(),
5152 CameraThreadState::getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005153 return NO_ERROR;
5154 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005155 bool locked = tryLock(mServiceLock);
5156 // failed to lock - CameraService is probably deadlocked
5157 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005158 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005159 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005160
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005161 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005162 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005163
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005164 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005165 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005166
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005167 if (locked) mServiceLock.unlock();
5168 return NO_ERROR;
5169 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005170 dprintf(fd, "\n== Service global info: ==\n\n");
5171 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005172 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005173 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5174 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005175 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5176 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5177 }
Austin Borgered99f642023-06-01 16:51:35 -07005178 std::string activeClientString = mActiveClientManager.toString();
5179 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5180 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005181 if (mStreamUseCaseOverrides.size() > 0) {
5182 dprintf(fd, "Active stream use case overrides:");
5183 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5184 dprintf(fd, " %" PRId64, useCaseOverride);
5185 }
5186 dprintf(fd, "\n");
5187 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005188
5189 dumpEventLog(fd);
5190
5191 bool stateLocked = tryLock(mCameraStatesLock);
5192 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005193 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005194 }
5195
Emilian Peevbd8c5032018-02-14 23:05:40 +00005196 int argSize = args.size();
5197 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005198 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005199 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005200 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005201 }
5202 break;
5203 }
5204 }
5205
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005206 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005207 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005208
Austin Borgered99f642023-06-01 16:51:35 -07005209 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005210
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005211 CameraParameters p = state.second->getShimParams();
5212 if (!p.isEmpty()) {
5213 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5214 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005215 }
5216
5217 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005218 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005219 // log the current open session info
5220 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005221 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005222 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005223 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005224
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005225 }
5226
5227 if (stateLocked) mCameraStatesLock.unlock();
5228
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005229 if (locked) mServiceLock.unlock();
5230
Emilian Peevf53f66e2017-04-11 14:29:43 +01005231 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005232
5233 dprintf(fd, "\n== Vendor tags: ==\n\n");
5234
5235 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5236 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005237 sp<VendorTagDescriptorCache> cache =
5238 VendorTagDescriptorCache::getGlobalVendorTagCache();
5239 if (cache == NULL) {
5240 dprintf(fd, "No vendor tags.\n");
5241 } else {
5242 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5243 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005244 } else {
5245 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5246 }
5247
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005248 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005249 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005250 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005251
5252 // Process dump arguments, if any
5253 int n = args.size();
5254 String16 verboseOption("-v");
5255 String16 unreachableOption("--unreachable");
5256 for (int i = 0; i < n; i++) {
5257 if (args[i] == verboseOption) {
5258 // change logging level
5259 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005260 std::string levelStr = toStdString(args[i+1]);
5261 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005262 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005263 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005264 } else if (args[i] == unreachableOption) {
5265 // Dump memory analysis
5266 // TODO - should limit be an argument parameter?
5267 UnreachableMemoryInfo info;
5268 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5269 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005270 dprintf(fd, "\n== Unable to dump unreachable memory. "
5271 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005272 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005273 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005274 std::string s = info.ToString(/*log_contents*/ true);
5275 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005276 }
5277 }
5278 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005279
5280 bool serviceLocked = tryLock(mServiceLock);
5281
5282 // Dump info from previous open sessions.
5283 // Reposition the offset to beginning of the file before reading
5284
5285 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5286 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5287 ssize_t size_read;
5288 char buf[4096];
5289 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5290 // Read data from file to a small buffer and write it to fd.
5291 write(fd, buf, size_read);
5292 if (size_read == -1) {
5293 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5294 break;
5295 }
5296 }
5297 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5298 } else {
5299 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5300 }
5301
5302 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005303 return NO_ERROR;
5304}
5305
Rucha Katakwardf223072021-06-15 10:21:00 -07005306void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005307 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005308 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005309 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005310 getFormattedCurrentTime().c_str(),
5311 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005312 dprintf(fd, " Client priority score: %d state: %d\n",
5313 clientDescriptor->getPriority().getScore(),
5314 clientDescriptor->getPriority().getState());
5315 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5316
5317 auto client = clientDescriptor->getValue();
5318 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005319 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005320
5321 client->dumpClient(fd, args);
5322}
5323
Austin Borgered99f642023-06-01 16:51:35 -07005324void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005325 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005326 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005327}
5328
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005329void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005330 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005331
5332 Mutex::Autolock l(mLogLock);
5333 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005334 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005335 }
5336
5337 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005338 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005339 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005340 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005341 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005342 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005343}
5344
Austin Borgered99f642023-06-01 16:51:35 -07005345void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005346 Mutex::Autolock lock(mLogLock);
5347 if (!isClientWatchedLocked(client)) { return; }
5348
5349 std::vector<std::string> dumpVector;
5350 client->dumpWatchedEventsToVector(dumpVector);
5351
5352 if (dumpVector.empty()) { return; }
5353
Austin Borgered99f642023-06-01 16:51:35 -07005354 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005355
Austin Borgered99f642023-06-01 16:51:35 -07005356 std::string currentTime = getFormattedCurrentTime();
5357 dumpString << "Cached @ ";
5358 dumpString << currentTime;
5359 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005360
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005361 size_t i = dumpVector.size();
5362
5363 // Store the string in reverse order (latest last)
5364 while (i > 0) {
5365 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005366 dumpString << cameraId;
5367 dumpString << ":";
5368 dumpString << client->getPackageName();
5369 dumpString << " ";
5370 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005371 }
5372
Austin Borgered99f642023-06-01 16:51:35 -07005373 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005374}
5375
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005376void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005377 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005378 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5379 if (mTorchClientMap[i] == who) {
5380 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005381 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005382 status_t res = mFlashlight->setTorchMode(cameraId, false);
5383 if (res) {
5384 ALOGE("%s: torch client died but couldn't turn off torch: "
5385 "%s (%d)", __FUNCTION__, strerror(-res), res);
5386 return;
5387 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005388 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005389 break;
5390 }
5391 }
5392}
5393
Ruben Brunkcc776712015-02-17 20:18:47 -08005394/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005395
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005396 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005397 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5398 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005399 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005400 // PID here is approximate and can be wrong.
Austin Borgered99f642023-06-01 16:51:35 -07005401 logClientDied(CameraThreadState::getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005402
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005403 // check torch client
5404 handleTorchClientBinderDied(who);
5405
5406 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005407 if(!evictClientIdByRemote(who)) {
5408 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005409 return;
5410 }
5411
Ruben Brunkcc776712015-02-17 20:18:47 -08005412 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5413 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005414}
5415
Austin Borgered99f642023-06-01 16:51:35 -07005416void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005417 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005418}
5419
Austin Borgered99f642023-06-01 16:51:35 -07005420void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005421 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005422 // Do not lock mServiceLock here or can get into a deadlock from
5423 // connect() -> disconnect -> updateStatus
5424
5425 auto state = getCameraState(cameraId);
5426
5427 if (state == nullptr) {
5428 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005429 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005430 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005431 }
5432
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005433 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5434 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5435 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005436 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005437 return;
5438 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005439
5440 // Collect the logical cameras without holding mStatusLock in updateStatus
5441 // as that can lead to a deadlock(b/162192331).
5442 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005443 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005444 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005445 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005446 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005447 (const std::string& cameraId, StatusInternal status) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005448
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005449 if (status != StatusInternal::ENUMERATING) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005450 // Update torch status if it has a flash unit.
5451 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005452 TorchModeStatus torchStatus;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005453 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5454 NAME_NOT_FOUND) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005455 TorchModeStatus newTorchStatus =
5456 status == StatusInternal::PRESENT ?
5457 TorchModeStatus::AVAILABLE_OFF :
5458 TorchModeStatus::NOT_AVAILABLE;
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005459 if (torchStatus != newTorchStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07005460 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005461 }
5462 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005463 }
5464
5465 Mutex::Autolock lock(mStatusListenerLock);
Austin Borgered99f642023-06-01 16:51:35 -07005466 notifyPhysicalCameraStatusLocked(mapToInterface(status), cameraId,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005467 logicalCameraIds, deviceKind);
Shuzhen Wang43858162020-01-10 13:42:15 -08005468
Ruben Brunkcc776712015-02-17 20:18:47 -08005469 for (auto& listener : mListenerList) {
Jayant Chowdhary90e63692019-10-25 14:13:01 -07005470 bool isVendorListener = listener->isVendorListener();
5471 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5472 listener->getListenerPid(), listener->getListenerUid()) ||
Shuzhen Wangb8259792021-05-27 09:27:06 -07005473 isVendorListener) {
5474 ALOGV("Skipping discovery callback for system-only camera device %s",
Jayant Chowdhary5216b212019-07-17 09:26:23 -07005475 cameraId.c_str());
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08005476 continue;
5477 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005478 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
Austin Borgered99f642023-06-01 16:51:35 -07005479 cameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005480 listener->handleBinderStatus(ret,
malikakash82ed4352023-07-21 22:44:34 +00005481 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
Austin Borgere8e2c422022-05-12 13:45:24 -07005482 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5483 ret.exceptionCode());
malikakash82ed4352023-07-21 22:44:34 +00005484 // Also trigger the callbacks for cameras that were remapped to the current
5485 // cameraId for the specific package that this listener belongs to.
Austin Borgered99f642023-06-01 16:51:35 -07005486 std::vector<std::string> remappedCameraIds =
malikakash82ed4352023-07-21 22:44:34 +00005487 findOriginalIdsForRemappedCameraId(cameraId, listener->getListenerUid());
5488 for (auto& remappedCameraId : remappedCameraIds) {
5489 ret = listener->getListener()->onStatusChanged(
Austin Borgered99f642023-06-01 16:51:35 -07005490 mapToInterface(status), remappedCameraId);
malikakash82ed4352023-07-21 22:44:34 +00005491 listener->handleBinderStatus(ret,
5492 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5493 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5494 ret.exceptionCode());
5495 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005496 }
5497 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005498}
5499
Austin Borgered99f642023-06-01 16:51:35 -07005500void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5501 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005502 auto state = getCameraState(cameraId);
5503 if (state == nullptr) {
5504 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005505 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005506 return;
5507 }
5508 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005509 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005510 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005511 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005512 }
5513
Shuzhen Wang695044d2020-03-06 09:02:23 -08005514 Mutex::Autolock lock(mStatusListenerLock);
5515
5516 for (const auto& it : mListenerList) {
5517 if (!it->isOpenCloseCallbackAllowed()) {
5518 continue;
5519 }
5520
5521 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005522 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005523 ret = it->getListener()->onCameraOpened(cameraId, clientPackageName);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005524 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005525 ret = it->getListener()->onCameraClosed(cameraId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005526 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005527
5528 it->handleBinderStatus(ret,
5529 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5530 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005531 }
5532}
5533
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005534template<class Func>
5535void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005536 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005537 std::initializer_list<StatusInternal> rejectSourceStates,
5538 Func onStatusUpdatedLocked) {
5539 Mutex::Autolock lock(mStatusLock);
5540 StatusInternal oldStatus = mStatus;
5541 mStatus = status;
5542
5543 if (oldStatus == status) {
5544 return;
5545 }
5546
5547 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005548 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005549
5550 if (oldStatus == StatusInternal::NOT_PRESENT &&
5551 (status != StatusInternal::PRESENT &&
5552 status != StatusInternal::ENUMERATING)) {
5553
5554 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5555 __FUNCTION__);
5556 mStatus = oldStatus;
5557 return;
5558 }
5559
5560 /**
5561 * Sometimes we want to conditionally do a transition.
5562 * For example if a client disconnects, we want to go to PRESENT
5563 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5564 */
5565 for (auto& rejectStatus : rejectSourceStates) {
5566 if (oldStatus == rejectStatus) {
5567 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005568 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005569 mStatus = oldStatus;
5570 return;
5571 }
5572 }
5573
5574 onStatusUpdatedLocked(cameraId, status);
5575}
5576
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005577status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005578 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005579 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005580 if (!status) {
5581 return BAD_VALUE;
5582 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005583 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5584 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005585 // invalid camera ID or the camera doesn't have a flash unit
5586 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005587 }
5588
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005589 *status = mTorchStatusMap.valueAt(index);
5590 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005591}
5592
Austin Borgered99f642023-06-01 16:51:35 -07005593status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005594 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005595 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5596 if (index == NAME_NOT_FOUND) {
5597 return BAD_VALUE;
5598 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005599 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005600
5601 return OK;
5602}
5603
Austin Borgered99f642023-06-01 16:51:35 -07005604std::list<std::string> CameraService::getLogicalCameras(
5605 const std::string& physicalCameraId) {
5606 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005607 Mutex::Autolock lock(mCameraStatesLock);
5608 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005609 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5610 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005611 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005612 }
5613 return retList;
5614}
5615
5616void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005617 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005618 SystemCameraKind deviceKind) {
5619 // mStatusListenerLock is expected to be locked
5620 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005621 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005622 // Note: we check only the deviceKind of the physical camera id
5623 // since, logical camera ids and their physical camera ids are
5624 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005625 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5626 listener->getListenerPid(), listener->getListenerUid())) {
5627 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005628 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005629 continue;
5630 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005631 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005632 logicalCameraId, physicalCameraId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005633 listener->handleBinderStatus(ret,
5634 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5635 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5636 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005637 }
5638 }
5639}
5640
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005641
Svet Ganova453d0d2018-01-11 15:37:58 -08005642void CameraService::blockClientsForUid(uid_t uid) {
5643 const auto clients = mActiveClientManager.getAll();
5644 for (auto& current : clients) {
5645 if (current != nullptr) {
5646 const auto basicClient = current->getValue();
5647 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5648 basicClient->block();
5649 }
5650 }
5651 }
5652}
5653
Michael Grooverd1d435a2018-12-18 17:39:42 -08005654void CameraService::blockAllClients() {
5655 const auto clients = mActiveClientManager.getAll();
5656 for (auto& current : clients) {
5657 if (current != nullptr) {
5658 const auto basicClient = current->getValue();
5659 if (basicClient.get() != nullptr) {
5660 basicClient->block();
5661 }
5662 }
5663 }
5664}
5665
Svet Ganova453d0d2018-01-11 15:37:58 -08005666// NOTE: This is a remote API - make sure all args are validated
5667status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005668 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005669 return PERMISSION_DENIED;
5670 }
5671 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5672 return BAD_VALUE;
5673 }
Austin Borgered99f642023-06-01 16:51:35 -07005674 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005675 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005676 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005677 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005678 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005679 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005680 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005681 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005682 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005683 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005684 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005685 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005686 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005687 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005688 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005689 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005690 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005691 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005692 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005693 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005694 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005695 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005696 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005697 handleClearStreamUseCaseOverrides();
5698 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005699 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005700 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005701 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005702 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005703 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005704 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005705 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00005706 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005707 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005708 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005709 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005710 }
5711 printHelp(err);
5712 return BAD_VALUE;
5713}
5714
malikakash82ed4352023-07-21 22:44:34 +00005715status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
5716 uid_t uid = IPCThreadState::self()->getCallingUid();
5717 if (uid != AID_ROOT) {
5718 dprintf(err, "Must be adb root\n");
5719 return PERMISSION_DENIED;
5720 }
5721 if (args.size() != 4) {
5722 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
5723 return BAD_VALUE;
5724 }
Austin Borgered99f642023-06-01 16:51:35 -07005725 std::string packageName = toStdString(args[1]);
5726 std::string cameraIdToReplace = toStdString(args[2]);
5727 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00005728 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
5729 return OK;
5730}
5731
Svet Ganova453d0d2018-01-11 15:37:58 -08005732status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005733 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005734
Svet Ganova453d0d2018-01-11 15:37:58 -08005735 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005736 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005737 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005738 } else if ((args[2] != toString16("idle"))) {
5739 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005740 return BAD_VALUE;
5741 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005742
5743 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005744 if (args.size() >= 5 && args[3] == toString16("--user")) {
5745 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005746 }
5747
5748 uid_t uid;
5749 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5750 return BAD_VALUE;
5751 }
5752
5753 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005754 return NO_ERROR;
5755}
5756
5757status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005758 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005759
5760 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005761 if (args.size() >= 4 && args[2] == toString16("--user")) {
5762 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005763 }
5764
5765 uid_t uid;
5766 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005767 return BAD_VALUE;
5768 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005769
5770 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005771 return NO_ERROR;
5772}
5773
5774status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005775 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005776
5777 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005778 if (args.size() >= 4 && args[2] == toString16("--user")) {
5779 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005780 }
5781
5782 uid_t uid;
5783 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005784 return BAD_VALUE;
5785 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005786
5787 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005788 return dprintf(out, "active\n");
5789 } else {
5790 return dprintf(out, "idle\n");
5791 }
5792}
5793
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005794status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005795 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005796 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5797 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5798 Mutex::Autolock lock(mServiceLock);
5799
5800 mOverrideRotateAndCropMode = rotateValue;
5801
5802 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5803
5804 const auto clients = mActiveClientManager.getAll();
5805 for (auto& current : clients) {
5806 if (current != nullptr) {
5807 const auto basicClient = current->getValue();
5808 if (basicClient.get() != nullptr) {
5809 basicClient->setRotateAndCropOverride(rotateValue);
5810 }
5811 }
5812 }
5813
5814 return OK;
5815}
5816
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005817status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5818 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005819 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005820 if ((*end != '\0') ||
5821 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5822 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5823 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5824 return BAD_VALUE;
5825 }
5826
5827 Mutex::Autolock lock(mServiceLock);
5828 mOverrideAutoframingMode = autoframingValue;
5829
5830 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5831
5832 const auto clients = mActiveClientManager.getAll();
5833 for (auto& current : clients) {
5834 if (current != nullptr) {
5835 const auto basicClient = current->getValue();
5836 if (basicClient.get() != nullptr) {
5837 basicClient->setAutoframingOverride(autoframingValue);
5838 }
5839 }
5840 }
5841
5842 return OK;
5843}
5844
Ravneetaeb20dc2022-03-30 05:33:03 +00005845status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005846 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00005847
5848 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
5849
5850 Mutex::Autolock lock(mServiceLock);
5851
5852 mCameraServiceWatchdogEnabled = enableWatchdog;
5853
5854 const auto clients = mActiveClientManager.getAll();
5855 for (auto& current : clients) {
5856 if (current != nullptr) {
5857 const auto basicClient = current->getValue();
5858 if (basicClient.get() != nullptr) {
5859 basicClient->setCameraServiceWatchdog(enableWatchdog);
5860 }
5861 }
5862 }
5863
5864 return OK;
5865}
5866
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005867status_t CameraService::handleGetRotateAndCrop(int out) {
5868 Mutex::Autolock lock(mServiceLock);
5869
5870 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
5871}
5872
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005873status_t CameraService::handleGetAutoframing(int out) {
5874 Mutex::Autolock lock(mServiceLock);
5875
5876 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
5877}
5878
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005879status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
5880 char *endPtr;
5881 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005882 std::string maskString = toStdString(args[1]);
5883 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005884
5885 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07005886 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005887 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
5888
5889 Mutex::Autolock lock(mServiceLock);
5890
5891 mImageDumpMask = maskValue;
5892
5893 return OK;
5894}
5895
5896status_t CameraService::handleGetImageDumpMask(int out) {
5897 Mutex::Autolock lock(mServiceLock);
5898
5899 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
5900}
5901
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005902status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005903 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005904 if (errno != 0) return BAD_VALUE;
5905
5906 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
5907 Mutex::Autolock lock(mServiceLock);
5908
5909 mOverrideCameraMuteMode = (muteValue == 1);
5910
5911 const auto clients = mActiveClientManager.getAll();
5912 for (auto& current : clients) {
5913 if (current != nullptr) {
5914 const auto basicClient = current->getValue();
5915 if (basicClient.get() != nullptr) {
5916 if (basicClient->supportsCameraMute()) {
5917 basicClient->setCameraMute(mOverrideCameraMuteMode);
5918 }
5919 }
5920 }
5921 }
5922
5923 return OK;
5924}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005925
Shuzhen Wang16610a62022-12-15 22:38:07 -08005926status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
5927 std::vector<int64_t> useCasesOverride;
5928 for (size_t i = 1; i < args.size(); i++) {
5929 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005930 std::string arg = toStdString(args[i]);
5931 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005932 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07005933 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005934 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07005935 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005936 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07005937 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005938 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07005939 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005940 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07005941 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005942 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07005943 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005944 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
5945 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005946 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005947 return BAD_VALUE;
5948 }
5949 useCasesOverride.push_back(useCase);
5950 }
5951
5952 Mutex::Autolock lock(mServiceLock);
5953 mStreamUseCaseOverrides = std::move(useCasesOverride);
5954
5955 return OK;
5956}
5957
5958void CameraService::handleClearStreamUseCaseOverrides() {
5959 Mutex::Autolock lock(mServiceLock);
5960 mStreamUseCaseOverrides.clear();
5961}
5962
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005963status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
5964 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005965 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005966 if ((*end != '\0') ||
5967 (zoomOverrideValue != -1 &&
5968 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
5969 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
5970 return BAD_VALUE;
5971 }
5972
5973 Mutex::Autolock lock(mServiceLock);
5974 mZoomOverrideValue = zoomOverrideValue;
5975
5976 const auto clients = mActiveClientManager.getAll();
5977 for (auto& current : clients) {
5978 if (current != nullptr) {
5979 const auto basicClient = current->getValue();
5980 if (basicClient.get() != nullptr) {
5981 if (basicClient->supportsZoomOverride()) {
5982 basicClient->setZoomOverride(mZoomOverrideValue);
5983 }
5984 }
5985 }
5986 }
5987
5988 return OK;
5989}
5990
Avichal Rakesh84147132021-11-11 17:47:11 -08005991status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07005992 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005993 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005994 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005995 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005996 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005997 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07005998 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08005999 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006000 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006001 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006002 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006003 dprintf(outFd, "Camera service watch commands:\n"
6004 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6005 " starts watching the provided tags for clients with provided package\n"
6006 " recognizes tag shorthands like '3a'\n"
6007 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006008 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006009 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006010 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006011 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006012 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006013 " clear clears all buffers storing information for watch command");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006014 return BAD_VALUE;
6015}
6016
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006017status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6018 Mutex::Autolock lock(mLogLock);
6019 size_t tagsIdx; // index of '-m'
6020 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006021 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006022 if (tagsIdx < args.size() - 1) {
6023 tags = args[tagsIdx + 1];
6024 } else {
6025 dprintf(outFd, "No tags provided.\n");
6026 return BAD_VALUE;
6027 }
6028
6029 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006030 // watch all clients if no clients are provided
6031 String16 clients = toString16(kWatchAllClientsFlag);
6032 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006033 clientsIdx++);
6034 if (clientsIdx < args.size() - 1) {
6035 clients = args[clientsIdx + 1];
6036 }
Austin Borgered99f642023-06-01 16:51:35 -07006037 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006038
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006039 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006040 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006041
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006042 bool serviceLock = tryLock(mServiceLock);
6043 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006044 auto cameraClients = mActiveClientManager.getAll();
6045 for (const auto &clientDescriptor: cameraClients) {
6046 if (clientDescriptor == nullptr) { continue; }
6047 sp<BasicClient> client = clientDescriptor->getValue();
6048 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006049
6050 if (isClientWatchedLocked(client.get())) {
6051 client->startWatchingTags(mMonitorTags, outFd);
6052 numWatchedClients++;
6053 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006054 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006055 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6056
6057 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006058 return OK;
6059}
6060
6061status_t CameraService::stopWatchingTags(int outFd) {
6062 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006063 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006064 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006065
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006066 mWatchedClientPackages.clear();
6067 mWatchedClientsDumpCache.clear();
6068
6069 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006070 auto cameraClients = mActiveClientManager.getAll();
6071 for (const auto &clientDescriptor : cameraClients) {
6072 if (clientDescriptor == nullptr) { continue; }
6073 sp<BasicClient> client = clientDescriptor->getValue();
6074 if (client.get() == nullptr) { continue; }
6075 client->stopWatchingTags(outFd);
6076 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006077 dprintf(outFd, "Stopped watching all clients.\n");
6078 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006079 return OK;
6080}
6081
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006082status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6083 Mutex::Autolock lock(mLogLock);
6084 size_t clearedSize = mWatchedClientsDumpCache.size();
6085 mWatchedClientsDumpCache.clear();
6086 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6087 return OK;
6088}
6089
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006090status_t CameraService::printWatchedTags(int outFd) {
6091 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006092 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006093
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006094 bool printedSomething = false; // tracks if any monitoring information was printed
6095 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006096
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006097 bool serviceLock = tryLock(mServiceLock);
6098 // get all watched clients that are currently connected
6099 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6100 if (clientDescriptor == nullptr) { continue; }
6101
6102 sp<BasicClient> client = clientDescriptor->getValue();
6103 if (client.get() == nullptr) { continue; }
6104 if (!isClientWatchedLocked(client.get())) { continue; }
6105
6106 std::vector<std::string> dumpVector;
6107 client->dumpWatchedEventsToVector(dumpVector);
6108
6109 size_t printIdx = dumpVector.size();
6110 if (printIdx == 0) {
6111 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006112 }
6113
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006114 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006115 const std::string &cameraId = clientDescriptor->getKey();
6116 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006117 while(printIdx > 0) {
6118 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006119 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006120 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006121 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006122 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006123 printedSomething = true;
6124
6125 connectedMonitoredClients.emplace(client->getPackageName());
6126 }
6127 if (serviceLock) { mServiceLock.unlock(); }
6128
6129 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6130 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006131 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006132 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6133 continue;
6134 }
6135
Austin Borgered99f642023-06-01 16:51:35 -07006136 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006137 dprintf(outFd, "%s\n", kv.second.c_str());
6138 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006139 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006140
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006141 if (!printedSomething) {
6142 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006143 }
6144
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006145 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006146}
6147
Avichal Rakesh84147132021-11-11 17:47:11 -08006148// Print all events in vector `events' that came after lastPrintedEvent
6149void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006150 const std::string &cameraId,
6151 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006152 const std::vector<std::string> &events,
6153 const std::string &lastPrintedEvent) {
6154 if (events.empty()) { return; }
6155
6156 // index of lastPrintedEvent in events.
6157 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6158 size_t lastPrintedIdx;
6159 for (lastPrintedIdx = 0;
6160 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6161 lastPrintedIdx++);
6162
6163 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6164
Avichal Rakesh84147132021-11-11 17:47:11 -08006165 // print events in chronological order (latest event last)
6166 size_t idxToPrint = lastPrintedIdx;
6167 do {
6168 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006169 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6170 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006171 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006172}
6173
6174// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6175// command should be interrupted if the user presses the return key, or if user loses any way to
6176// signal interrupt.
6177// If timeoutMs == 0, this function will always return false
6178bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6179 struct timeval startTime;
6180 int startTimeError = gettimeofday(&startTime, nullptr);
6181 if (startTimeError) {
6182 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6183 return true;
6184 }
6185
6186 const nfds_t numFds = 1;
6187 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6188
6189 struct timeval currTime;
6190 char buffer[2];
6191 while(true) {
6192 int currTimeError = gettimeofday(&currTime, nullptr);
6193 if (currTimeError) {
6194 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6195 return true;
6196 }
6197
6198 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6199 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6200 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6201
6202 if (remainingTimeMs <= 0) {
6203 // No user interrupt within timeoutMs, don't interrupt watch command
6204 return false;
6205 }
6206
6207 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6208 if (numFdsUpdated < 0) {
6209 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6210 return true;
6211 }
6212
6213 if (numFdsUpdated == 0) {
6214 // No user input within timeoutMs, don't interrupt watch command
6215 return false;
6216 }
6217
6218 if (!(pollFd.revents & POLLIN)) {
6219 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6220 return true;
6221 }
6222
6223 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6224 if (sizeRead < 0) {
6225 dprintf(outFd, "Error reading user input. Exiting.\n");
6226 return true;
6227 }
6228
6229 if (sizeRead == 0) {
6230 // Reached end of input fd (can happen if input is piped)
6231 // User has no way to signal an interrupt, so interrupt here
6232 return true;
6233 }
6234
6235 if (buffer[0] == '\n') {
6236 // User pressed return, interrupt watch command.
6237 return true;
6238 }
6239 }
6240}
6241
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006242status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6243 int inFd, int outFd) {
6244 // Figure out refresh interval, if present in args
6245 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006246 if (args.size() > 2) {
6247 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006248 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006249 intervalIdx++);
6250
6251 size_t intervalValIdx = intervalIdx + 1;
6252 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006253 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006254 if (errno) { return BAD_VALUE; }
6255 }
6256 }
6257
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006258 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6259 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006260
Avichal Rakesh84147132021-11-11 17:47:11 -08006261 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006262 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006263
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006264 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006265 bool serviceLock = tryLock(mServiceLock);
6266 auto cameraClients = mActiveClientManager.getAll();
6267 if (serviceLock) { mServiceLock.unlock(); }
6268
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006269 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006270 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006271 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006272
6273 sp<BasicClient> client = clientDescriptor->getValue();
6274 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006275 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006276
Austin Borgered99f642023-06-01 16:51:35 -07006277 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006278 // This also initializes the map entries with an empty string
6279 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6280
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006281 std::vector<std::string> latestEvents;
6282 client->dumpWatchedEventsToVector(latestEvents);
6283
6284 if (!latestEvents.empty()) {
6285 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006286 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006287 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006288 latestEvents,
6289 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006290 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006291 }
6292 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006293 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006294 break;
6295 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006296 }
6297 return OK;
6298}
6299
Austin Borgered99f642023-06-01 16:51:35 -07006300void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006301 mWatchedClientPackages.clear();
6302
Austin Borgered99f642023-06-01 16:51:35 -07006303 std::istringstream iss(clients);
6304 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006305
Austin Borgered99f642023-06-01 16:51:35 -07006306 while (std::getline(iss, nextClient, ',')) {
6307 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006308 // Don't need to track any other package if 'all' is present
6309 mWatchedClientPackages.clear();
6310 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6311 break;
6312 }
6313
6314 // track package names
6315 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006316 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006317}
6318
Svet Ganova453d0d2018-01-11 15:37:58 -08006319status_t CameraService::printHelp(int out) {
6320 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006321 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6322 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6323 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006324 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6325 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6326 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006327 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6328 " Valid values 0=false, 1=true, 2=auto\n"
6329 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006330 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6331 " Valid values 0=OFF, 1=ON for JPEG\n"
6332 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006333 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006334 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6335 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6336 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6337 " on. In case the number of usecases is smaller than the number of streams, the\n"
6338 " last use case is assigned to all the remaining streams. In case of multiple\n"
6339 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6340 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6341 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6342 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006343 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6344 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006345 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6346 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006347 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006348 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006349 " help print this message\n");
6350}
6351
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006352bool CameraService::isClientWatched(const BasicClient *client) {
6353 Mutex::Autolock lock(mLogLock);
6354 return isClientWatchedLocked(client);
6355}
6356
6357bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6358 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6359 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6360}
6361
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006362int32_t CameraService::updateAudioRestriction() {
6363 Mutex::Autolock lock(mServiceLock);
6364 return updateAudioRestrictionLocked();
6365}
6366
6367int32_t CameraService::updateAudioRestrictionLocked() {
6368 int32_t mode = 0;
6369 // iterate through all active client
6370 for (const auto& i : mActiveClientManager.getAll()) {
6371 const auto clientSp = i->getValue();
6372 mode |= clientSp->getAudioRestriction();
6373 }
6374
6375 bool modeChanged = (mAudioRestriction != mode);
6376 mAudioRestriction = mode;
6377 if (modeChanged) {
6378 mAppOps.setCameraAudioRestriction(mode);
6379 }
6380 return mode;
6381}
6382
Austin Borgered99f642023-06-01 16:51:35 -07006383status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006384 sp<BasicClient> clientSp) {
6385 std::unique_ptr<AutoConditionLock> lock =
6386 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6387 status_t res = NO_ERROR;
6388 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006389 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006390 mInjectionStatusListener->notifyInjectionError(
6391 externalCamId, UNKNOWN_TRANSACTION);
6392 clientSp->notifyError(
6393 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6394 CaptureResultExtras());
6395
6396 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6397 // other clients from connecting in mServiceLockWrapper if held
6398 mServiceLock.unlock();
6399
6400 // Clear caller identity temporarily so client disconnect PID checks work correctly
6401 int64_t token = CameraThreadState::clearCallingIdentity();
6402 clientSp->disconnect();
6403 CameraThreadState::restoreCallingIdentity(token);
6404
6405 // Reacquire mServiceLock
6406 mServiceLock.lock();
6407 }
6408
6409 return res;
6410}
6411
Cliff Wud3a05312021-04-26 23:07:31 +08006412void CameraService::clearInjectionParameters() {
6413 {
6414 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006415 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006416 mInjectionInternalCamId = "";
6417 }
6418 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006419 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006420}
6421
Mathias Agopian65ab4712010-07-14 17:59:35 -07006422}; // namespace android