blob: fdb5b7d11ccda5e9662ea136a93f68159c7b76f1 [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>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000086#include "utils/CameraTraces.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000088#include "utils/TagMonitor.h"
89#include "utils/Utils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080091namespace {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080092 const char* kActivityServiceName = "activity";
93 const char* kSensorPrivacyServiceName = "sensor_privacy";
94 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070095 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000096 const char* kVirtualDeviceBackCameraId = "0";
97 const char* kVirtualDeviceFrontCameraId = "1";
Austin Borger23694432024-10-07 19:28:01 -070098 const char* kUnknownPackageName = "<unknown>";
Biswarup Pal37a75182024-01-16 15:53:35 +000099
100 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
101 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
102 return android::kDefaultDeviceId;
103 }
104
105 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
106 return deviceIdEntry.data.i32[0];
107 }
Austin Borgera0c61f12024-10-11 13:38:35 -0700108
109 static android::PermissionChecker::PermissionResult appOpModeToPermissionResult(int32_t res) {
110 switch (res) {
111 case android::AppOpsManager::MODE_ERRORED:
112 return android::PermissionChecker::PERMISSION_HARD_DENIED;
113 case android::AppOpsManager::MODE_IGNORED:
114 return android::PermissionChecker::PERMISSION_SOFT_DENIED;
115 case android::AppOpsManager::MODE_ALLOWED:
116 return android::PermissionChecker::PERMISSION_GRANTED;
117 }
118
119 ALOGE("%s: Unexpected appOpMode %d", __FUNCTION__, res);
120 return android::PermissionChecker::PERMISSION_HARD_DENIED;
121 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000122} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800123
Mathias Agopian65ab4712010-07-14 17:59:35 -0700124namespace android {
125
Austin Borgerea931242021-12-13 23:10:41 +0000126using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700127using namespace camera3::SessionConfigurationUtils;
128
129using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000130using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700131using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700132using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800133using hardware::ICamera;
134using hardware::ICameraClient;
135using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800136using hardware::camera2::ICameraInjectionCallback;
137using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800138using hardware::camera2::utils::CameraIdAndSessionConfiguration;
139using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000140
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700141namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000142namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800143
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144// ----------------------------------------------------------------------------
145// Logging support -- this is for debugging only
146// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700147volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700148
Steve Blockb8a80522011-12-20 16:23:08 +0000149#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
150#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700151
152static void setLogLevel(int level) {
153 android_atomic_write(level, &gLogLevel);
154}
155
Henri Chataingbcb99452023-11-01 17:40:30 +0000156int32_t format_as(CameraService::StatusInternal s) {
157 return fmt::underlying(s);
158}
159
Mathias Agopian65ab4712010-07-14 17:59:35 -0700160// ----------------------------------------------------------------------------
161
Austin Borger249e6592024-03-10 22:28:11 -0700162// Permission strings (references to AttributionAndPermissionUtils for brevity)
163static const std::string &sDumpPermission =
164 AttributionAndPermissionUtils::sDumpPermission;
165static const std::string &sManageCameraPermission =
166 AttributionAndPermissionUtils::sManageCameraPermission;
167static const std::string &sCameraSendSystemEventsPermission =
168 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
169static const std::string &sCameraInjectExternalCameraPermission =
170 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
171
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000172// Constant integer for FGS Logging, used to denote the API type for logger
173static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700174const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800175static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
176static constexpr int32_t kSystemNativeClientState =
177 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700178static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700179
Austin Borgered99f642023-06-01 16:51:35 -0700180const std::string CameraService::kOfflineDevice("offline-");
181const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700182
Biswarup Pal7d072862024-04-17 15:24:47 +0000183constexpr int32_t kInvalidDeviceId = -1;
184
Rucha Katakward9ea6452021-05-06 11:57:16 -0700185// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700186static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700187
Austin Borger74fca042022-05-23 12:41:21 -0700188CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700189 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
190 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
191 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
192 std::make_shared<AttributionAndPermissionUtils>()\
193 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700194 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
195 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800196 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800197 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700198 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700199 mSoundRef(0), mInitialized(false),
200 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000201 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700202 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800203 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700204 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
205 if (mMemFd == -1) {
206 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
207 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700208}
209
Charles Chena7b613c2023-01-24 21:57:33 +0000210// Enable processes with isolated AID to request the binder
211void CameraService::instantiate() {
212 CameraService::publish(true);
213}
214
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800215void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700216 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800217 return;
218 }
219
220 ALOGV("appops service registered. setting camera audio restriction");
221 mAppOps.setCameraAudioRestriction(mAudioRestriction);
222}
223
Iliyan Malchev8951a972011-04-14 16:55:59 -0700224void CameraService::onFirstRef()
225{
Ruben Brunkcc776712015-02-17 20:18:47 -0800226 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800227
Iliyan Malchev8951a972011-04-14 16:55:59 -0700228 BnCameraService::onFirstRef();
229
Ruben Brunk99e69712015-05-26 17:25:07 -0700230 // Update battery life tracking if service is restarting
231 BatteryNotifier& notifier(BatteryNotifier::getInstance());
232 notifier.noteResetCamera();
233 notifier.noteResetFlashlight();
234
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800235 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800236
Emilian Peevf53f66e2017-04-11 14:29:43 +0100237 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800238 if (res == OK) {
239 mInitialized = true;
240 }
241
Svet Ganova453d0d2018-01-11 15:37:58 -0800242 mUidPolicy = new UidPolicy(this);
243 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700244 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800245 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800246 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800247
248 // appops function setCamerAudioRestriction uses getService which
249 // is blocking till the appops service is ready. To enable early
250 // boot availability for cameraservice, use checkService which is
251 // non blocking and register for notifications
252 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700253 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800254 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700255 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800256 } else {
257 mAppOps.setCameraAudioRestriction(mAudioRestriction);
258 }
259
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700260 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
261 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000262 // Deprecated, so it will fail to register on newer devices
263 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700264 __FUNCTION__);
265 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700266
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700267 if (!AidlCameraService::registerService(this)) {
268 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
269 }
270
Shuzhen Wang24b44152019-09-20 10:38:11 -0700271 // This needs to be last call in this function, so that it's as close to
272 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700273 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700274 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800275}
276
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800277status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800278 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100279
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800280 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000281 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 {
283 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800284
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800285 if (nullptr == mCameraProviderManager.get()) {
286 mCameraProviderManager = new CameraProviderManager();
287 res = mCameraProviderManager->initialize(this);
288 if (res != OK) {
289 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
290 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700291 logServiceError("Unable to initialize camera provider manager",
292 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800293 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100294 }
295 }
296
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 // Setup vendor tags before we call get_camera_info the first time
298 // because HAL might need to setup static vendor keys in get_camera_info
299 // TODO: maybe put this into CameraProviderManager::initialize()?
300 mCameraProviderManager->setUpVendorTags();
301
302 if (nullptr == mFlashlight.get()) {
303 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700304 }
305
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800306 res = mFlashlight->findFlashUnits();
307 if (res != OK) {
308 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
309 }
310
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000311 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800312 }
313
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800314 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700315 if (getCameraState(cameraId) == nullptr) {
316 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800317 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000318 if (unavailPhysicalIds.count(cameraId) > 0) {
319 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700320 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000321 }
322 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800323 }
324
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700325 // Derive primary rear/front cameras, and filter their charactierstics.
326 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700327 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700328 // Assume internal cameras are advertised from the same
329 // provider. If multiple providers are registered at different time,
330 // and each provider contains multiple internal color cameras, the current
331 // logic may filter the characteristics of more than one front/rear color
332 // cameras.
333 Mutex::Autolock l(mServiceLock);
334 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700335 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700336
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800337 return OK;
338}
339
Austin Borgered99f642023-06-01 16:51:35 -0700340void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700341 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000342 // Get the device id and app-visible camera id for the given HAL-visible camera id.
343 auto [deviceId, mappedCameraId] =
344 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
345
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800346 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800347 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700348 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
349 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000350 ALOGV("%s: Skipping torch callback for system-only camera device %s",
351 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700352 continue;
353 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000354
Austin Borgere8e2c422022-05-12 13:45:24 -0700355 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000356 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700357 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
358 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800359 }
360}
361
Mathias Agopian65ab4712010-07-14 17:59:35 -0700362CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800363 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800364 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800365 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800366 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700367}
368
Emilian Peevaee727d2017-05-04 16:35:48 +0100369void CameraService::onNewProviderRegistered() {
370 enumerateProviders();
371}
372
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700373void CameraService::filterAPI1SystemCameraLocked(
374 const std::vector<std::string> &normalDeviceIds) {
375 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000376 for (auto &cameraId : normalDeviceIds) {
377 if (vd_flags::camera_device_awareness()) {
378 CameraMetadata cameraInfo;
379 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000380 cameraId, false, &cameraInfo,
381 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000382 int32_t deviceId = kDefaultDeviceId;
383 if (res != OK) {
384 ALOGW("%s: Not able to get camera characteristics for camera id %s",
385 __FUNCTION__, cameraId.c_str());
386 } else {
387 deviceId = getDeviceId(cameraInfo);
388 }
389 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
390 // system cameras, so skip for non-default device id's.
391 if (deviceId != kDefaultDeviceId) {
392 continue;
393 }
394 }
395
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700396 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000397 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
398 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700399 continue;
400 }
401 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700402 // All system camera ids will necessarily come after public camera
403 // device ids as per the HAL interface contract.
404 break;
405 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000406 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700407 }
408 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
409 mNormalDeviceIdsWithoutSystemCamera.size());
410}
411
Austin Borgered99f642023-06-01 16:51:35 -0700412status_t CameraService::getSystemCameraKind(const std::string& cameraId,
413 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700414 auto state = getCameraState(cameraId);
415 if (state != nullptr) {
416 *kind = state->getSystemCameraKind();
417 return OK;
418 }
419 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700420 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700421}
422
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800423void CameraService::updateCameraNumAndIds() {
424 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700425 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
426 // Excludes hidden secure cameras
427 mNumberOfCameras =
428 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
429 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800430 mNormalDeviceIds =
431 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700432 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800433}
434
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700435void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700436 // To claim to be S Performance primary cameras, the cameras must be
437 // backward compatible. So performance class primary camera Ids must be API1
438 // compatible.
439 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
440 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
441 int facing = -1;
442 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800443 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000444 getDeviceVersion(cameraId,
445 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
446 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447 if (facing == -1) {
448 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
449 return;
450 }
451
452 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
453 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700454 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
455 if (res == OK) {
456 mPerfClassPrimaryCameraIds.insert(cameraId);
457 } else {
458 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
459 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
460 break;
461 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700462
463 if (facing == hardware::CAMERA_FACING_BACK) {
464 firstRearCameraSeen = true;
465 }
466 if (facing == hardware::CAMERA_FACING_FRONT) {
467 firstFrontCameraSeen = true;
468 }
469 }
470
471 if (firstRearCameraSeen && firstFrontCameraSeen) {
472 break;
473 }
474 }
475}
476
Austin Borgered99f642023-06-01 16:51:35 -0700477void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700478 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
480 if (res != OK) {
481 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
482 return;
483 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000484 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700485 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
486 if (res != OK) {
487 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
488 return;
489 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000490 std::vector<std::string> physicalCameraIds;
491 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700492 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700494 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100495 }
496
497 {
498 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700499 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000500 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100501 }
502
Austin Borgered99f642023-06-01 16:51:35 -0700503 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100504 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700505 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800506
Austin Borgered99f642023-06-01 16:51:35 -0700507 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100508 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800509
510 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700511 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100512}
513
Austin Borgered99f642023-06-01 16:51:35 -0700514void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800515 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700516 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100517 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700518 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100519 }
520
521 {
522 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700523 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100524 }
525}
526
Austin Borgered99f642023-06-01 16:51:35 -0700527void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800528 CameraDeviceStatus newHalStatus) {
529 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700530 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700531
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800532 StatusInternal newStatus = mapToInternal(newHalStatus);
533
Austin Borgered99f642023-06-01 16:51:35 -0700534 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800535
536 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700537 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100538 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700539 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100540
541 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700542 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100543
Austin Borgered99f642023-06-01 16:51:35 -0700544 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700545 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700546 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700547 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700548 return;
549 }
550
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800551 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700554 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
555 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700556 return;
557 }
558
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800559 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000560 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
561 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800562 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
563 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700564 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000565 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800566
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700567 std::vector<sp<BasicClient>> clientsToDisconnectOnline, clientsToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700568 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800569 // Don't do this in updateStatus to avoid deadlock over mServiceLock
570 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700571
Ruben Brunkcc776712015-02-17 20:18:47 -0800572 // Remove cached shim parameters
573 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700574
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800575 // Remove online as well as offline client from the list of active clients,
576 // if they are present
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700577 clientsToDisconnectOnline = removeClientsLocked(cameraId);
578 clientsToDisconnectOffline = removeClientsLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700579 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800580
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700581 disconnectClients(cameraId, clientsToDisconnectOnline);
582 disconnectClients(kOfflineDevice + cameraId, clientsToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700583
Austin Borgered99f642023-06-01 16:51:35 -0700584 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800585 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800586 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000587 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
588 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700589 }
Austin Borgered99f642023-06-01 16:51:35 -0700590 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700591 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800592}
Igor Murashkincba2c162013-03-20 15:56:31 -0700593
Austin Borgered99f642023-06-01 16:51:35 -0700594void CameraService::onDeviceStatusChanged(const std::string& id,
595 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800596 CameraDeviceStatus newHalStatus) {
597 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700598 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800599
600 StatusInternal newStatus = mapToInternal(newHalStatus);
601
602 std::shared_ptr<CameraState> state = getCameraState(id);
603
604 if (state == nullptr) {
605 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700606 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800607 return;
608 }
609
610 StatusInternal logicalCameraStatus = state->getStatus();
611 if (logicalCameraStatus != StatusInternal::PRESENT &&
612 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
613 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700614 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800615 return;
616 }
617
618 bool updated = false;
619 if (newStatus == StatusInternal::PRESENT) {
620 updated = state->removeUnavailablePhysicalId(physicalId);
621 } else {
622 updated = state->addUnavailablePhysicalId(physicalId);
623 }
624
625 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700626 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800627 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000628 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800629 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000630 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800631 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700632 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
633 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
634 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700635 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700636 return;
637 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800638 Mutex::Autolock lock(mStatusListenerLock);
639 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700640 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
641 listener->getListenerPid(), listener->getListenerUid())) {
642 ALOGV("Skipping discovery callback for system-only camera device %s",
643 id.c_str());
644 continue;
645 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700646 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000647 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700648 listener->handleBinderStatus(ret,
649 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
650 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
651 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800652 }
653 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700654}
655
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -0700656void CameraService::disconnectClients(const std::string& id,
657 std::vector<sp<BasicClient>> clientsToDisconnect) {
658 for (auto& client : clientsToDisconnect) {
659 disconnectClient(id, client);
660 }
661}
662
Austin Borgered99f642023-06-01 16:51:35 -0700663void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800664 if (clientToDisconnect.get() != nullptr) {
665 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700666 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800667 // Notify the client of disconnection
668 clientToDisconnect->notifyError(
669 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
670 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800671 clientToDisconnect->disconnect();
672 }
673}
674
Austin Borgered99f642023-06-01 16:51:35 -0700675void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800676 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700677 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
678 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
679 if (res != OK) {
680 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700681 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700682 return;
683 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800684 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700685 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800686}
687
Austin Borgered99f642023-06-01 16:51:35 -0700688void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700689 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
690 Mutex::Autolock al(mTorchStatusMutex);
691 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
692}
693
Austin Borgered99f642023-06-01 16:51:35 -0700694void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800695 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000696 // Get the device id and app-visible camera id for the given HAL-visible camera id.
697 auto [deviceId, mappedCameraId] =
698 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
699
Rucha Katakwar38284522021-11-10 11:25:21 -0800700 Mutex::Autolock lock(mStatusListenerLock);
701 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000702 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
703 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700704 i->handleBinderStatus(ret,
705 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
706 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800707 }
708}
709
Austin Borgered99f642023-06-01 16:51:35 -0700710void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700711 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800712 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700713 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800714
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800715 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800716 status_t res = getTorchStatusLocked(cameraId, &status);
717 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700718 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700719 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800720 return;
721 }
722 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800723 return;
724 }
725
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800726 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800727 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800728 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
729 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800730 return;
731 }
732
Ruben Brunkcc776712015-02-17 20:18:47 -0800733 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700734 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700735 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700736 auto iter = mTorchUidMap.find(cameraId);
737 if (iter != mTorchUidMap.end()) {
738 int oldUid = iter->second.second;
739 int newUid = iter->second.first;
740 BatteryNotifier& notifier(BatteryNotifier::getInstance());
741 if (oldUid != newUid) {
742 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800743 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700744 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700745 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800746 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700747 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700748 }
749 iter->second.second = newUid;
750 } else {
751 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800752 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700753 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700754 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700755 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700756 }
757 }
758 }
759 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700760 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800761}
762
Austin Borger249e6592024-03-10 22:28:11 -0700763bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700764 // Returns false if this is not an automotive device type.
765 if (!isAutomotiveDevice())
766 return false;
767
768 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700769 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700770 return false;
771
772 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
773 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
774 // This isn't a known camera ID, so it's not a system camera.
775 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
776 return false;
777 }
778
779 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
780 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
781 return false;
782 }
783
784 CameraMetadata cameraInfo;
785 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000786 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700787 if (res != OK){
788 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
789 cam_id.c_str());
790 return false;
791 }
792
793 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
794 if (auto_location.count != 1)
795 return false;
796
797 uint8_t location = auto_location.data.u8[0];
798 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
799 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
800 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
801 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
802 return false;
803 }
804
805 return true;
806}
807
Austin Borger65e64642024-06-11 15:58:23 -0700808Status CameraService::getNumberOfCameras(int32_t type,
809 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000810 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700811 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700812 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000813 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700814 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000815 return Status::ok();
816 }
817
Emilian Peevaee727d2017-05-04 16:35:48 +0100818 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700819 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800820 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
821 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700822 switch (type) {
823 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700824 if (hasSystemCameraPermissions) {
825 *numCameras = static_cast<int>(mNormalDeviceIds.size());
826 } else {
827 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
828 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700830 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700831 if (hasSystemCameraPermissions) {
832 *numCameras = mNumberOfCameras;
833 } else {
834 *numCameras = mNumberOfCamerasWithoutSystemCamera;
835 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700837 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800838 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700839 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800840 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
841 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700842 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800843 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700844}
845
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700846Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700847 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700848 /* out */
849 hardware::camera2::impl::CameraMetadataNative* request) {
850 ATRACE_CALL();
851
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700852 if (!mInitialized) {
853 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
854 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
855 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
856 }
857
Austin Borger65e64642024-06-11 15:58:23 -0700858 std::optional<std::string> cameraIdOptional =
859 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000860 if (!cameraIdOptional.has_value()) {
861 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700862 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000863 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
864 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
865 }
866 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700867
868 binder::Status res;
869 if (request == nullptr) {
870 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
871 "Camera %s: Error creating default request", cameraId.c_str());
872 return res;
873 }
874 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
875 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
876 cameraId, templateId, &tempId);
877 if (!res.isOk()) {
878 ALOGE("%s: Camera %s: failed to map request Template %d",
879 __FUNCTION__, cameraId.c_str(), templateId);
880 return res;
881 }
882
883 if (shouldRejectSystemCameraConnection(cameraId)) {
884 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
885 "request for system only device %s: ", cameraId.c_str());
886 }
887
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700888 CameraMetadata metadata;
889 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
890 if (err == OK) {
891 request->swap(metadata);
892 } else if (err == BAD_VALUE) {
893 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
894 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
895 cameraId.c_str(), templateId, strerror(-err), err);
896 } else {
897 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
898 "Camera %s: Error creating default request for template %d: %s (%d)",
899 cameraId.c_str(), templateId, strerror(-err), err);
900 }
901 return res;
902}
903
904Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700905 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700906 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700907 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700908 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700909 ATRACE_CALL();
910
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700911 if (!mInitialized) {
912 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
913 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
914 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
915 }
916
Austin Borger65e64642024-06-11 15:58:23 -0700917 std::optional<std::string> cameraIdOptional =
918 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000919 if (!cameraIdOptional.has_value()) {
920 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700921 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000922 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
923 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
924 }
925 std::string cameraId = cameraIdOptional.value();
926
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700927 if (supported == nullptr) {
928 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
929 unresolvedCameraId.c_str());
930 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
931 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
932 }
933
934 if (shouldRejectSystemCameraConnection(cameraId)) {
935 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
936 "session configuration with parameters support for system only device %s: ",
937 cameraId.c_str());
938 }
939
Avichal Rakeshe005df52024-09-25 17:13:27 -0700940 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700941 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
942
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700943 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
944 sessionConfiguration, overrideForPerfClass, supported);
945 if (flags::analytics_24q3()) {
946 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
947 getCallingUid(), sessionConfiguration, ret);
948 }
949 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700950}
951
952Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
953 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
954 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700955 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700956 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
957 cameraId, sessionConfiguration, overrideForPerfClass,
958 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700959 binder::Status res;
960 switch (ret) {
961 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700962 // Expected. Do Nothing.
963 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700964 case INVALID_OPERATION: {
965 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700966 "Camera %s: Session configuration with parameters supported query not "
967 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700968 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700969 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
970 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
971 *supported = false;
972 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700974 break;
975 case NAME_NOT_FOUND: {
976 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
977 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
978 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
979 *supported = false;
980 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
981 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700982 break;
983 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700984 std::string msg = fmt::sprintf(
985 "Unable to retrieve session configuration support for camera "
986 "device %s: Error: %s (%d)",
987 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700988 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700989 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
990 *supported = false;
991 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700992 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700993 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700994 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700995}
996
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800997Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000998 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700999 const SessionConfiguration& sessionConfiguration,
1000 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +00001001 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001002 ATRACE_CALL();
1003
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001004 if (outMetadata == nullptr) {
1005 std::string msg =
1006 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1007 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1008 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1009 }
1010
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001011 if (!mInitialized) {
1012 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1013 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1014 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1015 }
1016
Austin Borger65e64642024-06-11 15:58:23 -07001017 std::optional<std::string> cameraIdOptional =
1018 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001019 if (!cameraIdOptional.has_value()) {
1020 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001021 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001022 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1023 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1024 }
1025 std::string cameraId = cameraIdOptional.value();
1026
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001027 if (shouldRejectSystemCameraConnection(cameraId)) {
1028 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1029 "Unable to retrieve camera"
1030 "characteristics for system only device %s: ",
1031 cameraId.c_str());
1032 }
1033
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001034 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1035 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesheb961c72024-09-25 17:26:26 -07001036
1037 bool sessionConfigSupported;
1038 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1039 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1040 if (!res.isOk()) {
1041 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1042 // report the correct Status to send to the client. Simply forward the error to
1043 // the client.
1044 outMetadata->clear();
1045 return res;
1046 }
1047
1048 if (!sessionConfigSupported) {
1049 std::string msg = fmt::sprintf("Session configuration not supported for camera device %s.",
1050 cameraId.c_str());
1051 outMetadata->clear();
1052 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001053 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001054
1055 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001056 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001057
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001058 switch (ret) {
1059 case OK:
1060 // Expected, no handling needed.
1061 break;
1062 case INVALID_OPERATION: {
1063 std::string msg = fmt::sprintf(
1064 "Camera %s: Session characteristics query not supported!",
1065 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001066 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001067 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1068 outMetadata->clear();
1069 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1070 }
1071 break;
1072 case NAME_NOT_FOUND: {
1073 std::string msg = fmt::sprintf(
1074 "Camera %s: Unknown camera ID.",
1075 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001076 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001077 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1078 outMetadata->clear();
1079 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001080 }
1081 break;
1082 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001083 std::string msg = fmt::sprintf(
1084 "Unable to retrieve session characteristics for camera device %s: "
1085 "Error: %s (%d)",
1086 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001087 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001088 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1089 outMetadata->clear();
1090 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001091 }
1092 }
1093
Avichal Rakesheb961c72024-09-25 17:26:26 -07001094 res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001095 if (flags::analytics_24q3()) {
1096 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1097 getCallingUid(), sessionConfiguration, res);
1098 }
1099 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001100}
1101
1102Status CameraService::filterSensitiveMetadataIfNeeded(
1103 const std::string& cameraId, CameraMetadata* metadata) {
1104 int callingPid = getCallingPid();
1105 int callingUid = getCallingUid();
1106
1107 if (callingPid == getpid()) {
1108 // Caller is cameraserver; no need to remove keys
1109 return Status::ok();
1110 }
1111
1112 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1113 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1114 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1115 metadata->clear();
1116 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1117 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1118 }
1119 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1120 // Attempting to query system only camera without system camera permission would have
1121 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1122 // for a system only camera, then the caller has the required permission.
1123 // No need to remove keys
1124 return Status::ok();
1125 }
1126
1127 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001128 // Get the device id that owns this camera.
1129 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1130 cameraId);
1131 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1132 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001133 if (hasCameraPermission) {
1134 // Caller has camera permission; no need to remove keys
1135 return Status::ok();
1136 }
1137
1138 status_t ret = metadata->removePermissionEntries(
1139 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1140 if (ret != OK) {
1141 metadata->clear();
1142 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1143 "Failed to remove camera characteristics needing camera permission "
1144 "for device %s:%s (%d)",
1145 cameraId.c_str(), strerror(-ret), ret);
1146 }
1147
1148 if (!tagsRemoved.empty()) {
1149 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1150 tagsRemoved.data(), tagsRemoved.size());
1151 if (ret != OK) {
1152 metadata->clear();
1153 return STATUS_ERROR_FMT(
1154 ERROR_INVALID_OPERATION,
1155 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1156 cameraId.c_str(), strerror(-ret), ret);
1157 }
1158 }
1159 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001160}
1161
malikakash22af94c2023-12-04 18:13:14 +00001162Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001163 const std::string& cameraId,
1164 const CameraMetadata& sessionParams) {
1165 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001166 const int pid = getCallingPid();
1167 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001168 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1169 __FUNCTION__, pid, uid);
1170 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1171 "Permission Denial: no permission to inject session params");
1172 }
1173
Biswarup Pal37a75182024-01-16 15:53:35 +00001174 // Do not allow session params injection for a virtual camera.
1175 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1176 if (deviceId != kDefaultDeviceId) {
1177 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1178 "Cannot inject session params for a virtual camera");
1179 }
1180
malikakash22af94c2023-12-04 18:13:14 +00001181 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1182 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1183
1184 auto clientDescriptor = mActiveClientManager.get(cameraId);
1185 if (clientDescriptor == nullptr) {
1186 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1187 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1188 "No active client for camera id %s", cameraId.c_str());
1189 }
1190
1191 sp<BasicClient> clientSp = clientDescriptor->getValue();
1192 status_t res = clientSp->injectSessionParams(sessionParams);
1193
1194 if (res != OK) {
1195 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1196 "Error injecting session params into camera \"%s\": %s (%d)",
1197 cameraId.c_str(), strerror(-res), res);
1198 }
1199 return Status::ok();
1200}
1201
Biswarup Pal37a75182024-01-16 15:53:35 +00001202std::optional<std::string> CameraService::resolveCameraId(
1203 const std::string& inputCameraId,
1204 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001205 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001206 if ((deviceId == kDefaultDeviceId)
1207 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1208 auto [storedDeviceId, _] =
1209 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1210 if (storedDeviceId != kDefaultDeviceId) {
1211 // Trying to access a virtual camera from default-policy device context, we should fail.
1212 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1213 inputCameraId.c_str(), deviceId);
1214 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1215 return std::nullopt;
1216 }
malikakash98260df2024-05-10 23:33:57 +00001217 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001218 }
1219
1220 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1221}
1222
Austin Borger65e64642024-06-11 15:58:23 -07001223Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1224 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1225 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001226 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001227 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001228 std::string cameraIdStr =
1229 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001230 if (cameraIdStr.empty()) {
1231 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001232 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001233 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1234 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1235 }
malikakashedb38962023-09-06 00:03:35 +00001236
Austin Borgered99f642023-06-01 16:51:35 -07001237 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001238 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1239 "characteristics for system only device %s: ", cameraIdStr.c_str());
1240 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001241
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001242 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001243 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001244 return STATUS_ERROR(ERROR_DISCONNECTED,
1245 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001246 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001247 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001248 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001249 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1250 if (hasSystemCameraPermissions) {
1251 cameraIdBound = mNumberOfCameras;
1252 }
1253 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001254 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1255 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001256 }
1257
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001258 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001259 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001260 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001261 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001262 if (err != OK) {
1263 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1264 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1265 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001266 logServiceError(std::string("Error retrieving camera info from device ")
1267 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001268 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001269
Ruben Brunkcc776712015-02-17 20:18:47 -08001270 return ret;
1271}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001272
Biswarup Pal37a75182024-01-16 15:53:35 +00001273std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1274 int32_t deviceId, int32_t devicePolicy) {
1275 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1276 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1277 std::optional<std::string> cameraIdOptional =
1278 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1279 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1280 }
1281
1282 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001283 auto callingPid = getCallingPid();
1284 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001285 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1286 callingPid, callingUid, /* checkCameraPermissions= */ false);
1287 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001288 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001289 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001290 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1291 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1292 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001293 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001294 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001295
malikakash98260df2024-05-10 23:33:57 +00001296 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001297}
1298
Biswarup Pal37a75182024-01-16 15:53:35 +00001299std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1300 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001301 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001302 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001303}
1304
Austin Borgered99f642023-06-01 16:51:35 -07001305Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001306 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1307 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001308 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001309
Zhijun He2b59be82013-09-25 10:14:30 -07001310 if (!cameraInfo) {
1311 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001312 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001313 }
1314
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001315 if (!mInitialized) {
1316 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001317 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001318 return STATUS_ERROR(ERROR_DISCONNECTED,
1319 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001320 }
1321
Austin Borger65e64642024-06-11 15:58:23 -07001322 std::optional<std::string> cameraIdOptional =
1323 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001324 if (!cameraIdOptional.has_value()) {
1325 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001326 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001327 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1328 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1329 }
1330 std::string cameraId = cameraIdOptional.value();
1331
Austin Borgered99f642023-06-01 16:51:35 -07001332 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001333 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001334 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001335 }
1336
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001337 bool overrideForPerfClass =
1338 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001339 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001340 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001341 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001342 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001343 if (res == NAME_NOT_FOUND) {
1344 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001345 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001346 strerror(-res), res);
1347 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001348 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1349 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001350 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001351 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001352 strerror(-res), res);
1353 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001354 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001355
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001356 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001357}
1358
Austin Borger65e64642024-06-11 15:58:23 -07001359Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1360 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001361 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001362 ATRACE_CALL();
1363 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001364
Austin Borger65e64642024-06-11 15:58:23 -07001365 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1366 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001367 if (!cameraIdOptional.has_value()) {
1368 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001369 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001370 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1371 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1372 }
1373 std::string cameraId = cameraIdOptional.value();
1374
Rucha Katakwar38284522021-11-10 11:25:21 -08001375 if (!mInitialized) {
1376 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1377 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1378 }
1379
Biswarup Pal37a75182024-01-16 15:53:35 +00001380 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001381 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1382 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1383 }
1384
Austin Borgered99f642023-06-01 16:51:35 -07001385 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001386 if (res != OK) {
1387 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001388 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001389 strerror(-res), res);
1390 }
1391 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1392 return Status::ok();
1393}
1394
Austin Borgered99f642023-06-01 16:51:35 -07001395std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001396 time_t now = time(nullptr);
1397 char formattedTime[64];
1398 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001399 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001400}
1401
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001402Status CameraService::getCameraVendorTagDescriptor(
1403 /*out*/
1404 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001405 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001406 if (!mInitialized) {
1407 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001408 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001409 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001410 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1411 if (globalDescriptor != nullptr) {
1412 *desc = *(globalDescriptor.get());
1413 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001414 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001415}
1416
Emilian Peev71c73a22017-03-21 16:35:51 +00001417Status CameraService::getCameraVendorTagCache(
1418 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1419 ATRACE_CALL();
1420 if (!mInitialized) {
1421 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1422 return STATUS_ERROR(ERROR_DISCONNECTED,
1423 "Camera subsystem not available");
1424 }
1425 sp<VendorTagDescriptorCache> globalCache =
1426 VendorTagDescriptorCache::getGlobalVendorTagCache();
1427 if (globalCache != nullptr) {
1428 *cache = *(globalCache.get());
1429 }
1430 return Status::ok();
1431}
1432
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001433void CameraService::clearCachedVariables() {
1434 BasicClient::BasicClient::sCameraService = nullptr;
1435}
1436
Austin Borgered99f642023-06-01 16:51:35 -07001437std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001438 int rotationOverride, int* portraitRotation, int* facing,
1439 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001440 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001441
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001442 int deviceVersion = 0;
1443
Emilian Peevf53f66e2017-04-11 14:29:43 +01001444 status_t res;
1445 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001446 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001447 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001448 if (res != OK || transport == IPCTransport::INVALID) {
1449 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001450 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001451 return std::make_pair(-1, IPCTransport::INVALID) ;
1452 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001453 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001454
Emilian Peevf53f66e2017-04-11 14:29:43 +01001455 hardware::CameraInfo info;
1456 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001457 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001458 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001459 if (res != OK) {
1460 return std::make_pair(-1, IPCTransport::INVALID);
1461 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001462 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001463 if (orientation) {
1464 *orientation = info.orientation;
1465 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001466 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001467
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001468 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001469}
1470
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001471Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001472 switch(err) {
1473 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001474 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001475 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001476 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1477 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001478 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001479 return STATUS_ERROR(ERROR_DISCONNECTED,
1480 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001481 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001482 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1483 "Camera HAL encountered error %d: %s",
1484 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001485 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001486}
1487
Austin Borger2e772b82024-10-11 16:09:57 -07001488Status CameraService::makeClient(
1489 const sp<CameraService>& cameraService, const sp<IInterface>& cameraCb,
1490 const AttributionSourceState& clientAttribution, int callingPid, bool systemNativeClient,
1491 const std::string& cameraId, int api1CameraId, int facing, int sensorOrientation,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001492 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001493 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001494 bool forceSlowJpegMode, const std::string& originalCameraId, bool sharedMode,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00001495 bool isVendorClient,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001496 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001497 // For HIDL devices
1498 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1499 // Create CameraClient based on device version reported by the HAL.
1500 int deviceVersion = deviceVersionAndTransport.first;
1501 switch(deviceVersion) {
1502 case CAMERA_DEVICE_API_VERSION_1_0:
1503 ALOGE("Camera using old HAL version: %d", deviceVersion);
1504 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1505 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001506 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001507 break;
1508 case CAMERA_DEVICE_API_VERSION_3_0:
1509 case CAMERA_DEVICE_API_VERSION_3_1:
1510 case CAMERA_DEVICE_API_VERSION_3_2:
1511 case CAMERA_DEVICE_API_VERSION_3_3:
1512 case CAMERA_DEVICE_API_VERSION_3_4:
1513 case CAMERA_DEVICE_API_VERSION_3_5:
1514 case CAMERA_DEVICE_API_VERSION_3_6:
1515 case CAMERA_DEVICE_API_VERSION_3_7:
1516 break;
1517 default:
1518 // Should not be reachable
1519 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1520 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1521 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001522 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001523 }
1524 }
1525 if (effectiveApiLevel == API_1) { // Camera1 API route
1526 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001527 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger2e772b82024-10-11 16:09:57 -07001528 cameraService->mAttributionAndPermissionUtils,
1529 clientAttribution, callingPid, cameraId, api1CameraId, facing,
1530 sensorOrientation, servicePid, overrideForPerfClass,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001531 rotationOverride, forceSlowJpegMode, /*sharedMode*/false);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001532 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1533 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001534 } else { // Camera2 API route
1535 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1536 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger2e772b82024-10-11 16:09:57 -07001537 *client = new CameraDeviceClient(
1538 cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1539 cameraService->mAttributionAndPermissionUtils, clientAttribution, callingPid,
1540 systemNativeClient, cameraId, facing, sensorOrientation, servicePid,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00001541 overrideForPerfClass, rotationOverride, originalCameraId, sharedMode,
1542 isVendorClient);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001543 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001544 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001545 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001546}
1547
Austin Borgered99f642023-06-01 16:51:35 -07001548std::string CameraService::toString(std::set<userid_t> intSet) {
1549 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001550 bool first = true;
1551 for (userid_t i : intSet) {
1552 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001553 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001554 first = false;
1555 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001556 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001557 }
1558 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001559 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001560}
1561
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001562int32_t CameraService::mapToInterface(TorchModeStatus status) {
1563 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1564 switch (status) {
1565 case TorchModeStatus::NOT_AVAILABLE:
1566 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1567 break;
1568 case TorchModeStatus::AVAILABLE_OFF:
1569 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1570 break;
1571 case TorchModeStatus::AVAILABLE_ON:
1572 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1573 break;
1574 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001575 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001576 }
1577 return serviceStatus;
1578}
1579
1580CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1581 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1582 switch (status) {
1583 case CameraDeviceStatus::NOT_PRESENT:
1584 serviceStatus = StatusInternal::NOT_PRESENT;
1585 break;
1586 case CameraDeviceStatus::PRESENT:
1587 serviceStatus = StatusInternal::PRESENT;
1588 break;
1589 case CameraDeviceStatus::ENUMERATING:
1590 serviceStatus = StatusInternal::ENUMERATING;
1591 break;
1592 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001593 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001594 }
1595 return serviceStatus;
1596}
1597
1598int32_t CameraService::mapToInterface(StatusInternal status) {
1599 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1600 switch (status) {
1601 case StatusInternal::NOT_PRESENT:
1602 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1603 break;
1604 case StatusInternal::PRESENT:
1605 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1606 break;
1607 case StatusInternal::ENUMERATING:
1608 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1609 break;
1610 case StatusInternal::NOT_AVAILABLE:
1611 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1612 break;
1613 case StatusInternal::UNKNOWN:
1614 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1615 break;
1616 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001617 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001618 }
1619 return serviceStatus;
1620}
1621
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001622Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001623 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001624
Austin Borgered99f642023-06-01 16:51:35 -07001625 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001627 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001628
Austin Borgerb01a8702024-07-22 16:20:34 -07001629 int callingPid = getCallingPid();
1630 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001631
Austin Borger23694432024-10-07 19:28:01 -07001632 AttributionSourceState clientAttribution =
1633 buildAttributionSource(callingPid, uid, kServiceName, kDefaultDeviceId);
1634
1635 if (!(ret = connectHelper<ICameraClient, Client>(
1636 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId, clientAttribution,
1637 /*systemNativeClient*/ false, API_1, /*shimUpdateOnly*/ true,
1638 /*oomScoreOffset*/ 0,
1639 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1640 /*rotationOverride*/
1641 hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001642 /*forceSlowJpegMode*/ false, cameraIdStr, /*isNonSystemNdk*/ false,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00001643 /*sharedMode*/false, /*isVendorClient*/false,/*out*/ tmp))
Austin Borger23694432024-10-07 19:28:01 -07001644 .isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001645 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001646 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001647 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001648}
1649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651 /*out*/
1652 CameraParameters* parameters) {
1653
1654 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1655
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001656 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001657
1658 if (parameters == NULL) {
1659 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001660 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001661 }
1662
malikakash98260df2024-05-10 23:33:57 +00001663 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001664
1665 // Check if we already have parameters
1666 {
1667 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001668 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001669 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001670 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001671 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001672 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001673 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001674 }
1675 CameraParameters p = cameraState->getShimParams();
1676 if (!p.isEmpty()) {
1677 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001678 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001679 }
1680 }
1681
Austin Borger22c5c852024-03-08 13:31:36 -08001682 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001683 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001684 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001685 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001686 // Error already logged by callee
1687 return ret;
1688 }
1689
1690 // Check for parameters again
1691 {
1692 // Scope for service lock
1693 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001694 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001695 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001696 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001697 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001698 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001699 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001700 CameraParameters p = cameraState->getShimParams();
1701 if (!p.isEmpty()) {
1702 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001703 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001704 }
1705 }
1706
Ruben Brunkcc776712015-02-17 20:18:47 -08001707 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1708 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001709 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001710}
1711
Austin Borgered99f642023-06-01 16:51:35 -07001712Status CameraService::validateConnectLocked(const std::string& cameraId,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001713 const AttributionSourceState& clientAttribution,
1714 bool sharedMode) const {
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001715#ifdef __BRILLO__
Austin Borger23694432024-10-07 19:28:01 -07001716 UNUSED(clientAttribution);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001717#else
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001718 Status allowed = validateClientPermissionsLocked(cameraId, clientAttribution, sharedMode);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001719 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001720 return allowed;
1721 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001722#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001723
Austin Borger22c5c852024-03-08 13:31:36 -08001724 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001725
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001726 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001727 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1728 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001729 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001730 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001731 }
1732
Ruben Brunkcc776712015-02-17 20:18:47 -08001733 if (getCameraState(cameraId) == nullptr) {
1734 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001735 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001736 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001737 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738 }
1739
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001740 status_t err = checkIfDeviceIsUsable(cameraId);
1741 if (err != NO_ERROR) {
1742 switch(err) {
1743 case -ENODEV:
1744 case -EBUSY:
1745 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001746 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001747 default:
1748 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001749 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001750 }
1751 }
1752 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001753}
1754
Austin Borger23694432024-10-07 19:28:01 -07001755Status CameraService::validateClientPermissionsLocked(
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001756 const std::string& cameraId, const AttributionSourceState& clientAttribution,
1757 bool sharedMode) const {
Austin Borgerb01a8702024-07-22 16:20:34 -07001758 int callingPid = getCallingPid();
1759 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001760
Austin Borger23694432024-10-07 19:28:01 -07001761 int clientPid = clientAttribution.pid;
1762 int clientUid = clientAttribution.uid;
1763 const std::string clientName = clientAttribution.packageName.value_or(kUnknownPackageName);
1764
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001765 if (shouldRejectSystemCameraConnection(cameraId)) {
1766 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1767 cameraId.c_str());
1768 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001769 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001770 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001771 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1772 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001773 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001774 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001775 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001776 }
1777
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001778 if (flags::camera_multi_client() && sharedMode
1779 && (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA)) {
1780 ALOGE("%s: camera id %s is not system camera. Device sharing only supported for"
1781 " system cameras.", __FUNCTION__, cameraId.c_str());
1782 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "camera device sharing not supported for "
1783 "camera ID \"%s\"", cameraId.c_str());
1784 }
1785
Biswarup Pale506e732024-03-27 13:46:20 +00001786 // Get the device id that owns this camera.
1787 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Austin Borger23694432024-10-07 19:28:01 -07001788 AttributionSourceState clientAttributionWithDeviceId = clientAttribution;
1789 clientAttributionWithDeviceId.deviceId = deviceId;
Biswarup Pale506e732024-03-27 13:46:20 +00001790
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001791 // If it's not calling from cameraserver, check the permission if the
1792 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1793 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001794 bool checkPermissionForCamera =
Austin Borger23694432024-10-07 19:28:01 -07001795 hasPermissionsForCamera(cameraId, clientAttributionWithDeviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001796 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001797 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001798 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001799 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1800 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001801 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001802 }
1803
Svet Ganova453d0d2018-01-11 15:37:58 -08001804 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001805 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001806 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001807 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1808 clientPid, clientUid);
1809 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001810 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1811 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001812 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001813 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001814 }
1815
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001816 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1817 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1818 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1819 if ((!isAutomotivePrivilegedClient(callingUid) ||
1820 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1821 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001822 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1823 return STATUS_ERROR_FMT(ERROR_DISABLED,
1824 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001825 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001826 }
1827
Austin Borger6e831c42024-07-22 13:07:56 -07001828 userid_t clientUserId = multiuser_get_user_id(clientUid);
1829
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001830 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1831 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001832
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001833 // For non-system clients : Only allow clients who are being used by the current foreground
1834 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001835 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001836 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001837 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1838 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001839 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001840 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1841 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001842 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001843 }
1844
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001845 if (flags::camera_hsum_permission()) {
1846 // If the System User tries to access the camera when the device is running in
1847 // headless system user mode, ensure that client has the required permission
1848 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001849 if (isHeadlessSystemUserMode()
1850 && (clientUserId == USER_SYSTEM)
1851 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001852 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001853 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1854 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1855 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001856 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001857 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001858 }
1859
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001860 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001861}
1862
Austin Borgered99f642023-06-01 16:51:35 -07001863status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001864 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001865 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001866 if (cameraState == nullptr) {
1867 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001868 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001869 return -ENODEV;
1870 }
1871
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001872 StatusInternal currentStatus = cameraState->getStatus();
1873 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001874 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001875 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001876 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001877 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001878 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001879 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001880 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001881 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001882
Ruben Brunkcc776712015-02-17 20:18:47 -08001883 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001884}
1885
Ruben Brunkcc776712015-02-17 20:18:47 -08001886void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001887 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001888
Ruben Brunkcc776712015-02-17 20:18:47 -08001889 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001890 auto clientDescriptor =
1891 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001892 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1894
1895 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001896 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001897
1898 if (evicted.size() > 0) {
1899 // This should never happen - clients should already have been removed in disconnect
1900 for (auto& i : evicted) {
1901 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001902 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001903 }
1904
1905 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1906 __FUNCTION__);
1907 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001908
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001909 if (flags::camera_multi_client()) {
1910 sp<BasicClient> clientSp = clientDescriptor->getValue();
1911 auto primaryClient = mActiveClientManager.getPrimaryClient(desc->getKey());
1912 if (primaryClient == nullptr) {
1913 // There is no primary client yet. Assign this first client as
1914 // primary
1915 clientSp->setPrimaryClient(true);
1916 } else {
1917 // There is already primary client. If the incoming client has a
1918 // higher priority than the existing primary, then assign incoming
1919 // client as primary and change the existing client to secondary.
1920 // Otherwise incoming client is secondary client.
1921 if (clientDescriptor->getPriority() <= primaryClient->getPriority()) {
1922 clientSp->setPrimaryClient(true);
1923 primaryClient->getValue()->setPrimaryClient(false);
1924 primaryClient->getValue()->notifyClientSharedAccessPriorityChanged(false);
1925 } else {
1926 clientSp->setPrimaryClient(false);
1927 }
1928 }
1929 }
1930
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001931 // And register a death notification for the client callback. Do
1932 // this last to avoid Binder policy where a nested Binder
1933 // transaction might be pre-empted to service the client death
1934 // notification if the client process dies before linkToDeath is
1935 // invoked.
1936 sp<IBinder> remoteCallback = client->getRemote();
1937 if (remoteCallback != nullptr) {
1938 remoteCallback->linkToDeath(this);
1939 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001940}
1941
Austin Borgered99f642023-06-01 16:51:35 -07001942status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1943 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1944 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001945 bool sharedMode,
Ruben Brunkcc776712015-02-17 20:18:47 -08001946 /*out*/
1947 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001948 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001949 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001950 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001951 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001952 DescriptorPtr clientDescriptor;
1953 {
1954 if (effectiveApiLevel == API_1) {
1955 // If we are using API1, any existing client for this camera ID with the same remote
1956 // should be returned rather than evicted to allow MediaRecorder to work properly.
1957
1958 auto current = mActiveClientManager.get(cameraId);
1959 if (current != nullptr) {
1960 auto clientSp = current->getValue();
1961 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001962 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001963 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001964 " API level, evicting prior client...");
1965 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001966 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001967 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001968 *client = clientSp;
1969 return NO_ERROR;
1970 }
1971 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001972 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001973 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001974
Ruben Brunkcc776712015-02-17 20:18:47 -08001975 // Get state for the given cameraId
1976 auto state = getCameraState(cameraId);
1977 if (state == nullptr) {
1978 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001979 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001980 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001981 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001982 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001983
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001984 sp<IServiceManager> sm = defaultServiceManager();
1985 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001986 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001987 // If processinfo service is not available and the client is automotive privileged
1988 // client used for safety critical uses cases such as rear-view and surround-view which
1989 // needs to be available before android boot completes, then use the hardcoded values
1990 // for the process state and priority score. As this scenario is before android system
1991 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1992 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1993 // visible on the top.
1994 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1995 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1996 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001997 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient,
1998 sharedMode);
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001999 } else {
2000 // Get current active client PIDs
2001 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2002 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002003
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002004 std::vector<int> priorityScores(ownerPids.size());
2005 std::vector<int> states(ownerPids.size());
2006
2007 // Get priority scores of all active PIDs
2008 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2009 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2010 if (err != OK) {
2011 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2012 return err;
2013 }
2014
2015 // Update all active clients' priorities
2016 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2017 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2018 pidToPriorityMap.emplace(ownerPids[i],
2019 resource_policy::ClientPriority(priorityScores[i], states[i],
2020 /* isVendorClient won't get copied over*/ false,
2021 /* oomScoreOffset won't get copied over*/ 0));
2022 }
2023 mActiveClientManager.updatePriorities(pidToPriorityMap);
2024
2025 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2026 int32_t actualState = states[states.size() - 1];
2027
2028 // Make descriptor for incoming client. We store the oomScoreOffset
2029 // since we might need it later on new handleEvictionsLocked and
2030 // ProcessInfoService would not take that into account.
2031 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2032 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2033 state->getConflicting(), actualScore, clientPid, actualState,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002034 oomScoreOffset, systemNativeClient, sharedMode);
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002035 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002036
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002037 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2038
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 // Find clients that would be evicted
2040 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2041
2042 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2043 // background, so we cannot do evictions
2044 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2045 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2046 " priority).", clientPid);
2047
2048 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002049 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002050 auto incompatibleClients =
2051 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2052
Austin Borgered99f642023-06-01 16:51:35 -07002053 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2054 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2055 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002056 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002057
2058 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002059 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002060 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002061 i->getKey().c_str(),
2062 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002063 i->getOwnerId(), i->getPriority().getScore(),
2064 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002065 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002066 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2067 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002068 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002069 }
2070
2071 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002072 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002073 mEventLog.add(msg);
2074
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002075 auto current = mActiveClientManager.get(cameraId);
2076 if (current != nullptr) {
2077 return -EBUSY; // CAMERA_IN_USE
2078 } else {
2079 return -EUSERS; // MAX_CAMERAS_IN_USE
2080 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002081 }
2082
2083 for (auto& i : evicted) {
2084 sp<BasicClient> clientSp = i->getValue();
2085 if (clientSp.get() == nullptr) {
2086 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2087
2088 // TODO: Remove this
2089 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2090 __FUNCTION__);
2091 mActiveClientManager.remove(i);
2092 continue;
2093 }
2094
2095 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002096 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002097 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002098
Ruben Brunkcc776712015-02-17 20:18:47 -08002099 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002100 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002101 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2102 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002103 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002104 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002105 i->getPriority().getState(), cameraId.c_str(),
2106 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002107 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002108
2109 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002110 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002111 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002112 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002113 }
2114
Ruben Brunkcc776712015-02-17 20:18:47 -08002115 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2116 // other clients from connecting in mServiceLockWrapper if held
2117 mServiceLock.unlock();
2118
2119 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002120 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002121
2122 // Destroy evicted clients
2123 for (auto& i : evictedClients) {
2124 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002125 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002126 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002127
Austin Borger22c5c852024-03-08 13:31:36 -08002128 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002129
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002130 for (const auto& i : evictedClients) {
2131 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002132 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002133 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2134 if (ret == TIMED_OUT) {
2135 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002136 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2137 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002138 return -EBUSY;
2139 }
2140 if (ret != NO_ERROR) {
2141 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002142 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2143 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002144 return ret;
2145 }
2146 }
2147
2148 evictedClients.clear();
2149
Ruben Brunkcc776712015-02-17 20:18:47 -08002150 // Once clients have been disconnected, relock
2151 mServiceLock.lock();
2152
2153 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2154 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2155 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002156 }
2157
Ruben Brunkcc776712015-02-17 20:18:47 -08002158 *partial = clientDescriptor;
2159 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002160}
2161
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002162Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002163 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002164 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002165 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002166 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002167 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002168 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002169 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002170 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002171 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002172 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002173 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002174
Austin Borger65e64642024-06-11 15:58:23 -07002175 std::string cameraIdStr =
2176 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002177 if (cameraIdStr.empty()) {
2178 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002179 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002180 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2181 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2182 }
malikakashedb38962023-09-06 00:03:35 +00002183
Austin Borger7d2b9232024-07-22 14:17:14 -07002184 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2185 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002186
Austin Borger95a00152024-09-23 17:20:24 -07002187 AttributionSourceState resolvedClientAttribution(clientAttribution);
2188 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraIdStr);
2189 if (!ret.isOk()) {
2190 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002191 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002192 toStdString(ret.toString8()));
2193 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002194 }
2195
Austin Borger95a00152024-09-23 17:20:24 -07002196 const int clientPid = resolvedClientAttribution.pid;
2197 const int clientUid = resolvedClientAttribution.uid;
2198 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2199
2200 logConnectionAttempt(clientPid, clientPackageName, cameraIdStr, API_1);
Austin Borgerb01a8702024-07-22 16:20:34 -07002201
Ruben Brunkcc776712015-02-17 20:18:47 -08002202 sp<Client> client = nullptr;
Austin Borger23694432024-10-07 19:28:01 -07002203 ret = connectHelper<ICameraClient, Client>(
2204 cameraClient, cameraIdStr, api1CameraId, resolvedClientAttribution,
2205 /*systemNativeClient*/ false, API_1,
2206 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, rotationOverride,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002207 forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*sharedMode*/false,
2208 /*isVendorClient*/ false, /*out*/ client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002209
Biswarup Pal37a75182024-01-16 15:53:35 +00002210 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002211 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002212 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002213 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002214 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002215 }
2216
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002217 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002218
2219 const sp<IServiceManager> sm(defaultServiceManager());
2220 const auto& mActivityManager = getActivityManager();
2221 if (mActivityManager) {
2222 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002223 getCallingUid(),
2224 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002225 }
2226
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002227 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002228}
2229
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002230bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2231 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002232 // If the client is not a vendor client, don't add listener if
2233 // a) the camera is a publicly hidden secure camera OR
2234 // b) the camera is a system only camera and the client doesn't
2235 // have android.permission.SYSTEM_CAMERA permissions.
2236 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2237 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002238 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002239 return true;
2240 }
2241 return false;
2242}
2243
Austin Borgered99f642023-06-01 16:51:35 -07002244bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002245 // Rules for rejection:
2246 // 1) If cameraserver tries to access this camera device, accept the
2247 // connection.
2248 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002249 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002250 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2251 // and the serving thread is a non hwbinder thread, the client must have
2252 // android.permission.SYSTEM_CAMERA permissions to connect.
2253
Austin Borger22c5c852024-03-08 13:31:36 -08002254 int cPid = getCallingPid();
2255 int cUid = getCallingUid();
2256 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002257 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2258 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002259 // This isn't a known camera ID, so it's not a system camera
2260 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2261 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002262 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002263
2264 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002265 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002266 return false;
2267 }
2268 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002269 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002270 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2271 return true;
2272 }
2273 // (3) Here we only check for permissions if it is a system only camera device. This is since
2274 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2275 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2276 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002277 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002278 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002279 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2280 cameraId.c_str());
2281 return true;
2282 }
2283
2284 return false;
2285}
2286
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002287Status CameraService::connectDevice(
2288 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002289 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002290 int oomScoreOffset, int targetSdkVersion,
2291 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002292 bool sharedMode,
2293 /*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {
2294 return connectDeviceImpl(cameraCb, unresolvedCameraId, oomScoreOffset, targetSdkVersion,
2295 rotationOverride, clientAttribution, devicePolicy, sharedMode,
2296 /*isVendorClient*/false, device);
2297}
2298
2299Status CameraService::connectDeviceVendor(
2300 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
2301 const std::string& unresolvedCameraId,
2302 int oomScoreOffset, int targetSdkVersion,
2303 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
2304 bool sharedMode,
2305 /*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {
2306 return connectDeviceImpl(cameraCb, unresolvedCameraId, oomScoreOffset, targetSdkVersion,
2307 rotationOverride, clientAttribution, devicePolicy, sharedMode,
2308 /*isVendorClient*/true, device);
2309}
2310
2311Status CameraService::connectDeviceImpl(
2312 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
2313 const std::string& unresolvedCameraId,
2314 int oomScoreOffset, int targetSdkVersion,
2315 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
2316 bool sharedMode, bool isVendorClient,
2317 /*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002318 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002319 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002320 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002321 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002322 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002323 int callingPid = getCallingPid();
2324 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002325 bool systemNativeClient = false;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002326 AttributionSourceState resolvedClientAttribution(clientAttribution);
Austin Borger7d2b9232024-07-22 14:17:14 -07002327 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002328 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002329 clientPackageNameMaybe = systemClient;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002330 // Pass in packageName since AttributionAndPermissionUtils can't resolve vndk clients.
2331 resolvedClientAttribution.packageName = clientPackageNameMaybe;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002332 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002333 }
Austin Borger249e6592024-03-10 22:28:11 -07002334
Austin Borger65e64642024-06-11 15:58:23 -07002335 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2336 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002337 if (!cameraIdOptional.has_value()) {
2338 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002339 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002340 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2341 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2342 }
2343 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002344
Austin Borger7d2b9232024-07-22 14:17:14 -07002345 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002346
Austin Borger2a3f9a72024-11-07 12:24:49 -08002347 if (!flags::data_delivery_permission_checks()) {
Austin Borger95a00152024-09-23 17:20:24 -07002348 resolvedClientAttribution.pid = USE_CALLING_PID;
2349 }
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002350
Austin Borger95a00152024-09-23 17:20:24 -07002351 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraId);
2352 if (!ret.isOk()) {
2353 logRejected(cameraId, getCallingPid(), clientAttribution.packageName.value_or(""),
2354 toStdString(ret.toString8()));
2355 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002356 }
2357
Austin Borger95a00152024-09-23 17:20:24 -07002358 const int clientPid = resolvedClientAttribution.pid;
2359 const int clientUid = resolvedClientAttribution.uid;
2360 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2361 userid_t clientUserId = multiuser_get_user_id(resolvedClientAttribution.uid);
Austin Borgerb01a8702024-07-22 16:20:34 -07002362
Austin Borger95a00152024-09-23 17:20:24 -07002363 logConnectionAttempt(clientPid, clientPackageName, cameraId, API_2);
Austin Borgerb01a8702024-07-22 16:20:34 -07002364
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002365 if (oomScoreOffset < 0) {
Austin Borger95a00152024-09-23 17:20:24 -07002366 std::string msg = fmt::sprintf(
2367 "Cannot increase the priority of a client %s pid %d for "
2368 "camera id %s",
2369 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002370 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2371 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002372 }
2373
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002374 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2375 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002376 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2377 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002378 std::string msg = "Camera disabled by device policy";
2379 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2380 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002381 }
2382
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002383 // enforce system camera permissions
Austin Borger95a00152024-09-23 17:20:24 -07002384 if (oomScoreOffset > 0 && !hasPermissionsForSystemCamera(cameraId, clientPid, callingUid) &&
2385 !isTrustedCallingUid(callingUid)) {
2386 std::string msg = fmt::sprintf(
2387 "Cannot change the priority of a client %s pid %d for "
2388 "camera id %s without SYSTEM_CAMERA permissions",
2389 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002390 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2391 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002392 }
2393
Austin Borger95a00152024-09-23 17:20:24 -07002394 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks, CameraDeviceClient>(
Austin Borger23694432024-10-07 19:28:01 -07002395 cameraCb, cameraId, /*api1CameraId*/ -1, resolvedClientAttribution, systemNativeClient,
2396 API_2, /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002397 /*forceSlowJpegMode*/ false, unresolvedCameraId, isNonSystemNdk, sharedMode,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002398 isVendorClient, /*out*/ client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002399
Biswarup Pal37a75182024-01-16 15:53:35 +00002400 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002401 logRejected(cameraId, clientPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002402 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002403 }
2404
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002405 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002406 Mutex::Autolock lock(mServiceLock);
2407
2408 // Clear the previous cached logs and reposition the
2409 // file offset to beginning of the file to log new data.
2410 // If either truncate or lseek fails, close the previous file and create a new one.
2411 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2412 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2413 // Close the previous memfd.
2414 close(mMemFd);
2415 // If failure to wipe the data, then create a new file and
2416 // assign the new value to mMemFd.
2417 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2418 if (mMemFd == -1) {
2419 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2420 }
2421 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002422 const sp<IServiceManager> sm(defaultServiceManager());
2423 const auto& mActivityManager = getActivityManager();
2424 if (mActivityManager) {
2425 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002426 callingUid,
2427 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002428 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002429 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002430}
2431
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002432bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2433 int callingPid, int callingUid) {
2434 if (!isAutomotiveDevice()) {
2435 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2436 }
2437
2438 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2439 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2440 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2441 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2442 "using camera %s", callingUid, cam_id.c_str());
2443 return false;
2444 }
2445
2446 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2447 return true;
2448 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2449 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002450 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2451 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002452 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2453 return false;
2454 } else {
2455 return true;
2456 }
2457 }
2458 return false;
2459}
2460
Austin Borger7d2b9232024-07-22 14:17:14 -07002461void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
Austin Borger95a00152024-09-23 17:20:24 -07002462 const std::string& cameraId,
2463 apiLevel effectiveApiLevel) const {
Austin Borger7d2b9232024-07-22 14:17:14 -07002464 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borger95a00152024-09-23 17:20:24 -07002465 "Camera API version %d",
2466 clientPid, clientPackageName.c_str(), cameraId.c_str(),
2467 static_cast<int>(effectiveApiLevel));
Austin Borger7d2b9232024-07-22 14:17:14 -07002468}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002469
Austin Borger23694432024-10-07 19:28:01 -07002470template <class CALLBACK, class CLIENT>
Austin Borger7d2b9232024-07-22 14:17:14 -07002471Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
Austin Borger23694432024-10-07 19:28:01 -07002472 int api1CameraId,
2473 const AttributionSourceState& clientAttribution,
2474 bool systemNativeClient, apiLevel effectiveApiLevel,
2475 bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2476 int rotationOverride, bool forceSlowJpegMode,
2477 const std::string& originalCameraId, bool isNonSystemNdk,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002478 bool sharedMode, bool isVendorClient,
2479 /*out*/ sp<CLIENT>& device) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002480 binder::Status ret = binder::Status::ok();
2481
Shuzhen Wang316781a2020-08-18 18:11:01 -07002482 nsecs_t openTimeNs = systemTime();
2483
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002484 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002485 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002486 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002487
Austin Borger23694432024-10-07 19:28:01 -07002488 const std::string clientPackageName =
2489 clientAttribution.packageName.value_or(kUnknownPackageName);
2490
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002491 {
2492 // Acquire mServiceLock and prevent other clients from connecting
2493 std::unique_ptr<AutoConditionLock> lock =
2494 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2495
2496 if (lock == nullptr) {
Austin Borger23694432024-10-07 19:28:01 -07002497 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting).",
2498 clientAttribution.pid);
2499 return STATUS_ERROR_FMT(
2500 ERROR_MAX_CAMERAS_IN_USE,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002501 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borger23694432024-10-07 19:28:01 -07002502 cameraId.c_str(), clientPackageName.c_str(), clientAttribution.pid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002503 }
2504
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002505 // Enforce client permissions and do basic validity checks
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002506 if (!(ret = validateConnectLocked(cameraId, clientAttribution, sharedMode)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002507 return ret;
2508 }
2509
2510 // Check the shim parameters after acquiring lock, if they have already been updated and
2511 // we were doing a shim update, return immediately
2512 if (shimUpdateOnly) {
2513 auto cameraState = getCameraState(cameraId);
2514 if (cameraState != nullptr) {
2515 if (!cameraState->getShimParams().isEmpty()) return ret;
2516 }
2517 }
2518
2519 status_t err;
2520
2521 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002522 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger23694432024-10-07 19:28:01 -07002523 if ((err = handleEvictionsLocked(
2524 cameraId, clientAttribution.pid, effectiveApiLevel,
2525 IInterface::asBinder(cameraCb),
2526 clientAttribution.packageName.value_or(kUnknownPackageName), oomScoreOffset,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002527 systemNativeClient, sharedMode, /*out*/ &clientTmp,
Austin Borger23694432024-10-07 19:28:01 -07002528 /*out*/ &partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002529 switch (err) {
2530 case -ENODEV:
2531 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2532 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002533 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002534 case -EBUSY:
2535 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2536 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002537 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002538 case -EUSERS:
2539 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2540 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002541 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002542 default:
2543 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2544 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002545 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002546 }
2547 }
2548
2549 if (clientTmp.get() != nullptr) {
2550 // Handle special case for API1 MediaRecorder where the existing client is returned
2551 device = static_cast<CLIENT*>(clientTmp.get());
2552 return ret;
2553 }
2554
2555 // give flashlight a chance to close devices if necessary.
2556 mFlashlight->prepareDeviceOpen(cameraId);
2557
Austin Borger18b30a72022-10-27 12:20:29 -07002558 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002559 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002560 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002561 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002562 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002563 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002564 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002565 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002566 }
2567
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002568 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002569 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002570 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002571
Austin Borger6e831c42024-07-22 13:07:56 -07002572 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2573 // that's connected to camera service directly.
Austin Borger2e772b82024-10-11 16:09:57 -07002574 if (!(ret = makeClient(this, cameraCb, clientAttribution, getCallingPid(),
2575 systemNativeClient, cameraId, api1CameraId, facing, orientation,
2576 getpid(), deviceVersionAndTransport, effectiveApiLevel,
2577 overrideForPerfClass, rotationOverride, forceSlowJpegMode,
Jayant Chowdharydcae7962024-08-20 21:20:10 +00002578 originalCameraId, sharedMode, isVendorClient,
Austin Borger23694432024-10-07 19:28:01 -07002579 /*out*/ &tmp))
2580 .isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002581 return ret;
2582 }
2583 client = static_cast<CLIENT*>(tmp.get());
2584
2585 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2586 __FUNCTION__);
2587
Austin Borgered99f642023-06-01 16:51:35 -07002588 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002589 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002590 if (err != OK) {
2591 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002592 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002593 mServiceLock.unlock();
2594 client->disconnect();
2595 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002596 switch(err) {
2597 case BAD_VALUE:
2598 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002599 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002600 case -EBUSY:
2601 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002602 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002603 case -EUSERS:
2604 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2605 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002606 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002607 case PERMISSION_DENIED:
2608 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002609 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002610 case -EACCES:
2611 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002612 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002613 case -ENODEV:
2614 default:
2615 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002616 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002617 strerror(-err), err);
2618 }
2619 }
2620
2621 // Update shim paremeters for legacy clients
2622 if (effectiveApiLevel == API_1) {
2623 // Assume we have always received a Client subclass for API1
2624 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2625 String8 rawParams = shimClient->getParameters();
2626 CameraParameters params(rawParams);
2627
2628 auto cameraState = getCameraState(cameraId);
2629 if (cameraState != nullptr) {
2630 cameraState->setShimParams(params);
2631 } else {
2632 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002633 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002634 }
2635 }
2636
Ravneetaeb20dc2022-03-30 05:33:03 +00002637 // Enable/disable camera service watchdog
2638 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2639
Emilian Peev6d45db82024-01-18 20:11:54 +00002640 CameraMetadata chars;
2641 bool rotateAndCropSupported = true;
2642 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002643 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002644 if (err == OK) {
2645 auto availableRotateCropEntry = chars.find(
2646 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2647 if (availableRotateCropEntry.count <= 1) {
2648 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002649 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002650 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002651 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2652 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002653 }
2654
Emilian Peev6d45db82024-01-18 20:11:54 +00002655 if (rotateAndCropSupported) {
2656 // Set rotate-and-crop override behavior
2657 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2658 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002659 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2660 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002661 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2662 switch (portraitRotation) {
2663 case 90:
2664 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2665 break;
2666 case 180:
2667 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2668 break;
2669 case 270:
2670 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2671 break;
2672 default:
2673 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2674 break;
2675 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002676 // Here we're communicating to the client the chosen rotate
2677 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002678 client->setRotateAndCropOverride(rotateAndCropMode);
2679 } else {
2680 client->setRotateAndCropOverride(
Austin Borger23694432024-10-07 19:28:01 -07002681 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2682 clientPackageName, facing,
2683 multiuser_get_user_id(clientAttribution.uid)));
Emilian Peev6d45db82024-01-18 20:11:54 +00002684 }
2685 }
2686
2687 bool autoframingSupported = true;
2688 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2689 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2690 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2691 autoframingSupported = false;
2692 }
2693
2694 if (autoframingSupported) {
2695 // Set autoframing override behaviour
2696 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2697 client->setAutoframingOverride(mOverrideAutoframingMode);
2698 } else {
2699 client->setAutoframingOverride(
2700 mCameraServiceProxyWrapper->getAutoframingOverride(
2701 clientPackageName));
2702 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002703 }
2704
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002705 bool isCameraPrivacyEnabled;
2706 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002707 // Set camera muting behavior.
Austin Borger23694432024-10-07 19:28:01 -07002708 isCameraPrivacyEnabled =
2709 this->isCameraPrivacyEnabled(toString16(client->getPackageName()), cameraId,
2710 clientAttribution.pid, clientAttribution.uid);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002711 } else {
2712 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002713 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002714 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002715
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002716 if (client->supportsCameraMute()) {
2717 client->setCameraMute(
2718 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2719 } else if (isCameraPrivacyEnabled) {
2720 // no camera mute supported, but privacy is on! => disconnect
2721 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2722 client->getPackageName().c_str(), cameraId.c_str());
2723 // Do not hold mServiceLock while disconnecting clients, but
2724 // retain the condition blocking other clients from connecting
2725 // in mServiceLockWrapper if held.
2726 mServiceLock.unlock();
2727 // Clear caller identity temporarily so client disconnect PID
2728 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002729 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002730 // Note AppOp to trigger the "Unblock" dialog
2731 client->noteAppOp();
2732 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002733 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002734 // Reacquire mServiceLock
2735 mServiceLock.lock();
2736
2737 return STATUS_ERROR_FMT(ERROR_DISABLED,
2738 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002739 }
2740
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002741 if (shimUpdateOnly) {
2742 // If only updating legacy shim parameters, immediately disconnect client
2743 mServiceLock.unlock();
2744 client->disconnect();
2745 mServiceLock.lock();
2746 } else {
2747 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002748 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002749 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002750
2751 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002752 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002753 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002754 } // lock is destroyed, allow further connect calls
2755
2756 // Important: release the mutex here so the client can call back into the service from its
2757 // destructor (can be at the end of the call)
2758 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002759
2760 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002761 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002762 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002763
Cliff Wud3a05312021-04-26 23:07:31 +08002764 {
2765 Mutex::Autolock lock(mInjectionParametersLock);
2766 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2767 mInjectionInitPending = false;
2768 status_t res = NO_ERROR;
2769 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2770 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002771 sp<BasicClient> clientSp = clientDescriptor->getValue();
2772 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2773 if(res != OK) {
2774 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2775 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002776 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002777 }
2778 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002779 if (res != OK) {
2780 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2781 }
2782 } else {
2783 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002784 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002785 res = NO_INIT;
2786 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2787 }
2788 }
2789 }
2790
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002791 return ret;
2792}
2793
Austin Borgered99f642023-06-01 16:51:35 -07002794status_t CameraService::addOfflineClient(const std::string &cameraId,
2795 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002796 if (offlineClient.get() == nullptr) {
2797 return BAD_VALUE;
2798 }
2799
2800 {
2801 // Acquire mServiceLock and prevent other clients from connecting
2802 std::unique_ptr<AutoConditionLock> lock =
2803 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2804
2805 if (lock == nullptr) {
2806 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
Austin Borger2e772b82024-10-11 16:09:57 -07002807 , __FUNCTION__, offlineClient->getClientCallingPid());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002808 return TIMED_OUT;
2809 }
2810
2811 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2812 if (onlineClientDesc.get() == nullptr) {
2813 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2814 cameraId.c_str());
2815 return BAD_VALUE;
2816 }
2817
2818 // Offline clients do not evict or conflict with other online devices. Resource sharing
2819 // conflicts are handled by the camera provider which will either succeed or fail before
2820 // reaching this method.
2821 const auto& onlinePriority = onlineClientDesc->getPriority();
2822 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2823 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002824 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002825 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002826 // native clients don't have offline processing support.
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002827 /*ommScoreOffset*/ 0, /*systemNativeClient*/false, /*sharedMode*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002828 if (offlineClientDesc == nullptr) {
2829 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2830 return BAD_VALUE;
2831 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002832
2833 // Allow only one offline device per camera
2834 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2835 if (!incompatibleClients.empty()) {
2836 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2837 return BAD_VALUE;
2838 }
2839
Austin Borgered99f642023-06-01 16:51:35 -07002840 std::string monitorTags = isClientWatched(offlineClient.get())
2841 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002842 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002843 if (err != OK) {
2844 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2845 return err;
2846 }
2847
2848 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2849 if (evicted.size() > 0) {
2850 for (auto& i : evicted) {
2851 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002852 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002853 }
2854
2855 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2856 "properly", __FUNCTION__);
2857
2858 return BAD_VALUE;
2859 }
2860
2861 logConnectedOffline(offlineClientDesc->getKey(),
2862 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002863 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002864
2865 sp<IBinder> remoteCallback = offlineClient->getRemote();
2866 if (remoteCallback != nullptr) {
2867 remoteCallback->linkToDeath(this);
2868 }
2869 } // lock is destroyed, allow further connect calls
2870
2871 return OK;
2872}
2873
Austin Borgered99f642023-06-01 16:51:35 -07002874Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002875 int32_t torchStrength, const sp<IBinder>& clientBinder,
2876 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 Mutex::Autolock lock(mServiceLock);
2878
2879 ATRACE_CALL();
2880 if (clientBinder == nullptr) {
2881 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2882 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2883 "Torch client binder in null.");
2884 }
2885
Austin Borger22c5c852024-03-08 13:31:36 -08002886 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002887 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2888 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002889 if (!cameraIdOptional.has_value()) {
2890 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002891 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002892 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2893 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2894 }
2895 std::string cameraId = cameraIdOptional.value();
2896
Austin Borgered99f642023-06-01 16:51:35 -07002897 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002898 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002899 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002900 }
2901
2902 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002903 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002904 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002905 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002906 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002907 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002908 }
2909
2910 StatusInternal cameraStatus = state->getStatus();
2911 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2912 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002913 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002914 (int)cameraStatus);
2915 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002916 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002917 }
2918
2919 {
2920 Mutex::Autolock al(mTorchStatusMutex);
2921 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002922 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002923 if (err != OK) {
2924 if (err == NAME_NOT_FOUND) {
2925 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002926 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 }
2928 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002929 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002930 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2931 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002932 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002933 }
2934
2935 if (status == TorchModeStatus::NOT_AVAILABLE) {
2936 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2937 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002938 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002939 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2940 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002941 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002942 } else {
2943 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002944 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002945 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2946 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002947 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002948 }
2949 }
2950 }
2951
2952 {
2953 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002954 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002955 }
2956 // Check if the current torch strength level is same as the new one.
2957 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002958 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002959
Austin Borgered99f642023-06-01 16:51:35 -07002960 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002961
2962 if (err != OK) {
2963 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002964 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002965 switch (err) {
2966 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002967 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2968 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002969 errorCode = ERROR_ILLEGAL_ARGUMENT;
2970 break;
2971 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002972 msg = fmt::sprintf("Camera \"%s\" is in use",
2973 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002974 errorCode = ERROR_CAMERA_IN_USE;
2975 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002976 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002977 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002978 "valid range.", torchStrength);
2979 errorCode = ERROR_ILLEGAL_ARGUMENT;
2980 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002981 default:
Austin Borgered99f642023-06-01 16:51:35 -07002982 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002983 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002984 }
Austin Borgered99f642023-06-01 16:51:35 -07002985 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2986 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002987 }
2988
2989 {
2990 // update the link to client's death
2991 // Store the last client that turns on each camera's torch mode.
2992 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002993 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002994 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002995 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002996 } else {
2997 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2998 mTorchClientMap.replaceValueAt(index, clientBinder);
2999 }
3000 clientBinder->linkToDeath(this);
3001 }
3002
Austin Borger22c5c852024-03-08 13:31:36 -08003003 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003004 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003005 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003006 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003007 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003008 }
3009 return Status::ok();
3010}
3011
malikakash73125c62023-07-21 22:44:34 +00003012Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07003013 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
3014 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003015 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003016
3017 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003018 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003019 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003020 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3021 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003022 }
3023
Austin Borger22c5c852024-03-08 13:31:36 -08003024 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07003025 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
3026 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00003027 if (!cameraIdOptional.has_value()) {
3028 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003029 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00003030 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3031 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3032 }
3033 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003034
Austin Borgered99f642023-06-01 16:51:35 -07003035 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003036 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003037 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003038 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003039 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003040 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003041 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003042 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003043 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003044 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003045 }
3046
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003047 StatusInternal cameraStatus = state->getStatus();
3048 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003049 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003050 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3051 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003052 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003053 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003054 }
3055
3056 {
3057 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003058 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003059 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003060 if (err != OK) {
3061 if (err == NAME_NOT_FOUND) {
3062 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003063 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003064 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003065 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003066 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003067 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003068 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003069 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003070 }
3071
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003072 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003073 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003074 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003075 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003076 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3077 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003078 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003079 } else {
3080 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003081 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003082 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3083 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003084 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003085 }
3086 }
3087 }
3088
Ruben Brunk99e69712015-05-26 17:25:07 -07003089 {
3090 // Update UID map - this is used in the torch status changed callbacks, so must be done
3091 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003092 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003093 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003094 }
3095
Austin Borgered99f642023-06-01 16:51:35 -07003096 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003097
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003098 if (err != OK) {
3099 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003100 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003101 switch (err) {
3102 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003103 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3104 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003105 errorCode = ERROR_ILLEGAL_ARGUMENT;
3106 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003107 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003108 msg = fmt::sprintf("Camera \"%s\" is in use",
3109 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003110 errorCode = ERROR_CAMERA_IN_USE;
3111 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003112 default:
Austin Borgered99f642023-06-01 16:51:35 -07003113 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003114 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003115 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003116 errorCode = ERROR_INVALID_OPERATION;
3117 }
Austin Borgered99f642023-06-01 16:51:35 -07003118 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3119 logServiceError(msg, errorCode);
3120 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003121 }
3122
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003123 {
3124 // update the link to client's death
3125 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003126 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003127 if (enabled) {
3128 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003129 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003130 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003131 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003132 mTorchClientMap.replaceValueAt(index, clientBinder);
3133 }
3134 clientBinder->linkToDeath(this);
3135 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003136 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003137 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003138 }
3139
Austin Borger22c5c852024-03-08 13:31:36 -08003140 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003141 std::string torchState = enabled ? "on" : "off";
3142 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3143 torchState.c_str(), clientPid);
3144 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003145 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003146}
3147
Austin Borgered99f642023-06-01 16:51:35 -07003148void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3149 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3150 mTorchUidMap[cameraId].first = uid;
3151 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003152 } else {
3153 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003154 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003155 }
3156}
3157
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003158Status CameraService::notifySystemEvent(int32_t eventId,
3159 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003160 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003161 const int selfPid = getpid();
3162
3163 // Permission checks
3164 if (pid != selfPid) {
3165 // Ensure we're being called by system_server, or similar process with
3166 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003167 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003168 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003169 ALOGE("Permission Denial: cannot send updates to camera service about system"
3170 " events from pid=%d, uid=%d", pid, uid);
3171 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003172 "No permission to send updates to camera service about system events"
3173 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003174 }
3175 }
3176
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003177 ATRACE_CALL();
3178
Ruben Brunk36597b22015-03-20 22:15:57 -07003179 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003180 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003181 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003182 // from a system server crash
3183 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003184 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003185 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003186 break;
3187 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003188 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3189 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003190 if (args.size() != 1) {
3191 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3192 "USB Device Event requires 1 argument");
3193 }
3194
Valentin Iftime29e2e152021-08-13 15:17:33 +02003195 // Notify CameraProviderManager for lazy HALs
3196 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3197 std::to_string(args[0]));
3198 break;
3199 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003200 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003201 default: {
3202 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3203 eventId);
3204 break;
3205 }
3206 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003207 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003208}
3209
Emilian Peev53722fa2019-02-22 17:47:20 -08003210void CameraService::notifyMonitoredUids() {
3211 Mutex::Autolock lock(mStatusListenerLock);
3212
3213 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003214 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003215 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3216 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003217 }
3218}
3219
Austin Borgerdddb7552023-03-30 17:53:01 -07003220void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3221 Mutex::Autolock lock(mStatusListenerLock);
3222
3223 for (const auto& it : mListenerList) {
3224 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3225 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3226 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3227 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3228 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3229 }
3230 }
3231}
3232
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003233Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003234 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003235 const int selfPid = getpid();
3236
3237 // Permission checks
3238 if (pid != selfPid) {
3239 // Ensure we're being called by system_server, or similar process with
3240 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003241 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003242 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003243 ALOGE("Permission Denial: cannot send updates to camera service about device"
3244 " state changes from pid=%d, uid=%d", pid, uid);
3245 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3246 "No permission to send updates to camera service about device state"
3247 " changes from pid=%d, uid=%d", pid, uid);
3248 }
3249 }
3250
3251 ATRACE_CALL();
3252
Austin Borger18b30a72022-10-27 12:20:29 -07003253 {
3254 Mutex::Autolock lock(mServiceLock);
3255 mDeviceState = newState;
3256 }
3257
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003258 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003259
3260 return Status::ok();
3261}
3262
Emilian Peev8b64f282021-03-25 16:49:57 -07003263Status CameraService::notifyDisplayConfigurationChange() {
3264 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003265 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003266 const int selfPid = getpid();
3267
3268 // Permission checks
3269 if (callingPid != selfPid) {
3270 // Ensure we're being called by system_server, or similar process with
3271 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003272 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003273 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003274 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3275 " changes from pid=%d, uid=%d", callingPid, uid);
3276 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3277 "No permission to send updates to camera service about orientation"
3278 " changes from pid=%d, uid=%d", callingPid, uid);
3279 }
3280 }
3281
3282 Mutex::Autolock lock(mServiceLock);
3283
3284 // Don't do anything if rotate-and-crop override via cmd is active
3285 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3286
3287 const auto clients = mActiveClientManager.getAll();
3288 for (auto& current : clients) {
3289 if (current != nullptr) {
3290 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003291 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3292 basicClient->setRotateAndCropOverride(
3293 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3294 basicClient->getPackageName(),
3295 basicClient->getCameraFacing(),
3296 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003297 }
3298 }
3299 }
3300
3301 return Status::ok();
3302}
3303
3304Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003305 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3306 ATRACE_CALL();
3307 if (!concurrentCameraIds) {
3308 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3309 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3310 }
3311
3312 if (!mInitialized) {
3313 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003314 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003315 return STATUS_ERROR(ERROR_DISCONNECTED,
3316 "Camera subsystem is not available");
3317 }
3318 // First call into the provider and get the set of concurrent camera
3319 // combinations
3320 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003321 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003322 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003323 std::vector<std::pair<std::string, int32_t>> validCombination;
3324 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003325 for (auto &cameraId : combination) {
3326 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003327 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003328 if (state == nullptr) {
3329 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3330 continue;
3331 }
3332 StatusInternal status = state->getStatus();
3333 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3334 continue;
3335 }
Austin Borgered99f642023-06-01 16:51:35 -07003336 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003337 continue;
3338 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003339 auto [cameraOwnerDeviceId, mappedCameraId] =
3340 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3341 if (firstDeviceId == kInvalidDeviceId) {
3342 firstDeviceId = cameraOwnerDeviceId;
3343 } else if (firstDeviceId != cameraOwnerDeviceId) {
3344 // Found an invalid combination which contains cameras with different device id's,
3345 // hence discard it.
3346 validCombination.clear();
3347 break;
3348 }
3349 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003350 }
3351 if (validCombination.size() != 0) {
3352 concurrentCameraIds->push_back(std::move(validCombination));
3353 }
3354 }
3355 return Status::ok();
3356}
3357
3358Status CameraService::isConcurrentSessionConfigurationSupported(
3359 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003360 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003361 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003362 if (!isSupported) {
3363 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3364 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3365 }
3366
3367 if (!mInitialized) {
3368 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3369 return STATUS_ERROR(ERROR_DISCONNECTED,
3370 "Camera subsystem is not available");
3371 }
3372
Biswarup Pal7d072862024-04-17 15:24:47 +00003373 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3374 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003375 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3376 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003377 if (!cameraIdOptional.has_value()) {
3378 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003379 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003380 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3381 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3382 }
3383 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3384 }
3385
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003386 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003387 int callingPid = getCallingPid();
3388 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003389 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003390 hasPermissionsForCamera(callingPid, callingUid,
3391 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003392 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003393 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003394 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3395 "android.permission.CAMERA needed to call"
3396 "isConcurrentSessionConfigurationSupported");
3397 }
3398
3399 status_t res =
3400 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003401 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3402 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003403 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003404 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003405 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003406 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3407 "support %s (%d)", strerror(-res), res);
3408 }
3409 return Status::ok();
3410}
3411
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003412Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3413 /*out*/
3414 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003415 return addListenerHelper(listener, cameraStatuses);
3416}
3417
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003418binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3419 std::vector<hardware::CameraStatus>* cameraStatuses) {
3420 return addListenerHelper(listener, cameraStatuses, false, true);
3421}
3422
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003423Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3424 /*out*/
3425 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003426 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003427 ATRACE_CALL();
3428
Igor Murashkinbfc99152013-02-27 12:55:20 -08003429 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003430
Ruben Brunk3450ba72015-06-16 11:00:37 -07003431 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003432 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003433 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003434 }
3435
Austin Borger22c5c852024-03-08 13:31:36 -08003436 auto clientPid = getCallingPid();
3437 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003438 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003439
Igor Murashkinbfc99152013-02-27 12:55:20 -08003440 Mutex::Autolock lock(mServiceLock);
3441
Ruben Brunkcc776712015-02-17 20:18:47 -08003442 {
3443 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003444 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003445 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003446 ALOGW("%s: Tried to add listener %p which was already subscribed",
3447 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003448 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003449 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003450 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003451
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003452 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003453 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3454 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003455 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003456 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003457 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003458 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003459 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3460 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3461 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003462 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003463 // The listener still needs to be added to the list of listeners, regardless of what
3464 // permissions the listener process has / whether it is a vendor listener. Since it might be
3465 // eligible to listen to other camera ids.
3466 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003467 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003468 }
3469
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003470 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003471 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003472 Mutex::Autolock lock(mCameraStatesLock);
3473 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003474 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3475 auto [deviceId, mappedCameraId] =
3476 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3477
3478 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003479 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003480 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3481 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003482 }
3483 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003484 // Remove the camera statuses that should be hidden from the client, we do
3485 // this after collecting the states in order to avoid holding
3486 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3487 // the same time.
3488 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3489 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003490 std::string cameraId = s.cameraId;
3491 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003492 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003493 if (!cameraIdOptional.has_value()) {
3494 std::string msg =
3495 fmt::sprintf(
3496 "Camera %s: Invalid camera id for device id %d",
3497 s.cameraId.c_str(), s.deviceId);
3498 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3499 return true;
3500 }
3501 cameraId = cameraIdOptional.value();
3502 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3503 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3504 ALOGE("%s: Invalid camera id %s, skipping status update",
3505 __FUNCTION__, s.cameraId.c_str());
3506 return true;
3507 }
3508 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3509 clientUid);
3510 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003511
Biswarup Pal37a75182024-01-16 15:53:35 +00003512 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003513 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003514 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003515 // Add only default device cameras here, as virtual cameras currently don't support torch
3516 // anyway. Note that this is a simplification of the implementation here, and we should
3517 // change this when virtual cameras support torch.
3518 if (s.deviceId == kDefaultDeviceId) {
3519 idsChosenForCallback.insert(s.cameraId);
3520 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003521 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003522
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003523 /*
3524 * Immediately signal current torch status to this listener only
3525 * This may be a subset of all the devices, so don't include it in the response directly
3526 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003527 {
3528 Mutex::Autolock al(mTorchStatusMutex);
3529 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003530 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003531 // The camera id is visible to the client. Fine to send torch
3532 // callback.
3533 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003534 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3535 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003536 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003537 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003538 }
3539
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003540 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003541}
Ruben Brunkcc776712015-02-17 20:18:47 -08003542
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003543Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003544 ATRACE_CALL();
3545
Igor Murashkinbfc99152013-02-27 12:55:20 -08003546 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3547
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003548 if (listener == 0) {
3549 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003550 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003551 }
3552
Igor Murashkinbfc99152013-02-27 12:55:20 -08003553 Mutex::Autolock lock(mServiceLock);
3554
Ruben Brunkcc776712015-02-17 20:18:47 -08003555 {
3556 Mutex::Autolock lock(mStatusListenerLock);
3557 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003558 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003559 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003560 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003561 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003562 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003563 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003564 }
3565 }
3566
3567 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3568 __FUNCTION__, listener.get());
3569
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003570 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003571}
3572
Austin Borgered99f642023-06-01 16:51:35 -07003573Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003574
3575 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003576 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3577
3578 if (parameters == NULL) {
3579 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003580 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003581 }
3582
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003583 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003584
3585 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003586 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003587 // Error logged by caller
3588 return ret;
3589 }
3590
3591 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003592
Austin Borgered99f642023-06-01 16:51:35 -07003593 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003594
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003595 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003596}
3597
malikakash98260df2024-05-10 23:33:57 +00003598Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003599 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003600 ATRACE_CALL();
3601
Austin Borgered99f642023-06-01 16:51:35 -07003602 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003603
3604 switch (apiVersion) {
3605 case API_VERSION_1:
3606 case API_VERSION_2:
3607 break;
3608 default:
Austin Borgered99f642023-06-01 16:51:35 -07003609 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3610 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3611 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003612 }
3613
Austin Borger18b30a72022-10-27 12:20:29 -07003614 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003615 auto deviceVersionAndTransport =
3616 getDeviceVersion(cameraId,
3617 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3618 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003619 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003620 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3621 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3622 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003623 }
3624 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3625 int deviceVersion = deviceVersionAndTransport.first;
3626 switch (deviceVersion) {
3627 case CAMERA_DEVICE_API_VERSION_1_0:
3628 case CAMERA_DEVICE_API_VERSION_3_0:
3629 case CAMERA_DEVICE_API_VERSION_3_1:
3630 if (apiVersion == API_VERSION_2) {
3631 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003632 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003633 *isSupported = false;
3634 } else { // if (apiVersion == API_VERSION_1) {
3635 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003636 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003637 *isSupported = true;
3638 }
3639 break;
3640 case CAMERA_DEVICE_API_VERSION_3_2:
3641 case CAMERA_DEVICE_API_VERSION_3_3:
3642 case CAMERA_DEVICE_API_VERSION_3_4:
3643 case CAMERA_DEVICE_API_VERSION_3_5:
3644 case CAMERA_DEVICE_API_VERSION_3_6:
3645 case CAMERA_DEVICE_API_VERSION_3_7:
3646 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003647 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003648 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003649 break;
3650 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003651 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3652 deviceVersion, cameraId.c_str());
3653 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3654 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003655 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003656 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003657 } else {
3658 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003659 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003660 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003661}
3662
malikakash98260df2024-05-10 23:33:57 +00003663Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003664 /*out*/ bool *isSupported) {
3665 ATRACE_CALL();
3666
Austin Borgered99f642023-06-01 16:51:35 -07003667 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3668 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003669
3670 return Status::ok();
3671}
3672
Cliff Wud8cae102021-03-11 01:37:42 +08003673Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003674 const std::string& packageName, const std::string& internalCamId,
3675 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003676 const sp<ICameraInjectionCallback>& callback,
3677 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003678 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003679 ATRACE_CALL();
3680
Austin Borgered99f642023-06-01 16:51:35 -07003681 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003682 const int pid = getCallingPid();
3683 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003684 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3685 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003686 "Permission Denial: no permission to inject camera");
3687 }
3688
3689 // Do not allow any camera injection that injects or replaces a virtual camera.
3690 auto [deviceIdForInternalCamera, _] =
3691 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3692 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3693 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3694 "Cannot replace a virtual camera");
3695 }
3696 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3697 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3698 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3699 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3700 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003701 }
3702
3703 ALOGV(
3704 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3705 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003706 __FUNCTION__, packageName.c_str(),
3707 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003708
Cliff Wud3a05312021-04-26 23:07:31 +08003709 {
3710 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003711 mInjectionInternalCamId = internalCamId;
3712 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003713 mInjectionStatusListener->addListener(callback);
3714 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003715 status_t res = NO_ERROR;
3716 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3717 // If the client already exists, we can directly connect to the camera device through the
3718 // client's injectCamera(), otherwise we need to wait until the client is established
3719 // (execute connectHelper()) before injecting the camera to the camera device.
3720 if (clientDescriptor != nullptr) {
3721 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003722 sp<BasicClient> clientSp = clientDescriptor->getValue();
3723 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3724 if(res != OK) {
3725 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3726 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003727 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003728 }
3729 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003730 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003731 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3732 }
3733 } else {
3734 mInjectionInitPending = true;
3735 }
3736 }
Cliff Wud8cae102021-03-11 01:37:42 +08003737
Cliff Wud3a05312021-04-26 23:07:31 +08003738 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003739}
3740
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003741Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003742 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003743 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3744 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3745 return Status::ok();
3746}
3747
Ruben Brunkcc776712015-02-17 20:18:47 -08003748void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003749 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003750 for (auto& i : mActiveClientManager.getAll()) {
3751 auto clientSp = i->getValue();
3752 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003753 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003755 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003756 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003757 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003758}
3759
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003760bool CameraService::isOnlyClient(const BasicClient* client) {
3761 Mutex::Autolock lock(mServiceLock);
3762 bool ret = true;
3763 if (!flags::camera_multi_client()) {
3764 return ret;
3765 }
3766 if (client != nullptr) {
3767 std::string camId = client->mCameraIdStr;
3768 for (const auto& i : mActiveClientManager.getAll()) {
3769 auto clientSp = i->getValue();
3770 auto curCamId = i->getKey();
3771 if (!curCamId.compare(camId) && clientSp.get() != client) {
3772 return false;
3773 }
3774 }
3775 }
3776 return ret;
3777}
3778
Ruben Brunkcc776712015-02-17 20:18:47 -08003779bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003780 bool ret = false;
3781 {
3782 // Acquire mServiceLock and prevent other clients from connecting
3783 std::unique_ptr<AutoConditionLock> lock =
3784 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003785
Ruben Brunkcc776712015-02-17 20:18:47 -08003786 std::vector<sp<BasicClient>> evicted;
3787 for (auto& i : mActiveClientManager.getAll()) {
3788 auto clientSp = i->getValue();
3789 if (clientSp.get() == nullptr) {
3790 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3791 mActiveClientManager.remove(i);
3792 continue;
3793 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003794 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003795 mActiveClientManager.remove(i);
3796 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003797
Ruben Brunkcc776712015-02-17 20:18:47 -08003798 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003799 clientSp->notifyError(
3800 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003801 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003802 }
3803 }
3804
Ruben Brunkcc776712015-02-17 20:18:47 -08003805 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3806 // other clients from connecting in mServiceLockWrapper if held
3807 mServiceLock.unlock();
3808
Ruben Brunk36597b22015-03-20 22:15:57 -07003809 // Do not clear caller identity, remote caller should be client proccess
3810
Ruben Brunkcc776712015-02-17 20:18:47 -08003811 for (auto& i : evicted) {
3812 if (i.get() != nullptr) {
3813 i->disconnect();
3814 ret = true;
3815 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003816 }
3817
Ruben Brunkcc776712015-02-17 20:18:47 -08003818 // Reacquire mServiceLock
3819 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003820
Ruben Brunkcc776712015-02-17 20:18:47 -08003821 } // lock is destroyed, allow further connect calls
3822
3823 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003824}
3825
Ruben Brunkcc776712015-02-17 20:18:47 -08003826std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003827 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003828 std::shared_ptr<CameraState> state;
3829 {
3830 Mutex::Autolock lock(mCameraStatesLock);
3831 auto iter = mCameraStates.find(cameraId);
3832 if (iter != mCameraStates.end()) {
3833 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003834 }
3835 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003836 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003837}
3838
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003839std::vector<sp<CameraService::BasicClient>> CameraService::removeClientsLocked(
3840 const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003841 // Remove from active clients list
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003842 std::vector<sp<CameraService::BasicClient>> clients;
Jyoti Bhayana1a586fd2024-11-20 19:54:35 -08003843 if (flags::camera_multi_client()) {
3844 std::vector<CameraService::DescriptorPtr> clientDescriptors;
3845 clientDescriptors = mActiveClientManager.removeAll(cameraId);
3846 for (const auto& clientDescriptorPtr : clientDescriptors) {
3847 if (clientDescriptorPtr != nullptr) {
3848 sp<BasicClient> client = clientDescriptorPtr->getValue();
3849 if (client.get() != nullptr) {
3850 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3851 clients.push_back(client);
3852 }
3853 }
3854 }
3855 } else {
3856 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3857 if (clientDescriptorPtr == nullptr) {
3858 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3859 cameraId.c_str());
3860 return clients;
3861 }
3862
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003863 sp<BasicClient> client = clientDescriptorPtr->getValue();
3864 if (client.get() != nullptr) {
3865 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
Jyoti Bhayana1a586fd2024-11-20 19:54:35 -08003866 clients.push_back(client);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003867 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003868 }
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003869 return clients;
Keun young Parkd8973a72012-03-28 14:13:09 -07003870}
3871
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003872void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003873 // Acquire mServiceLock and prevent other clients from connecting
3874 std::unique_ptr<AutoConditionLock> lock =
3875 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3876
Ruben Brunk6267b532015-04-30 17:44:07 -07003877 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003878 for (size_t i = 0; i < newUserIds.size(); i++) {
3879 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003880 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003881 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003882 return;
3883 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003884 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003885 }
3886
Ruben Brunka8ca9152015-04-07 14:23:40 -07003887
Ruben Brunk6267b532015-04-30 17:44:07 -07003888 if (newAllowedUsers == mAllowedUsers) {
3889 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3890 return;
3891 }
3892
3893 logUserSwitch(mAllowedUsers, newAllowedUsers);
3894
3895 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003896
3897 // Current user has switched, evict all current clients.
3898 std::vector<sp<BasicClient>> evicted;
3899 for (auto& i : mActiveClientManager.getAll()) {
3900 auto clientSp = i->getValue();
3901
3902 if (clientSp.get() == nullptr) {
3903 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3904 continue;
3905 }
3906
Ruben Brunk6267b532015-04-30 17:44:07 -07003907 // Don't evict clients that are still allowed.
3908 uid_t clientUid = clientSp->getClientUid();
3909 userid_t clientUserId = multiuser_get_user_id(clientUid);
3910 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3911 continue;
3912 }
3913
Ruben Brunk36597b22015-03-20 22:15:57 -07003914 evicted.push_back(clientSp);
3915
Ruben Brunk36597b22015-03-20 22:15:57 -07003916 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003917 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003918
Ruben Brunk36597b22015-03-20 22:15:57 -07003919 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003920 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003921 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003922 " to user switch.", i->getKey().c_str(),
3923 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003924 i->getOwnerId(), i->getPriority().getScore(),
3925 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003926
3927 }
3928
3929 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3930 // blocking other clients from connecting in mServiceLockWrapper if held.
3931 mServiceLock.unlock();
3932
3933 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003934 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003935
3936 for (auto& i : evicted) {
3937 i->disconnect();
3938 }
3939
Austin Borger22c5c852024-03-08 13:31:36 -08003940 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003941
3942 // Reacquire mServiceLock
3943 mServiceLock.lock();
3944}
Ruben Brunkcc776712015-02-17 20:18:47 -08003945
Austin Borgered99f642023-06-01 16:51:35 -07003946void CameraService::logEvent(const std::string &event) {
3947 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003948 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003949 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003950 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003951 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003952 mEventLog.add(msg);
3953 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3954 // Error event not added to the dumpsys log before
3955 mEventLog.add(msg);
3956 sServiceErrorEventSet.insert(msg);
3957 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003958}
3959
Austin Borgered99f642023-06-01 16:51:35 -07003960void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3961 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003962 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003963 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3964 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003965}
3966
Austin Borgered99f642023-06-01 16:51:35 -07003967void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3968 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003969 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003970 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3971 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003972}
3973
Austin Borgered99f642023-06-01 16:51:35 -07003974void CameraService::logConnected(const std::string &cameraId, int clientPid,
3975 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003976 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003977 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3978 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003979}
3980
Austin Borgered99f642023-06-01 16:51:35 -07003981void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3982 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003983 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003984 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3985 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003986}
3987
Austin Borgered99f642023-06-01 16:51:35 -07003988void CameraService::logRejected(const std::string &cameraId, int clientPid,
3989 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003990 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003991 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3992 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003993}
3994
Austin Borgered99f642023-06-01 16:51:35 -07003995void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3996 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003997 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003998 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3999 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004000}
4001
Ruben Brunk6267b532015-04-30 17:44:07 -07004002void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4003 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004004 std::string newUsers = toString(newUserIds);
4005 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004006 if (oldUsers.size() == 0) {
4007 oldUsers = "<None>";
4008 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004009 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004010 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4011 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004012}
4013
Austin Borgered99f642023-06-01 16:51:35 -07004014void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004015 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004016 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004017}
4018
Austin Borgered99f642023-06-01 16:51:35 -07004019void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004020 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004021 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004022}
4023
Austin Borgered99f642023-06-01 16:51:35 -07004024void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004025 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004026 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004027}
4028
Austin Borgered99f642023-06-01 16:51:35 -07004029void CameraService::logServiceError(const std::string &msg, int errorCode) {
4030 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4031 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004032}
4033
Ruben Brunk36597b22015-03-20 22:15:57 -07004034status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4035 uint32_t flags) {
4036
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037 // Permission checks
4038 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004039 case SHELL_COMMAND_TRANSACTION: {
4040 int in = data.readFileDescriptor();
4041 int out = data.readFileDescriptor();
4042 int err = data.readFileDescriptor();
4043 int argc = data.readInt32();
4044 Vector<String16> args;
4045 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4046 args.add(data.readString16());
4047 }
4048 sp<IBinder> unusedCallback;
4049 sp<IResultReceiver> resultReceiver;
4050 status_t status;
4051 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4052 return status;
4053 }
4054 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4055 return status;
4056 }
4057 status = shellCommand(in, out, err, args);
4058 if (resultReceiver != nullptr) {
4059 resultReceiver->send(status);
4060 }
4061 return NO_ERROR;
4062 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004063 }
4064
4065 return BnCameraService::onTransact(code, data, reply, flags);
4066}
4067
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068// We share the media players for shutter and recording sound for all clients.
4069// A reference count is kept to determine when we will actually release the
4070// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004071sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4072 sp<MediaPlayer> mp = new MediaPlayer();
4073 status_t error;
4074 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004075 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004076 error = mp->prepare();
4077 }
4078 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004079 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004080 mp->disconnect();
4081 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004082 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004083 }
4084 return mp;
4085}
4086
username5755fea2018-12-27 09:48:08 +08004087void CameraService::increaseSoundRef() {
4088 Mutex::Autolock lock(mSoundLock);
4089 mSoundRef++;
4090}
4091
4092void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004093 ATRACE_CALL();
4094
username5755fea2018-12-27 09:48:08 +08004095 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4096 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4097 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4098 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4099 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4100 }
4101 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4102 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4103 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4104 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004105 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004106 }
4107 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4108 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4109 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4110 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4111 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004112 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004113}
4114
username5755fea2018-12-27 09:48:08 +08004115void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004116 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004117 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004118 if (--mSoundRef) return;
4119
4120 for (int i = 0; i < NUM_SOUNDS; i++) {
4121 if (mSoundPlayer[i] != 0) {
4122 mSoundPlayer[i]->disconnect();
4123 mSoundPlayer[i].clear();
4124 }
4125 }
4126}
4127
4128void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004129 ATRACE_CALL();
4130
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004132 if (kind < 0 || kind >= NUM_SOUNDS) {
4133 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4134 return;
4135 }
4136
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004138 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139 sp<MediaPlayer> player = mSoundPlayer[kind];
4140 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004141 player->seekTo(0);
4142 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143 }
4144}
4145
4146// ----------------------------------------------------------------------------
4147
Austin Borger2e772b82024-10-11 16:09:57 -07004148CameraService::Client::Client(
4149 const sp<CameraService>& cameraService, const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004150 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004151 const AttributionSourceState& clientAttribution, int callingPid, bool systemNativeClient,
4152 const std::string& cameraIdStr, int api1CameraId, int cameraFacing, int sensorOrientation,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004153 int servicePid, int rotationOverride, bool sharedMode)
Austin Borger2e772b82024-10-11 16:09:57 -07004154 : CameraService::BasicClient(cameraService, IInterface::asBinder(cameraClient),
4155 attributionAndPermissionUtils, clientAttribution, callingPid,
4156 systemNativeClient, cameraIdStr, cameraFacing, sensorOrientation,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004157 servicePid, rotationOverride, sharedMode),
Austin Borger2e772b82024-10-11 16:09:57 -07004158 mCameraId(api1CameraId) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004159 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004160
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004161 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004162
username5755fea2018-12-27 09:48:08 +08004163 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004164
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004165 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004166}
4167
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168// tear down the client
4169CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004170 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004171 mDestructionStarted = true;
4172
username5755fea2018-12-27 09:48:08 +08004173 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004174 // unconditionally disconnect. function is idempotent
4175 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004176}
4177
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004178sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4179
Austin Borger2e772b82024-10-11 16:09:57 -07004180CameraService::BasicClient::BasicClient(
4181 const sp<CameraService>& cameraService, const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004182 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004183 const AttributionSourceState& clientAttribution, int callingPid, bool nativeClient,
4184 const std::string& cameraIdStr, int cameraFacing, int sensorOrientation, int servicePid,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004185 int rotationOverride, bool sharedMode)
Austin Borger2e772b82024-10-11 16:09:57 -07004186 : AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
4187 mDestructionStarted(false),
4188 mCameraIdStr(cameraIdStr),
4189 mCameraFacing(cameraFacing),
4190 mOrientation(sensorOrientation),
4191 mClientAttribution(clientAttribution),
4192 mCallingPid(callingPid),
4193 mSystemNativeClient(nativeClient),
4194 mServicePid(servicePid),
4195 mDisconnected(false),
4196 mUidIsTrusted(false),
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004197 mRotationOverride(rotationOverride), mSharedMode(sharedMode),
Austin Borger2e772b82024-10-11 16:09:57 -07004198 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
4199 mRemoteBinder(remoteCallback),
Austin Borgera0c61f12024-10-11 13:38:35 -07004200 mCameraOpen(false),
4201 mCameraStreaming(false) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004202 if (sCameraService == nullptr) {
4203 sCameraService = cameraService;
4204 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004205
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004206 // There are 2 scenarios in which a client won't have AppOps operations
4207 // (both scenarios : native clients)
4208 // 1) It's an system native client*, the package name will be empty
4209 // and it will return from this function in the previous if condition
4210 // (This is the same as the previously existing behavior).
4211 // 2) It is a system native client, but its package name has been
4212 // modified for debugging, however it still must not use AppOps since
4213 // the package name is not a real one.
4214 //
4215 // * system native client - native client with UID < AID_APP_START. It
4216 // doesn't exclude clients not on the system partition.
4217 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004218 mAppOpsManager = std::make_unique<AppOpsManager>();
4219 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004220
Austin Borger32163932024-10-25 13:56:52 -07004221 mUidIsTrusted = isTrustedCallingUid(mClientAttribution.uid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004222}
4223
4224CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004225 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004226 mDestructionStarted = true;
4227}
4228
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004229binder::Status CameraService::BasicClient::disconnect() {
4230 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004231 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004232 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004233 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004234 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004235
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004236 sCameraService->removeByClient(this);
Austin Borger2e772b82024-10-11 16:09:57 -07004237 sCameraService->logDisconnected(mCameraIdStr, mCallingPid, getPackageName());
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004238 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode &&
4239 sCameraService->isOnlyClient(this))) {
4240 // Remove the HAL reference for the camera in either of the following scenarios :
4241 // 1) Camera was opened in non-shared mode.
4242 // 2) Camera was opened in shared mode and this is the last client using
4243 // the camera which is being disconnected
4244 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
4245 mCameraIdStr);
4246 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004247
4248 sp<IBinder> remote = getRemote();
4249 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004250 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004251 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004252
Austin Borgera0c61f12024-10-11 13:38:35 -07004253 notifyCameraClosing();
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004254 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode &&
4255 sCameraService->isOnlyClient(this))) {
4256 // Notify flashlight that a camera device is closed.
4257 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
4258 }
Austin Borgered99f642023-06-01 16:51:35 -07004259 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004260 mCallingPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004261
Igor Murashkincba2c162013-03-20 15:56:31 -07004262 // client shouldn't be able to call into us anymore
Austin Borger2e772b82024-10-11 16:09:57 -07004263 mCallingPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004264
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004265 const auto& mActivityManager = getActivityManager();
4266 if (mActivityManager) {
4267 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004268 getCallingUid(),
4269 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004270 }
4271
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004272 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004273}
4274
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004275status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4276 // No dumping of clients directly over Binder,
4277 // must go through CameraService::dump
4278 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004279 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004280 return OK;
4281}
4282
Austin Borgered99f642023-06-01 16:51:35 -07004283status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004284 // Can't watch tags directly, must go through CameraService::startWatchingTags
4285 return OK;
4286}
4287
4288status_t CameraService::BasicClient::stopWatchingTags(int) {
4289 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4290 return OK;
4291}
4292
4293status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4294 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4295 return OK;
4296}
4297
Austin Borgered99f642023-06-01 16:51:35 -07004298std::string CameraService::BasicClient::getPackageName() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004299 return mClientAttribution.packageName.value_or(kUnknownPackageName);
Ruben Brunkcc776712015-02-17 20:18:47 -08004300}
4301
Emilian Peev8b64f282021-03-25 16:49:57 -07004302int CameraService::BasicClient::getCameraFacing() const {
4303 return mCameraFacing;
4304}
4305
4306int CameraService::BasicClient::getCameraOrientation() const {
4307 return mOrientation;
4308}
Ruben Brunkcc776712015-02-17 20:18:47 -08004309
Austin Borger2e772b82024-10-11 16:09:57 -07004310int CameraService::BasicClient::getClientCallingPid() const {
4311 return mCallingPid;
Ruben Brunkcc776712015-02-17 20:18:47 -08004312}
4313
Ruben Brunk6267b532015-04-30 17:44:07 -07004314uid_t CameraService::BasicClient::getClientUid() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004315 return mClientAttribution.uid;
4316}
4317
4318const std::optional<std::string>& CameraService::BasicClient::getClientAttributionTag() const {
4319 return mClientAttribution.attributionTag;
Ruben Brunk6267b532015-04-30 17:44:07 -07004320}
4321
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004322bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4323 // Defaults to API2.
4324 return level == API_2;
4325}
4326
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004327status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004328 {
4329 Mutex::Autolock l(mAudioRestrictionLock);
4330 mAudioRestriction = mode;
4331 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004332 sCameraService->updateAudioRestriction();
4333 return OK;
4334}
4335
4336int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004337 return sCameraService->updateAudioRestriction();
4338}
4339
4340int32_t CameraService::BasicClient::getAudioRestriction() const {
4341 Mutex::Autolock l(mAudioRestrictionLock);
4342 return mAudioRestriction;
4343}
4344
4345bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4346 switch (mode) {
4347 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4348 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4349 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4350 return true;
4351 default:
4352 return false;
4353 }
4354}
4355
Austin Borgera0c61f12024-10-11 13:38:35 -07004356status_t CameraService::BasicClient::handlePermissionResult(
4357 PermissionChecker::PermissionResult result) {
4358 if (result == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004359 ALOGI("Camera %s: Access for \"%s\" has been revoked", mCameraIdStr.c_str(),
4360 getPackageName().c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004361 return PERMISSION_DENIED;
Austin Borgera0c61f12024-10-11 13:38:35 -07004362 } else if (!mUidIsTrusted && result == PermissionChecker::PERMISSION_SOFT_DENIED) {
4363 // If the calling Uid is trusted (a native service), the AppOpsManager/PermissionChecker
4364 // could return MODE_IGNORED/PERMISSION_SOFT_DENIED. Do not treat such case as error.
Austin Borger2e772b82024-10-11 16:09:57 -07004365 bool isUidActive =
4366 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004367
4368 bool isCameraPrivacyEnabled;
4369 if (flags::camera_privacy_allowlist()) {
4370 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004371 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004372 } else {
4373 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004374 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004375 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004376 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4377 // We prefer to successfully open the camera and perform camera muting
4378 // or blocking in connectHelper as handleAppOpMode can be called before the
4379 // connection has been fully established and at that time camera muting
4380 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004381 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004382 ALOGI("Camera %s: Access for \"%s\" has been restricted."
Austin Borger2e772b82024-10-11 16:09:57 -07004383 "uid active: %s, privacy enabled: %s",
4384 mCameraIdStr.c_str(), getPackageName().c_str(), isUidActive ? "true" : "false",
4385 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004386 // Return the same error as for device policy manager rejection
4387 return -EACCES;
4388 }
4389 }
4390 return OK;
4391}
4392
Austin Borgera0c61f12024-10-11 13:38:35 -07004393status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4394 return handlePermissionResult(appOpModeToPermissionResult(mode));
4395}
4396
4397status_t CameraService::BasicClient::notifyCameraOpening() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004398 ATRACE_CALL();
4399
Austin Borgera0c61f12024-10-11 13:38:35 -07004400 // Don't start watching until we're streaming when using permissionChecker for data delivery
Austin Borger2a3f9a72024-11-07 12:24:49 -08004401 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004402 ALOGD("%s: Start camera ops, package name = %s, client UID = %d", __FUNCTION__,
Austin Borger2e772b82024-10-11 16:09:57 -07004403 getPackageName().c_str(), getClientUid());
Austin Borgerca1e0062023-06-28 11:32:55 -07004404
Austin Borgera0c61f12024-10-11 13:38:35 -07004405 if (mAppOpsManager != nullptr) {
4406 // Notify app ops that the camera is not available
4407 mOpsCallback = new OpsCallback(this);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004408
Austin Borgera0c61f12024-10-11 13:38:35 -07004409 mAppOpsManager->startWatchingMode(
4410 AppOpsManager::OP_CAMERA, toString16(getPackageName()),
4411 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4412
4413 // Just check for camera access here on open - delay startOp until
4414 // camera frames start streaming in startCameraStreamingOps
4415 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4416 toString16(getPackageName()));
4417 status_t res = handleAppOpMode(mode);
4418 if (res != OK) {
4419 return res;
4420 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004421 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004422 } else {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004423 // TODO: Remove when removing the data_delivery_permission_checks flag
Austin Borgera0c61f12024-10-11 13:38:35 -07004424 ALOGD("%s: Bypassing checkOp for uid %d", __FUNCTION__, getClientUid());
Svetoslav28e8ef72015-05-11 19:21:31 -07004425 }
4426
Austin Borgera0c61f12024-10-11 13:38:35 -07004427 mCameraOpen = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004428
4429 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004430 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004431
Austin Borger2e772b82024-10-11 16:09:57 -07004432 sCameraService->mUidPolicy->registerMonitorUid(getClientUid(), /*openCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004433
Shuzhen Wang695044d2020-03-06 09:02:23 -08004434 // Notify listeners of camera open/close status
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004435 sCameraService->updateOpenCloseStatus(mCameraIdStr, true /*open*/, getPackageName(),
4436 mSharedMode);
Shuzhen Wang695044d2020-03-06 09:02:23 -08004437
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004438 return OK;
4439}
4440
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004441status_t CameraService::BasicClient::startCameraStreamingOps() {
4442 ATRACE_CALL();
4443
Austin Borgera0c61f12024-10-11 13:38:35 -07004444 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004445 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4446 return INVALID_OPERATION;
4447 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004448
4449 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004450 ALOGV("%s: Streaming already active!", __FUNCTION__);
4451 return OK;
4452 }
4453
Austin Borger2e772b82024-10-11 16:09:57 -07004454 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d", __FUNCTION__,
4455 getPackageName().c_str(), getClientUid());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004456
4457 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004458 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004459 ALOGD("%s: Start data delivery for uid %d", __FUNCTION__, getClientUid());
4460
4461 const PermissionChecker::PermissionResult result =
4462 checkPermissionsForCameraForStartDataDelivery(mCameraIdStr, mClientAttribution);
4463 status_t res = handlePermissionResult(result);
4464 if (res != OK) {
4465 return res;
4466 }
4467
4468 mOpsCallback = new OpsCallback(this);
4469 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4470 [&](const auto& attr) {
4471 mAppOpsManager->startWatchingMode(
4472 AppOpsManager::OP_CAMERA,
4473 toString16(attr.packageName.value_or("")),
4474 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4475 });
4476 } else {
4477 ALOGD("%s: startOp for uid %d", __FUNCTION__, getClientUid());
4478 int32_t mode = mAppOpsManager->startOpNoThrow(
4479 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4480 /*startIfModeDefault*/ false, toString16(getClientAttributionTag()),
4481 toString16("start camera ") + toString16(mCameraIdStr));
4482 status_t res = handleAppOpMode(mode);
4483 if (res != OK) {
4484 return res;
4485 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004486 }
4487 }
4488
Austin Borgera0c61f12024-10-11 13:38:35 -07004489 mCameraStreaming = true;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004490
4491 return OK;
4492}
4493
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004494status_t CameraService::BasicClient::noteAppOp() {
4495 ATRACE_CALL();
4496
Austin Borger2e772b82024-10-11 16:09:57 -07004497 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d", __FUNCTION__,
4498 getPackageName().c_str(), getClientUid());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004499
4500 // noteAppOp is only used for when camera mute is not supported, in order
4501 // to trigger the sensor privacy "Unblock" dialog
Austin Borger2a3f9a72024-11-07 12:24:49 -08004502 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004503 // Ignore the result, since we're only triggering the dialog
4504 ALOGD("%s: Check data delivery permissions for uid %d", __FUNCTION__, getClientUid());
4505 hasPermissionsForCameraForDataDelivery(std::string(), mClientAttribution);
4506 } else if (mAppOpsManager != nullptr) {
4507 ALOGD("%s: noteOp for uid %d", __FUNCTION__, getClientUid());
Austin Borger2e772b82024-10-11 16:09:57 -07004508 int32_t mode = mAppOpsManager->noteOp(
4509 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4510 toString16(getClientAttributionTag()),
Austin Borgered99f642023-06-01 16:51:35 -07004511 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004512 status_t res = handleAppOpMode(mode);
4513 if (res != OK) {
4514 return res;
4515 }
4516 }
4517
4518 return OK;
4519}
4520
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004521status_t CameraService::BasicClient::finishCameraStreamingOps() {
4522 ATRACE_CALL();
4523
Austin Borgera0c61f12024-10-11 13:38:35 -07004524 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004525 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4526 return INVALID_OPERATION;
4527 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004528 if (!mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004529 ALOGV("%s: Streaming not active!", __FUNCTION__);
4530 return OK;
4531 }
4532
4533 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004534 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004535 ALOGD("%s: finishDataDelivery for uid %d", __FUNCTION__, getClientUid());
4536 finishDataDelivery(mClientAttribution);
4537
4538 // Stop watching app op changes after stop streaming
4539 if (mOpsCallback != nullptr) {
4540 mAppOpsManager->stopWatchingMode(mOpsCallback);
4541 mOpsCallback.clear();
4542 }
4543 } else {
4544 ALOGD("%s: finishOp for uid %d", __FUNCTION__, getClientUid());
4545 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, getClientUid(),
4546 toString16(getPackageName()),
4547 toString16(getClientAttributionTag()));
4548 }
4549 mCameraStreaming = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004550 }
4551
4552 return OK;
4553}
4554
Austin Borgera0c61f12024-10-11 13:38:35 -07004555status_t CameraService::BasicClient::notifyCameraClosing() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004556 ATRACE_CALL();
4557
Austin Borgera0c61f12024-10-11 13:38:35 -07004558 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004559 // Make sure we've notified everyone about camera stopping
4560 finishCameraStreamingOps();
4561 }
4562
Austin Borgera0c61f12024-10-11 13:38:35 -07004563 // Check if notifyCameraOpening succeeded, and if so, finish the camera op if necessary
4564 if (mCameraOpen) {
4565 mCameraOpen = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004566
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004567 // This function is called when a client disconnects. This should
4568 // release the camera, but actually only if it was in a proper
4569 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004570 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004571 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004572
Ruben Brunkcc776712015-02-17 20:18:47 -08004573 // Transition to PRESENT if the camera is not in either of the rejected states
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004574 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode
4575 && sCameraService->isOnlyClient(this))) {
4576 sCameraService->updateStatus(StatusInternal::PRESENT,
4577 mCameraIdStr, rejected);
4578 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004579 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004580
4581 // When using the data delivery permission checks, the open state does not involve AppOps
Austin Borger2a3f9a72024-11-07 12:24:49 -08004582 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004583 // Always stop watching, even if no camera op is active
4584 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4585 mAppOpsManager->stopWatchingMode(mOpsCallback);
4586 }
4587 mOpsCallback.clear();
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004588 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004589
Austin Borger2e772b82024-10-11 16:09:57 -07004590 sCameraService->mUidPolicy->unregisterMonitorUid(getClientUid(), /*closeCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004591
Shuzhen Wang695044d2020-03-06 09:02:23 -08004592 // Notify listeners of camera open/close status
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004593 sCameraService->updateOpenCloseStatus(mCameraIdStr, false /*open*/, getPackageName(),
4594 mSharedMode);
Shuzhen Wang695044d2020-03-06 09:02:23 -08004595
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004596 return OK;
4597}
4598
Austin Borgerf2da9c72024-11-12 13:45:28 -08004599int32_t CameraService::getUidProcessState(int32_t uid) {
4600 const auto& activityManager = getActivityManager();
4601 int32_t procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
4602 if (activityManager != nullptr) {
4603 procState = activityManager->getUidProcessState(uid, toString16(kServiceName));
4604 } else {
4605 ALOGE("%s: getActivityManager returned nullptr.", __FUNCTION__);
4606 }
4607 return procState;
4608}
4609
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004610void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004611 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004612 if (mAppOpsManager == nullptr) {
4613 return;
4614 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004615 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004616 if (op != AppOpsManager::OP_CAMERA) {
4617 ALOGW("Unexpected app ops notification received: %d", op);
4618 return;
4619 }
4620
Austin Borgera0c61f12024-10-11 13:38:35 -07004621 PermissionChecker::PermissionResult res;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004622 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004623 int32_t appOpMode = AppOpsManager::MODE_ALLOWED;
4624 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4625 [&](const auto& attr) {
4626 appOpMode = std::max(appOpMode, mAppOpsManager->checkOp(
4627 AppOpsManager::OP_CAMERA, attr.uid,
4628 toString16(attr.packageName.value_or(""))));
4629 });
4630 ALOGV("checkOp returns: %d, %s ", res,
4631 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4632 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4633 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4634 : "UNKNOWN");
4635 res = appOpModeToPermissionResult(appOpMode);
4636 } else {
4637 int32_t appOpMode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4638 toString16(getPackageName()));
4639 ALOGV("checkOp returns: %d, %s ", res,
4640 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4641 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4642 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4643 : "UNKNOWN");
4644 res = appOpModeToPermissionResult(appOpMode);
4645 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004646
Austin Borgera0c61f12024-10-11 13:38:35 -07004647 if (res == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borgered99f642023-06-01 16:51:35 -07004648 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004649 getPackageName().c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004650 block();
Austin Borgera0c61f12024-10-11 13:38:35 -07004651 } else if (res == PermissionChecker::PERMISSION_SOFT_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004652 bool isUidActive =
4653 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004654
Austin Borgerca1e0062023-06-28 11:32:55 -07004655 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4656 // If not visible, but still active, then we want to block instead of muting the camera.
Austin Borgera0c61f12024-10-11 13:38:35 -07004657 int32_t procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004658 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004659 // Use the proc state of the last uid in the chain (ultimately receiving the data)
4660 // when determining whether to mute or block
4661 int32_t uid = -1;
4662 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4663 [&](const auto& attr) {
4664 uid = static_cast<uid_t>(attr.uid);
4665 });
Austin Borgerf2da9c72024-11-12 13:45:28 -08004666 procState = getUidProcessState(uid);
4667 } else if (flags::query_process_state()) {
4668 procState = getUidProcessState(getClientUid());
Austin Borgera0c61f12024-10-11 13:38:35 -07004669 } else {
4670 procState = sCameraService->mUidPolicy->getProcState(getClientUid());
4671 }
Austin Borgerca1e0062023-06-28 11:32:55 -07004672 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4673
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004674 bool isCameraPrivacyEnabled;
4675 if (flags::camera_privacy_allowlist()) {
4676 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004677 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004678 } else {
4679 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004680 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004681 }
4682
4683 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgera0c61f12024-10-11 13:38:35 -07004684 " isUidVisible %d, isCameraPrivacyEnabled %d procState %d",
Austin Borger2e772b82024-10-11 16:09:57 -07004685 mCameraIdStr.c_str(), getPackageName().c_str(), mUidIsTrusted, isUidActive,
Austin Borgera0c61f12024-10-11 13:38:35 -07004686 isUidVisible, isCameraPrivacyEnabled, procState);
Austin Borgerca1e0062023-06-28 11:32:55 -07004687 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4688 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4689 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004690 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004691 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4692 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004693 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004694 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004695 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004696 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004697 } else if (res == PermissionChecker::PERMISSION_GRANTED) {
Evan Severson09ab4002021-02-10 14:15:19 -08004698 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004699 }
4700}
4701
Svet Ganova453d0d2018-01-11 15:37:58 -08004702void CameraService::BasicClient::block() {
4703 ATRACE_CALL();
4704
4705 // Reset the client PID to allow server-initiated disconnect,
4706 // and to prevent further calls by client.
Austin Borger2e772b82024-10-11 16:09:57 -07004707 mCallingPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004708 CaptureResultExtras resultExtras; // a dummy result (invalid)
4709 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4710 disconnect();
4711}
4712
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004713status_t CameraService::BasicClient::isPrimaryClient(bool* isPrimary) {
4714 ATRACE_CALL();
4715 if (!flags::camera_multi_client()) {
4716 return INVALID_OPERATION;
4717 }
4718
4719 if (!mSharedMode) {
4720 ALOGW("%s: Invalid operation when camera is not opened in shared mode", __FUNCTION__);
4721 return INVALID_OPERATION;
4722 }
4723 *isPrimary = mIsPrimaryClient;
4724 return OK;
4725}
4726
4727status_t CameraService::BasicClient::setPrimaryClient(bool isPrimary) {
4728 ATRACE_CALL();
4729
4730 if (!flags::camera_multi_client()) {
4731 return INVALID_OPERATION;
4732 }
4733
4734 if (!mSharedMode) {
4735 ALOGW("%s:Invalid operation when camera is not opened in shared mode", __FUNCTION__);
4736 return INVALID_OPERATION;
4737 }
4738 mIsPrimaryClient = isPrimary;
4739 return OK;
4740}
4741
Mathias Agopian65ab4712010-07-14 17:59:35 -07004742// ----------------------------------------------------------------------------
4743
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004744void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004745 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004746 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004747 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4748 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4749 api1ErrorCode = CAMERA_ERROR_DISABLED;
4750 }
4751 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004752 } else {
4753 ALOGE("mRemoteCallback is NULL!!");
4754 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004755}
4756
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004757// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004758binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004759 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004760 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004761}
4762
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004763bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4764 return level == API_1;
4765}
4766
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004767CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4768 mClient(client) {
4769}
4770
4771void CameraService::Client::OpsCallback::opChanged(int32_t op,
4772 const String16& packageName) {
4773 sp<BasicClient> client = mClient.promote();
4774 if (client != NULL) {
4775 client->opChanged(op, packageName);
4776 }
4777}
4778
Mathias Agopian65ab4712010-07-14 17:59:35 -07004779// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004780// UidPolicy
4781// ----------------------------------------------------------------------------
4782
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004783void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004784 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004785 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004786
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004787 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004788 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004789 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004790 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004791 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4792 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004793 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004794 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004795 if (res == OK) {
4796 mRegistered = true;
4797 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004798 } else {
4799 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004800 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004801}
4802
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004803void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004804 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004805 return;
4806 }
4807
4808 registerWithActivityManager();
4809}
4810
4811void CameraService::UidPolicy::registerSelf() {
4812 // Use check service to see if the activity service is available
4813 // If not available then register for notifications, instead of blocking
4814 // till the service is ready
4815 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004816 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004817 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004818 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004819 } else {
4820 registerWithActivityManager();
4821 }
4822}
4823
Svet Ganova453d0d2018-01-11 15:37:58 -08004824void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004825 Mutex::Autolock _l(mUidLock);
4826
Steven Moreland2f348142019-07-02 15:59:07 -07004827 mAm.unregisterUidObserver(this);
4828 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004829 mRegistered = false;
4830 mActiveUids.clear();
4831 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004832}
4833
4834void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4835 onUidIdle(uid, disabled);
4836}
4837
4838void CameraService::UidPolicy::onUidActive(uid_t uid) {
4839 Mutex::Autolock _l(mUidLock);
4840 mActiveUids.insert(uid);
4841}
4842
4843void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4844 bool deleted = false;
4845 {
4846 Mutex::Autolock _l(mUidLock);
4847 if (mActiveUids.erase(uid) > 0) {
4848 deleted = true;
4849 }
4850 }
4851 if (deleted) {
4852 sp<CameraService> service = mService.promote();
4853 if (service != nullptr) {
4854 service->blockClientsForUid(uid);
4855 }
4856 }
4857}
4858
Emilian Peev53722fa2019-02-22 17:47:20 -08004859void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004860 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004861 bool procStateChange = false;
4862 {
4863 Mutex::Autolock _l(mUidLock);
4864 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4865 mMonitoredUids[uid].procState != procState) {
4866 mMonitoredUids[uid].procState = procState;
4867 procStateChange = true;
4868 }
4869 }
4870
4871 if (procStateChange) {
4872 sp<CameraService> service = mService.promote();
4873 if (service != nullptr) {
4874 service->notifyMonitoredUids();
4875 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004876 }
4877}
4878
Austin Borgerdddb7552023-03-30 17:53:01 -07004879/**
4880 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4881 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4882 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4883 * monitoredUids. If it is revised above some other monitoredUid, signal
4884 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4885 * foreground apps in split screen - state changes will capture all other cases.
4886 */
4887void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4888 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004889 {
4890 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004891 auto it = mMonitoredUids.find(uid);
4892
4893 if (it != mMonitoredUids.end()) {
4894 if (it->second.hasCamera) {
4895 for (auto &monitoredUid : mMonitoredUids) {
4896 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004897 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004898 notifyUidSet.emplace(monitoredUid.first);
4899 }
4900 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004901 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004902 notifyUidSet.emplace(uid);
4903 } else {
4904 for (auto &monitoredUid : mMonitoredUids) {
4905 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004906 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004907 notifyUidSet.emplace(uid);
4908 }
4909 }
4910 }
4911 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004912 }
4913 }
4914
Austin Borgerdddb7552023-03-30 17:53:01 -07004915 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004916 sp<CameraService> service = mService.promote();
4917 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004918 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004919 }
4920 }
4921}
4922
Austin Borgerdddb7552023-03-30 17:53:01 -07004923/**
4924 * Register a uid for monitoring, and note whether it owns a camera.
4925 */
4926void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004927 Mutex::Autolock _l(mUidLock);
4928 auto it = mMonitoredUids.find(uid);
4929 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004930 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004931 } else {
Austin Borger65577682022-02-17 00:25:43 +00004932 MonitoredUid monitoredUid;
4933 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004934 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004935 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004936 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004937 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004938 if (res != OK) {
4939 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4940 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004941 }
4942
4943 if (openCamera) {
4944 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004945 }
4946}
4947
Austin Borgerdddb7552023-03-30 17:53:01 -07004948/**
4949 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4950 */
4951void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004952 Mutex::Autolock _l(mUidLock);
4953 auto it = mMonitoredUids.find(uid);
4954 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004955 it->second.refCount--;
4956 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004957 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004958 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004959 if (res != OK) {
4960 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4961 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004962 } else if (closeCamera) {
4963 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004964 }
4965 } else {
4966 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4967 }
4968}
4969
Austin Borgered99f642023-06-01 16:51:35 -07004970bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004971 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004972 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004973}
4974
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004975static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4976static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004977
Austin Borgered99f642023-06-01 16:51:35 -07004978bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004979 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004980 // If activity manager is unreachable, assume everything is active
4981 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004982 return true;
4983 }
4984 auto it = mOverrideUids.find(uid);
4985 if (it != mOverrideUids.end()) {
4986 return it->second;
4987 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004988 bool active = mActiveUids.find(uid) != mActiveUids.end();
4989 if (!active) {
4990 // We want active UIDs to always access camera with their first attempt since
4991 // there is no guarantee the app is robustly written and would retry getting
4992 // the camera on failure. The inverse case is not a problem as we would take
4993 // camera away soon once we get the callback that the uid is no longer active.
4994 ActivityManager am;
4995 // Okay to access with a lock held as UID changes are dispatched without
4996 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004997 int64_t startTimeMillis = 0;
4998 do {
4999 // TODO: Fix this b/109950150!
5000 // Okay this is a hack. There is a race between the UID turning active and
5001 // activity being resumed. The proper fix is very risky, so we temporary add
5002 // some polling which should happen pretty rarely anyway as the race is hard
5003 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005004 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07005005 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07005006 if (active) {
5007 break;
5008 }
5009 if (startTimeMillis <= 0) {
5010 startTimeMillis = uptimeMillis();
5011 }
5012 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005013 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07005014 if (remainingTimeMillis <= 0) {
5015 break;
5016 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005017 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
5018
5019 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07005020 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07005021 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07005022 } while (true);
5023
Svet Ganov7b4ab782018-03-25 12:48:10 -07005024 if (active) {
5025 // Now that we found out the UID is actually active, cache that
5026 mActiveUids.insert(uid);
5027 }
5028 }
5029 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08005030}
5031
Varun Shahb42f1eb2019-04-16 14:45:13 -07005032int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
5033 Mutex::Autolock _l(mUidLock);
5034 return getProcStateLocked(uid);
5035}
5036
5037int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
5038 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
5039 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00005040 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07005041 }
5042 return procState;
5043}
5044
Austin Borgered99f642023-06-01 16:51:35 -07005045void CameraService::UidPolicy::addOverrideUid(uid_t uid,
5046 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005047 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08005048}
5049
Austin Borgered99f642023-06-01 16:51:35 -07005050void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005051 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005052}
5053
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005054void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5055 Mutex::Autolock _l(mUidLock);
5056 ALOGV("UidPolicy: ActivityManager has died");
5057 mRegistered = false;
5058 mActiveUids.clear();
5059}
5060
Austin Borgered99f642023-06-01 16:51:35 -07005061void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005062 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005063 bool wasActive = false;
5064 bool isActive = false;
5065 {
5066 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005067 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005068 mOverrideUids.erase(uid);
5069 if (insert) {
5070 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5071 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005072 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005073 }
5074 if (wasActive != isActive && !isActive) {
5075 sp<CameraService> service = mService.promote();
5076 if (service != nullptr) {
5077 service->blockClientsForUid(uid);
5078 }
5079 }
5080}
5081
5082// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005083// SensorPrivacyPolicy
5084// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005085
5086void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5087{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005088 Mutex::Autolock _l(mSensorPrivacyLock);
5089 if (mRegistered) {
5090 return;
5091 }
Evan Severson09ab4002021-02-10 14:15:19 -08005092 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005093 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005094 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005095 mSpm.addToggleSensorPrivacyListener(this);
5096 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005097 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005098 if (flags::camera_privacy_allowlist()) {
5099 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5100 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5101 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5102 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005103 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005104 if (res == OK) {
5105 mRegistered = true;
5106 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5107 }
5108}
5109
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005110void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5111 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005112 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005113 return;
5114 }
5115
5116 registerWithSensorPrivacyManager();
5117}
5118
5119void CameraService::SensorPrivacyPolicy::registerSelf() {
5120 // Use checkservice to see if the sensor_privacy service is available
5121 // If service is not available then register for notification
5122 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005123 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005124 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005125 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005126 } else {
5127 registerWithSensorPrivacyManager();
5128 }
5129}
5130
Michael Grooverd1d435a2018-12-18 17:39:42 -08005131void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5132 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005133 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005134 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005135 mSpm.removeToggleSensorPrivacyListener(this);
5136 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005137 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005138 mRegistered = false;
5139 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5140}
5141
5142bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005143 if (!mRegistered) {
5144 registerWithSensorPrivacyManager();
5145 }
5146
Michael Grooverd1d435a2018-12-18 17:39:42 -08005147 Mutex::Autolock _l(mSensorPrivacyLock);
5148 return mSensorPrivacyEnabled;
5149}
5150
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005151int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5152 if (!mRegistered) {
5153 registerWithSensorPrivacyManager();
5154 }
5155
5156 Mutex::Autolock _l(mSensorPrivacyLock);
5157 return mCameraPrivacyState;
5158}
5159
Evan Seversond0b69922022-01-27 10:47:34 -08005160bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005161 if (!hasCameraPrivacyFeature()) {
5162 return false;
5163 }
Evan Seversond0b69922022-01-27 10:47:34 -08005164 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005165}
5166
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005167bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5168 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07005169 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005170 }
5171 return mSpm.isCameraPrivacyEnabled(packageName);
5172}
5173
Evan Seversond0b69922022-01-27 10:47:34 -08005174binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005175 int toggleType, int sensor, bool enabled) {
5176 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5177 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5178 {
5179 Mutex::Autolock _l(mSensorPrivacyLock);
5180 mSensorPrivacyEnabled = enabled;
5181 }
5182 // if sensor privacy is enabled then block all clients from accessing the camera
5183 if (enabled) {
5184 sp<CameraService> service = mService.promote();
5185 if (service != nullptr) {
5186 service->blockAllClients();
5187 }
5188 }
5189 }
5190 return binder::Status::ok();
5191}
5192
5193binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5194 int, int sensor, int state) {
5195 if (!flags::camera_privacy_allowlist()
5196 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5197 return binder::Status::ok();
5198 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005199 {
5200 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005201 mCameraPrivacyState = state;
5202 }
5203 sp<CameraService> service = mService.promote();
5204 if (!service) {
5205 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005206 }
5207 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005208 if (state == SensorPrivacyManager::ENABLED) {
5209 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005210 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005211 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005212 }
5213 return binder::Status::ok();
5214}
5215
5216void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5217 Mutex::Autolock _l(mSensorPrivacyLock);
5218 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5219 mRegistered = false;
5220}
5221
Evan Severson09ab4002021-02-10 14:15:19 -08005222bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005223 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5224 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5225 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5226 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5227 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005228}
5229
Michael Grooverd1d435a2018-12-18 17:39:42 -08005230// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005231// CameraState
5232// ----------------------------------------------------------------------------
5233
Austin Borgered99f642023-06-01 16:51:35 -07005234CameraService::CameraState::CameraState(const std::string& id, int cost,
5235 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005236 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005237 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005238 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005239
5240CameraService::CameraState::~CameraState() {}
5241
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005242CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005243 Mutex::Autolock lock(mStatusLock);
5244 return mStatus;
5245}
5246
Austin Borgered99f642023-06-01 16:51:35 -07005247std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005248 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005249 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005250 return res;
5251}
5252
Ruben Brunkcc776712015-02-17 20:18:47 -08005253CameraParameters CameraService::CameraState::getShimParams() const {
5254 return mShimParams;
5255}
5256
5257void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5258 mShimParams = params;
5259}
5260
5261int CameraService::CameraState::getCost() const {
5262 return mCost;
5263}
5264
Austin Borgered99f642023-06-01 16:51:35 -07005265std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005266 return mConflicting;
5267}
5268
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005269SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5270 return mSystemCameraKind;
5271}
5272
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005273bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5274 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5275 != mPhysicalCameras.end();
5276}
5277
Austin Borgered99f642023-06-01 16:51:35 -07005278bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005279 Mutex::Autolock lock(mStatusLock);
5280 auto result = mUnavailablePhysicalIds.insert(physicalId);
5281 return result.second;
5282}
5283
Austin Borgered99f642023-06-01 16:51:35 -07005284bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005285 Mutex::Autolock lock(mStatusLock);
5286 auto count = mUnavailablePhysicalIds.erase(physicalId);
5287 return count > 0;
5288}
5289
Austin Borgered99f642023-06-01 16:51:35 -07005290void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005291 Mutex::Autolock lock(mStatusLock);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005292 mClientPackages.clear();
5293 mClientPackages.insert(clientPackage);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005294}
5295
Austin Borgered99f642023-06-01 16:51:35 -07005296std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005297 Mutex::Autolock lock(mStatusLock);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005298 if (!mClientPackages.empty()) {
5299 std::set<std::string>::iterator it = mClientPackages.begin();
5300 return *it;
5301 }
5302 return std::string();
5303}
5304
5305void CameraService::CameraState::addClientPackage(const std::string& clientPackage) {
5306 Mutex::Autolock lock(mStatusLock);
5307 mClientPackages.insert(clientPackage);
5308}
5309
5310void CameraService::CameraState::removeClientPackage(const std::string& clientPackage) {
5311 Mutex::Autolock lock(mStatusLock);
5312 mClientPackages.erase(clientPackage);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005313}
5314
Ruben Brunkcc776712015-02-17 20:18:47 -08005315// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005316// ClientEventListener
5317// ----------------------------------------------------------------------------
5318
5319void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005320 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005321 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005322 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005323 if (basicClient.get() != nullptr) {
5324 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005325 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005326 static_cast<int>(basicClient->getClientUid()));
5327 }
5328}
5329
5330void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005331 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005332 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005333 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005334 if (basicClient.get() != nullptr) {
5335 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005336 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005337 static_cast<int>(basicClient->getClientUid()));
5338 }
5339}
5340
Ruben Brunk99e69712015-05-26 17:25:07 -07005341// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005342// CameraClientManager
5343// ----------------------------------------------------------------------------
5344
Ruben Brunk99e69712015-05-26 17:25:07 -07005345CameraService::CameraClientManager::CameraClientManager() {
5346 setListener(std::make_shared<ClientEventListener>());
5347}
5348
Ruben Brunkcc776712015-02-17 20:18:47 -08005349CameraService::CameraClientManager::~CameraClientManager() {}
5350
5351sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005352 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005353 auto descriptor = get(id);
5354 if (descriptor == nullptr) {
5355 return sp<BasicClient>{nullptr};
5356 }
5357 return descriptor->getValue();
5358}
5359
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005360void CameraService::CameraClientManager::remove(const CameraService::DescriptorPtr& value) {
5361 ClientManager::remove(value);
5362 if (!flags::camera_multi_client()) {
5363 return;
5364 }
5365 auto clientToRemove = value->getValue();
5366 if ((clientToRemove.get() != nullptr) && clientToRemove->mSharedMode) {
5367 bool primaryClient = false;
5368 status_t ret = clientToRemove->isPrimaryClient(&primaryClient);
5369 if ((ret == OK) && primaryClient) {
5370 // Primary client is being removed. Find the next higher priority
5371 // client to become primary client.
5372 auto clientDescriptor = get(value->getKey());
5373 if (clientDescriptor == nullptr) {
5374 ALOGV("CameraService::CameraClientManager::no other clients are using same camera");
5375 return;
5376 }
5377 resource_policy::ClientPriority highestPriority = clientDescriptor->getPriority();
5378 sp<BasicClient> highestPriorityClient = clientDescriptor->getValue();
5379 if (highestPriorityClient.get() != nullptr) {
5380 for (auto& i : getAll()) {
5381 if ((i->getKey() == value->getKey()) && (i->getPriority() < highestPriority)) {
5382 highestPriority = i->getPriority();
5383 highestPriorityClient = i->getValue();
5384 }
5385 }
5386 highestPriorityClient->setPrimaryClient(true);
5387 highestPriorityClient->notifyClientSharedAccessPriorityChanged(true);
5388 }
5389 }
5390 }
5391}
5392
Austin Borgered99f642023-06-01 16:51:35 -07005393std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005394 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005395 std::ostringstream ret;
5396 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005397 bool hasAny = false;
5398 for (auto& i : all) {
5399 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005400 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005401 int32_t cost = i->getCost();
5402 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005403 int32_t score = i->getPriority().getScore();
5404 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005405 auto conflicting = i->getConflicting();
5406 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005407 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005408 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005409 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005410 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005411 uid_t clientUid = clientSp->getClientUid();
5412 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005413 }
Austin Borgered99f642023-06-01 16:51:35 -07005414 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5415 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005416
Ruben Brunk6267b532015-04-30 17:44:07 -07005417 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005418 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005419 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005420 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005421 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005422 }
5423
Austin Borgered99f642023-06-01 16:51:35 -07005424 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005425 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005426 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005427 }
Austin Borgered99f642023-06-01 16:51:35 -07005428 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005429 }
Austin Borgered99f642023-06-01 16:51:35 -07005430 if (hasAny) ret << "\n";
5431 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005432 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005433}
5434
5435CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005436 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5437 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005438 int32_t state, int32_t oomScoreOffset, bool systemNativeClient, bool sharedMode) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005439
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005440 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005441 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005442
Austin Borgered99f642023-06-01 16:51:35 -07005443 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005444 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005445 systemNativeClient, oomScoreOffset, sharedMode);
Ruben Brunkcc776712015-02-17 20:18:47 -08005446}
5447
5448CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005449 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005450 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005451 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005452 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005453 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005454 systemNativeClient, partial->getSharedMode());
Ruben Brunkcc776712015-02-17 20:18:47 -08005455}
5456
5457// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005458// InjectionStatusListener
5459// ----------------------------------------------------------------------------
5460
5461void CameraService::InjectionStatusListener::addListener(
5462 const sp<ICameraInjectionCallback>& callback) {
5463 Mutex::Autolock lock(mListenerLock);
5464 if (mCameraInjectionCallback) return;
5465 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5466 if (res == OK) {
5467 mCameraInjectionCallback = callback;
5468 }
5469}
5470
5471void CameraService::InjectionStatusListener::removeListener() {
5472 Mutex::Autolock lock(mListenerLock);
5473 if (mCameraInjectionCallback == nullptr) {
5474 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5475 return;
5476 }
5477 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5478 mCameraInjectionCallback = nullptr;
5479}
5480
5481void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005482 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005483 if (mCameraInjectionCallback == nullptr) {
5484 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5485 return;
5486 }
Cliff Wud3a05312021-04-26 23:07:31 +08005487
5488 switch (err) {
5489 case -ENODEV:
5490 mCameraInjectionCallback->onInjectionError(
5491 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5492 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005493 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005494 break;
5495 case -EBUSY:
5496 mCameraInjectionCallback->onInjectionError(
5497 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5498 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005499 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005500 break;
5501 case DEAD_OBJECT:
5502 mCameraInjectionCallback->onInjectionError(
5503 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5504 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005505 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005506 break;
5507 case INVALID_OPERATION:
5508 mCameraInjectionCallback->onInjectionError(
5509 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5510 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005511 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005512 break;
5513 case UNKNOWN_TRANSACTION:
5514 mCameraInjectionCallback->onInjectionError(
5515 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5516 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005517 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005518 break;
5519 default:
5520 mCameraInjectionCallback->onInjectionError(
5521 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5522 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005523 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005524 }
Cliff Wud8cae102021-03-11 01:37:42 +08005525}
5526
5527void CameraService::InjectionStatusListener::binderDied(
5528 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005529 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5530 auto parent = mParent.promote();
5531 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005532 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5533 if (clientDescriptor != nullptr) {
5534 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5535 baseClientPtr->stopInjection();
5536 }
Cliff Wu3b268182021-07-06 15:44:43 +08005537 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005538 }
5539}
5540
5541// ----------------------------------------------------------------------------
5542// CameraInjectionSession
5543// ----------------------------------------------------------------------------
5544
5545binder::Status CameraService::CameraInjectionSession::stopInjection() {
5546 Mutex::Autolock lock(mInjectionSessionLock);
5547 auto parent = mParent.promote();
5548 if (parent == nullptr) {
5549 ALOGE("CameraInjectionSession: Parent is gone");
5550 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5551 "Camera service encountered error");
5552 }
Cliff Wud3a05312021-04-26 23:07:31 +08005553
5554 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005555 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5556 if (clientDescriptor != nullptr) {
5557 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5558 res = baseClientPtr->stopInjection();
5559 if (res != OK) {
5560 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5561 " ret != NO_ERROR: %d", res);
5562 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5563 "Camera session encountered error");
5564 }
5565 }
Cliff Wu3b268182021-07-06 15:44:43 +08005566 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005567 return binder::Status::ok();
5568}
5569
5570// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005571
5572static const int kDumpLockRetries = 50;
5573static const int kDumpLockSleep = 60000;
5574
5575static bool tryLock(Mutex& mutex)
5576{
5577 bool locked = false;
5578 for (int i = 0; i < kDumpLockRetries; ++i) {
5579 if (mutex.tryLock() == NO_ERROR) {
5580 locked = true;
5581 break;
5582 }
5583 usleep(kDumpLockSleep);
5584 }
5585 return locked;
5586}
5587
Rucha Katakwardf223072021-06-15 10:21:00 -07005588void CameraService::cacheDump() {
5589 if (mMemFd != -1) {
5590 const Vector<String16> args;
5591 ATRACE_CALL();
5592 // Acquiring service lock here will avoid the deadlock since
5593 // cacheDump will not be called during the second disconnect.
5594 Mutex::Autolock lock(mServiceLock);
5595
5596 Mutex::Autolock l(mCameraStatesLock);
5597 // Start collecting the info for open sessions and store it in temp file.
5598 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005599 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005600 auto clientDescriptor = mActiveClientManager.get(cameraId);
5601 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005602 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005603 // Log the current open session info before device is disconnected.
5604 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5605 }
5606 }
5607 }
5608}
5609
Mathias Agopian65ab4712010-07-14 17:59:35 -07005610status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005611 ATRACE_CALL();
5612
Austin Borgered99f642023-06-01 16:51:35 -07005613 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005614 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005615 getCallingPid(),
5616 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005617 return NO_ERROR;
5618 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005619 bool locked = tryLock(mServiceLock);
5620 // failed to lock - CameraService is probably deadlocked
5621 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005622 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005623 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005624
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005625 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005626 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005627
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005628 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005629 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005630
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005631 if (locked) mServiceLock.unlock();
5632 return NO_ERROR;
5633 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005634 dprintf(fd, "\n== Service global info: ==\n\n");
5635 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005636 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005637 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5638 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005639 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5640 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5641 }
Austin Borgered99f642023-06-01 16:51:35 -07005642 std::string activeClientString = mActiveClientManager.toString();
5643 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5644 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005645 if (mStreamUseCaseOverrides.size() > 0) {
5646 dprintf(fd, "Active stream use case overrides:");
5647 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5648 dprintf(fd, " %" PRId64, useCaseOverride);
5649 }
5650 dprintf(fd, "\n");
5651 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005652
5653 dumpEventLog(fd);
5654
5655 bool stateLocked = tryLock(mCameraStatesLock);
5656 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005657 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005658 }
5659
Emilian Peevbd8c5032018-02-14 23:05:40 +00005660 int argSize = args.size();
5661 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005662 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005663 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005664 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005665 }
5666 break;
5667 }
5668 }
5669
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005670 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005671 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005672
Austin Borgered99f642023-06-01 16:51:35 -07005673 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005674
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005675 CameraParameters p = state.second->getShimParams();
5676 if (!p.isEmpty()) {
5677 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5678 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005679 }
5680
5681 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005682 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005683 // log the current open session info
5684 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005685 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005686 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005687 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005688
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005689 }
5690
5691 if (stateLocked) mCameraStatesLock.unlock();
5692
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005693 if (locked) mServiceLock.unlock();
5694
Emilian Peevf53f66e2017-04-11 14:29:43 +01005695 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005696
5697 dprintf(fd, "\n== Vendor tags: ==\n\n");
5698
5699 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5700 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005701 sp<VendorTagDescriptorCache> cache =
5702 VendorTagDescriptorCache::getGlobalVendorTagCache();
5703 if (cache == NULL) {
5704 dprintf(fd, "No vendor tags.\n");
5705 } else {
5706 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5707 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005708 } else {
5709 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5710 }
5711
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005712 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005713 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005714 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005715
5716 // Process dump arguments, if any
5717 int n = args.size();
5718 String16 verboseOption("-v");
5719 String16 unreachableOption("--unreachable");
5720 for (int i = 0; i < n; i++) {
5721 if (args[i] == verboseOption) {
5722 // change logging level
5723 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005724 std::string levelStr = toStdString(args[i+1]);
5725 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005726 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005727 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005728 } else if (args[i] == unreachableOption) {
5729 // Dump memory analysis
5730 // TODO - should limit be an argument parameter?
5731 UnreachableMemoryInfo info;
5732 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5733 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005734 dprintf(fd, "\n== Unable to dump unreachable memory. "
5735 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005736 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005737 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005738 std::string s = info.ToString(/*log_contents*/ true);
5739 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005740 }
5741 }
5742 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005743
5744 bool serviceLocked = tryLock(mServiceLock);
5745
5746 // Dump info from previous open sessions.
5747 // Reposition the offset to beginning of the file before reading
5748
5749 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5750 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5751 ssize_t size_read;
5752 char buf[4096];
5753 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5754 // Read data from file to a small buffer and write it to fd.
5755 write(fd, buf, size_read);
5756 if (size_read == -1) {
5757 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5758 break;
5759 }
5760 }
5761 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5762 } else {
5763 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5764 }
5765
5766 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005767 return NO_ERROR;
5768}
5769
Rucha Katakwardf223072021-06-15 10:21:00 -07005770void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005771 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005772 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005773 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005774 getFormattedCurrentTime().c_str(),
5775 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005776 dprintf(fd, " Client priority score: %d state: %d\n",
5777 clientDescriptor->getPriority().getScore(),
5778 clientDescriptor->getPriority().getState());
5779 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5780
5781 auto client = clientDescriptor->getValue();
5782 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005783 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005784
5785 client->dumpClient(fd, args);
5786}
5787
Austin Borgered99f642023-06-01 16:51:35 -07005788void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005789 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005790 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005791}
5792
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005793void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005794 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005795
5796 Mutex::Autolock l(mLogLock);
5797 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005798 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005799 }
5800
5801 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005802 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005803 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005804 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005805 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005806 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005807}
5808
Austin Borgered99f642023-06-01 16:51:35 -07005809void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005810 Mutex::Autolock lock(mLogLock);
5811 if (!isClientWatchedLocked(client)) { return; }
5812
5813 std::vector<std::string> dumpVector;
5814 client->dumpWatchedEventsToVector(dumpVector);
5815
5816 if (dumpVector.empty()) { return; }
5817
Austin Borgered99f642023-06-01 16:51:35 -07005818 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005819
Austin Borgered99f642023-06-01 16:51:35 -07005820 std::string currentTime = getFormattedCurrentTime();
5821 dumpString << "Cached @ ";
5822 dumpString << currentTime;
5823 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005824
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005825 size_t i = dumpVector.size();
5826
5827 // Store the string in reverse order (latest last)
5828 while (i > 0) {
5829 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005830 dumpString << cameraId;
5831 dumpString << ":";
5832 dumpString << client->getPackageName();
5833 dumpString << " ";
5834 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005835 }
5836
Austin Borgered99f642023-06-01 16:51:35 -07005837 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005838}
5839
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005840void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005841 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005842 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5843 if (mTorchClientMap[i] == who) {
5844 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005845 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005846 status_t res = mFlashlight->setTorchMode(cameraId, false);
5847 if (res) {
5848 ALOGE("%s: torch client died but couldn't turn off torch: "
5849 "%s (%d)", __FUNCTION__, strerror(-res), res);
5850 return;
5851 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005852 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005853 break;
5854 }
5855 }
5856}
5857
Ruben Brunkcc776712015-02-17 20:18:47 -08005858/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005859
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005860 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005861 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5862 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005863 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005864 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005865 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005866
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005867 // check torch client
5868 handleTorchClientBinderDied(who);
5869
5870 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005871 if(!evictClientIdByRemote(who)) {
5872 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005873 return;
5874 }
5875
Ruben Brunkcc776712015-02-17 20:18:47 -08005876 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5877 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005878}
5879
Austin Borgered99f642023-06-01 16:51:35 -07005880void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005881 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005882}
5883
Austin Borgered99f642023-06-01 16:51:35 -07005884void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005885 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005886 // Do not lock mServiceLock here or can get into a deadlock from
5887 // connect() -> disconnect -> updateStatus
5888
5889 auto state = getCameraState(cameraId);
5890
5891 if (state == nullptr) {
5892 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005893 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005894 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005895 }
5896
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005897 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5898 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5899 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005900 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005901 return;
5902 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005903
Biswarup Pal37a75182024-01-16 15:53:35 +00005904 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5905 CameraMetadata cameraInfo;
5906 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005907 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005908 if (res != OK) {
5909 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5910 __FUNCTION__, cameraId.c_str());
5911 } else {
5912 int32_t deviceId = getDeviceId(cameraInfo);
5913 if (deviceId != kDefaultDeviceId) {
5914 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5915 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5916 static_cast<camera_metadata_enum_android_lens_facing_t>(
5917 lensFacingEntry.data.u8[0]);
5918 std::string mappedCameraId;
5919 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5920 mappedCameraId = kVirtualDeviceBackCameraId;
5921 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5922 mappedCameraId = kVirtualDeviceFrontCameraId;
5923 } else {
5924 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5925 __func__);
5926 }
5927 if (!mappedCameraId.empty()) {
5928 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5929 }
5930 }
5931 }
5932 }
5933
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005934 // Collect the logical cameras without holding mStatusLock in updateStatus
5935 // as that can lead to a deadlock(b/162192331).
5936 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005937 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005938 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005939 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005940 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005941 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005942 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5943 auto [deviceId, mappedCameraId] =
5944 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005945
Biswarup Pal37a75182024-01-16 15:53:35 +00005946 if (status != StatusInternal::ENUMERATING) {
5947 // Update torch status if it has a flash unit.
5948 Mutex::Autolock al(mTorchStatusMutex);
5949 TorchModeStatus torchStatus;
5950 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5951 NAME_NOT_FOUND) {
5952 TorchModeStatus newTorchStatus =
5953 status == StatusInternal::PRESENT ?
5954 TorchModeStatus::AVAILABLE_OFF :
5955 TorchModeStatus::NOT_AVAILABLE;
5956 if (torchStatus != newTorchStatus) {
5957 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5958 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005959 }
5960 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005961
Biswarup Pal37a75182024-01-16 15:53:35 +00005962 Mutex::Autolock lock(mStatusListenerLock);
5963 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5964 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005965
Biswarup Pal37a75182024-01-16 15:53:35 +00005966 for (auto& listener : mListenerList) {
5967 bool isVendorListener = listener->isVendorListener();
5968 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5969 listener->getListenerPid(), listener->getListenerUid())) {
5970 ALOGV("Skipping discovery callback for system-only camera device %s",
5971 cameraId.c_str());
5972 continue;
5973 }
5974
5975 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5976 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005977 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005978 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005979 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5980 ret.exceptionCode());
5981 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005982 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005983}
5984
Austin Borgered99f642023-06-01 16:51:35 -07005985void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005986 const std::string& clientPackageName, bool sharedMode) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005987 auto state = getCameraState(cameraId);
5988 if (state == nullptr) {
5989 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005990 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005991 return;
5992 }
5993 if (open) {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005994 if (flags::camera_multi_client() && sharedMode) {
5995 state->addClientPackage(clientPackageName);
5996 } else {
5997 state->setClientPackage(clientPackageName);
5998 }
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005999 } else {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07006000 if (flags::camera_multi_client() && sharedMode) {
6001 state->removeClientPackage(clientPackageName);
6002 } else {
6003 state->setClientPackage(std::string());
6004 }
Shuzhen Wange7aa0342021-08-03 11:29:47 -07006005 }
6006
Biswarup Pal37a75182024-01-16 15:53:35 +00006007 // Get the device id and app-visible camera id for the given HAL-visible camera id.
6008 auto [deviceId, mappedCameraId] =
6009 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
6010
Shuzhen Wang695044d2020-03-06 09:02:23 -08006011 Mutex::Autolock lock(mStatusListenerLock);
6012
6013 for (const auto& it : mListenerList) {
6014 if (!it->isOpenCloseCallbackAllowed()) {
6015 continue;
6016 }
6017
6018 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08006019 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00006020 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
6021 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08006022 } else {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07006023 if (!flags::camera_multi_client() || !sharedMode || (sharedMode &&
6024 mActiveClientManager.getCameraClient(cameraId) == nullptr)) {
6025 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
6026 }
Shuzhen Wang695044d2020-03-06 09:02:23 -08006027 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006028
6029 it->handleBinderStatus(ret,
6030 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
6031 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08006032 }
6033}
6034
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006035template<class Func>
6036void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07006037 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006038 std::initializer_list<StatusInternal> rejectSourceStates,
6039 Func onStatusUpdatedLocked) {
6040 Mutex::Autolock lock(mStatusLock);
6041 StatusInternal oldStatus = mStatus;
6042 mStatus = status;
6043
6044 if (oldStatus == status) {
6045 return;
6046 }
6047
6048 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07006049 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006050
6051 if (oldStatus == StatusInternal::NOT_PRESENT &&
6052 (status != StatusInternal::PRESENT &&
6053 status != StatusInternal::ENUMERATING)) {
6054
6055 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
6056 __FUNCTION__);
6057 mStatus = oldStatus;
6058 return;
6059 }
6060
6061 /**
6062 * Sometimes we want to conditionally do a transition.
6063 * For example if a client disconnects, we want to go to PRESENT
6064 * only if we weren't already in NOT_PRESENT or ENUMERATING.
6065 */
6066 for (auto& rejectStatus : rejectSourceStates) {
6067 if (oldStatus == rejectStatus) {
6068 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07006069 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006070 mStatus = oldStatus;
6071 return;
6072 }
6073 }
6074
6075 onStatusUpdatedLocked(cameraId, status);
6076}
6077
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006078status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07006079 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006080 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006081 if (!status) {
6082 return BAD_VALUE;
6083 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006084 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6085 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006086 // invalid camera ID or the camera doesn't have a flash unit
6087 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006088 }
6089
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006090 *status = mTorchStatusMap.valueAt(index);
6091 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006092}
6093
Austin Borgered99f642023-06-01 16:51:35 -07006094status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006095 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006096 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6097 if (index == NAME_NOT_FOUND) {
6098 return BAD_VALUE;
6099 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006100 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006101
6102 return OK;
6103}
6104
Austin Borgered99f642023-06-01 16:51:35 -07006105std::list<std::string> CameraService::getLogicalCameras(
6106 const std::string& physicalCameraId) {
6107 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006108 Mutex::Autolock lock(mCameraStatesLock);
6109 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006110 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6111 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006112 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006113 }
6114 return retList;
6115}
6116
6117void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006118 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006119 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006120 // mStatusListenerLock is expected to be locked
6121 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006122 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006123 // Note: we check only the deviceKind of the physical camera id
6124 // since, logical camera ids and their physical camera ids are
6125 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006126 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6127 listener->getListenerPid(), listener->getListenerUid())) {
6128 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006129 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006130 continue;
6131 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006132 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006133 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006134 listener->handleBinderStatus(ret,
6135 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6136 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6137 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006138 }
6139 }
6140}
6141
Svet Ganova453d0d2018-01-11 15:37:58 -08006142void CameraService::blockClientsForUid(uid_t uid) {
6143 const auto clients = mActiveClientManager.getAll();
6144 for (auto& current : clients) {
6145 if (current != nullptr) {
6146 const auto basicClient = current->getValue();
6147 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6148 basicClient->block();
6149 }
6150 }
6151 }
6152}
6153
Michael Grooverd1d435a2018-12-18 17:39:42 -08006154void CameraService::blockAllClients() {
6155 const auto clients = mActiveClientManager.getAll();
6156 for (auto& current : clients) {
6157 if (current != nullptr) {
6158 const auto basicClient = current->getValue();
6159 if (basicClient.get() != nullptr) {
6160 basicClient->block();
6161 }
6162 }
6163 }
6164}
6165
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006166void CameraService::blockPrivacyEnabledClients() {
6167 const auto clients = mActiveClientManager.getAll();
6168 for (auto& current : clients) {
6169 if (current != nullptr) {
6170 const auto basicClient = current->getValue();
6171 if (basicClient.get() != nullptr) {
6172 std::string pkgName = basicClient->getPackageName();
6173 bool cameraPrivacyEnabled =
6174 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6175 if (cameraPrivacyEnabled) {
6176 basicClient->block();
6177 }
6178 }
6179 }
6180 }
6181}
6182
Svet Ganova453d0d2018-01-11 15:37:58 -08006183// NOTE: This is a remote API - make sure all args are validated
6184status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006185 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006186 return PERMISSION_DENIED;
6187 }
6188 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6189 return BAD_VALUE;
6190 }
Austin Borgered99f642023-06-01 16:51:35 -07006191 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006192 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006193 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006194 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006195 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006196 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006197 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006198 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006199 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006200 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006201 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006202 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006203 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006204 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006205 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006206 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006207 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006208 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006209 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006210 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006211 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006212 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006213 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006214 handleClearStreamUseCaseOverrides();
6215 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006216 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006217 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006218 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006219 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006220 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006221 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006222 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006223 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006224 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006225 }
6226 printHelp(err);
6227 return BAD_VALUE;
6228}
6229
6230status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006231 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006232
Svet Ganova453d0d2018-01-11 15:37:58 -08006233 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006234 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006235 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006236 } else if ((args[2] != toString16("idle"))) {
6237 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006238 return BAD_VALUE;
6239 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006240
6241 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006242 if (args.size() >= 5 && args[3] == toString16("--user")) {
6243 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006244 }
6245
6246 uid_t uid;
6247 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6248 return BAD_VALUE;
6249 }
6250
6251 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006252 return NO_ERROR;
6253}
6254
6255status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006256 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006257
6258 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006259 if (args.size() >= 4 && args[2] == toString16("--user")) {
6260 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006261 }
6262
6263 uid_t uid;
6264 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006265 return BAD_VALUE;
6266 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006267
6268 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006269 return NO_ERROR;
6270}
6271
6272status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006273 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006274
6275 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006276 if (args.size() >= 4 && args[2] == toString16("--user")) {
6277 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006278 }
6279
6280 uid_t uid;
6281 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006282 return BAD_VALUE;
6283 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006284
6285 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006286 return dprintf(out, "active\n");
6287 } else {
6288 return dprintf(out, "idle\n");
6289 }
6290}
6291
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006292status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006293 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006294 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6295 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6296 Mutex::Autolock lock(mServiceLock);
6297
6298 mOverrideRotateAndCropMode = rotateValue;
6299
6300 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6301
6302 const auto clients = mActiveClientManager.getAll();
6303 for (auto& current : clients) {
6304 if (current != nullptr) {
6305 const auto basicClient = current->getValue();
6306 if (basicClient.get() != nullptr) {
6307 basicClient->setRotateAndCropOverride(rotateValue);
6308 }
6309 }
6310 }
6311
6312 return OK;
6313}
6314
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006315status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6316 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006317 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006318 if ((*end != '\0') ||
6319 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6320 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6321 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6322 return BAD_VALUE;
6323 }
6324
6325 Mutex::Autolock lock(mServiceLock);
6326 mOverrideAutoframingMode = autoframingValue;
6327
6328 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6329
6330 const auto clients = mActiveClientManager.getAll();
6331 for (auto& current : clients) {
6332 if (current != nullptr) {
6333 const auto basicClient = current->getValue();
6334 if (basicClient.get() != nullptr) {
6335 basicClient->setAutoframingOverride(autoframingValue);
6336 }
6337 }
6338 }
6339
6340 return OK;
6341}
6342
Ravneetaeb20dc2022-03-30 05:33:03 +00006343status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006344 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006345
6346 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6347
6348 Mutex::Autolock lock(mServiceLock);
6349
6350 mCameraServiceWatchdogEnabled = enableWatchdog;
6351
6352 const auto clients = mActiveClientManager.getAll();
6353 for (auto& current : clients) {
6354 if (current != nullptr) {
6355 const auto basicClient = current->getValue();
6356 if (basicClient.get() != nullptr) {
6357 basicClient->setCameraServiceWatchdog(enableWatchdog);
6358 }
6359 }
6360 }
6361
6362 return OK;
6363}
6364
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006365status_t CameraService::handleGetRotateAndCrop(int out) {
6366 Mutex::Autolock lock(mServiceLock);
6367
6368 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6369}
6370
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006371status_t CameraService::handleGetAutoframing(int out) {
6372 Mutex::Autolock lock(mServiceLock);
6373
6374 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6375}
6376
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006377status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6378 char *endPtr;
6379 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006380 std::string maskString = toStdString(args[1]);
6381 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006382
6383 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006384 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006385 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6386
6387 Mutex::Autolock lock(mServiceLock);
6388
6389 mImageDumpMask = maskValue;
6390
6391 return OK;
6392}
6393
6394status_t CameraService::handleGetImageDumpMask(int out) {
6395 Mutex::Autolock lock(mServiceLock);
6396
6397 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6398}
6399
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006400status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006401 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006402 if (errno != 0) return BAD_VALUE;
6403
6404 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6405 Mutex::Autolock lock(mServiceLock);
6406
6407 mOverrideCameraMuteMode = (muteValue == 1);
6408
6409 const auto clients = mActiveClientManager.getAll();
6410 for (auto& current : clients) {
6411 if (current != nullptr) {
6412 const auto basicClient = current->getValue();
6413 if (basicClient.get() != nullptr) {
6414 if (basicClient->supportsCameraMute()) {
6415 basicClient->setCameraMute(mOverrideCameraMuteMode);
6416 }
6417 }
6418 }
6419 }
6420
6421 return OK;
6422}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006423
Shuzhen Wang16610a62022-12-15 22:38:07 -08006424status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6425 std::vector<int64_t> useCasesOverride;
6426 for (size_t i = 1; i < args.size(); i++) {
6427 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006428 std::string arg = toStdString(args[i]);
6429 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006430 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006431 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006432 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006433 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006434 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006435 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006436 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006437 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006438 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006439 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006440 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006441 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006442 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6443 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006444 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006445 return BAD_VALUE;
6446 }
6447 useCasesOverride.push_back(useCase);
6448 }
6449
6450 Mutex::Autolock lock(mServiceLock);
6451 mStreamUseCaseOverrides = std::move(useCasesOverride);
6452
6453 return OK;
6454}
6455
6456void CameraService::handleClearStreamUseCaseOverrides() {
6457 Mutex::Autolock lock(mServiceLock);
6458 mStreamUseCaseOverrides.clear();
6459}
6460
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006461status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6462 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006463 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006464 if ((*end != '\0') ||
6465 (zoomOverrideValue != -1 &&
6466 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6467 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6468 return BAD_VALUE;
6469 }
6470
6471 Mutex::Autolock lock(mServiceLock);
6472 mZoomOverrideValue = zoomOverrideValue;
6473
6474 const auto clients = mActiveClientManager.getAll();
6475 for (auto& current : clients) {
6476 if (current != nullptr) {
6477 const auto basicClient = current->getValue();
6478 if (basicClient.get() != nullptr) {
6479 if (basicClient->supportsZoomOverride()) {
6480 basicClient->setZoomOverride(mZoomOverrideValue);
6481 }
6482 }
6483 }
6484 }
6485
6486 return OK;
6487}
6488
Avichal Rakesh84147132021-11-11 17:47:11 -08006489status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006490 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006491 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006492 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006493 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006494 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006495 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006496 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006497 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006498 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006499 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006500 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006501 dprintf(outFd, "Camera service watch commands:\n"
6502 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6503 " starts watching the provided tags for clients with provided package\n"
6504 " recognizes tag shorthands like '3a'\n"
6505 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006506 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006507 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006508 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006509 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006510 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006511 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006512 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006513}
6514
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006515status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6516 Mutex::Autolock lock(mLogLock);
6517 size_t tagsIdx; // index of '-m'
6518 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006519 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006520 if (tagsIdx < args.size() - 1) {
6521 tags = args[tagsIdx + 1];
6522 } else {
6523 dprintf(outFd, "No tags provided.\n");
6524 return BAD_VALUE;
6525 }
6526
6527 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006528 // watch all clients if no clients are provided
6529 String16 clients = toString16(kWatchAllClientsFlag);
6530 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006531 clientsIdx++);
6532 if (clientsIdx < args.size() - 1) {
6533 clients = args[clientsIdx + 1];
6534 }
Austin Borgered99f642023-06-01 16:51:35 -07006535 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006536
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006537 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006538 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006539
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006540 bool serviceLock = tryLock(mServiceLock);
6541 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006542 auto cameraClients = mActiveClientManager.getAll();
6543 for (const auto &clientDescriptor: cameraClients) {
6544 if (clientDescriptor == nullptr) { continue; }
6545 sp<BasicClient> client = clientDescriptor->getValue();
6546 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006547
6548 if (isClientWatchedLocked(client.get())) {
6549 client->startWatchingTags(mMonitorTags, outFd);
6550 numWatchedClients++;
6551 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006552 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006553 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6554
6555 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006556 return OK;
6557}
6558
6559status_t CameraService::stopWatchingTags(int outFd) {
6560 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006561 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006562 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006563
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006564 mWatchedClientPackages.clear();
6565 mWatchedClientsDumpCache.clear();
6566
6567 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006568 auto cameraClients = mActiveClientManager.getAll();
6569 for (const auto &clientDescriptor : cameraClients) {
6570 if (clientDescriptor == nullptr) { continue; }
6571 sp<BasicClient> client = clientDescriptor->getValue();
6572 if (client.get() == nullptr) { continue; }
6573 client->stopWatchingTags(outFd);
6574 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006575 dprintf(outFd, "Stopped watching all clients.\n");
6576 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006577 return OK;
6578}
6579
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006580status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6581 Mutex::Autolock lock(mLogLock);
6582 size_t clearedSize = mWatchedClientsDumpCache.size();
6583 mWatchedClientsDumpCache.clear();
6584 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6585 return OK;
6586}
6587
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006588status_t CameraService::printWatchedTags(int outFd) {
6589 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006590 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006591
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006592 bool printedSomething = false; // tracks if any monitoring information was printed
6593 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006594
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006595 bool serviceLock = tryLock(mServiceLock);
6596 // get all watched clients that are currently connected
6597 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6598 if (clientDescriptor == nullptr) { continue; }
6599
6600 sp<BasicClient> client = clientDescriptor->getValue();
6601 if (client.get() == nullptr) { continue; }
6602 if (!isClientWatchedLocked(client.get())) { continue; }
6603
6604 std::vector<std::string> dumpVector;
6605 client->dumpWatchedEventsToVector(dumpVector);
6606
6607 size_t printIdx = dumpVector.size();
6608 if (printIdx == 0) {
6609 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006610 }
6611
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006612 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006613 const std::string &cameraId = clientDescriptor->getKey();
6614 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006615 while(printIdx > 0) {
6616 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006617 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006618 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006619 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006620 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006621 printedSomething = true;
6622
6623 connectedMonitoredClients.emplace(client->getPackageName());
6624 }
6625 if (serviceLock) { mServiceLock.unlock(); }
6626
6627 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6628 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006629 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006630 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6631 continue;
6632 }
6633
Austin Borgered99f642023-06-01 16:51:35 -07006634 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006635 dprintf(outFd, "%s\n", kv.second.c_str());
6636 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006637 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006638
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006639 if (!printedSomething) {
6640 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006641 }
6642
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006643 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006644}
6645
Avichal Rakesh84147132021-11-11 17:47:11 -08006646// Print all events in vector `events' that came after lastPrintedEvent
6647void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006648 const std::string &cameraId,
6649 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006650 const std::vector<std::string> &events,
6651 const std::string &lastPrintedEvent) {
6652 if (events.empty()) { return; }
6653
6654 // index of lastPrintedEvent in events.
6655 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6656 size_t lastPrintedIdx;
6657 for (lastPrintedIdx = 0;
6658 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6659 lastPrintedIdx++);
6660
6661 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6662
Avichal Rakesh84147132021-11-11 17:47:11 -08006663 // print events in chronological order (latest event last)
6664 size_t idxToPrint = lastPrintedIdx;
6665 do {
6666 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006667 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6668 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006669 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006670}
6671
6672// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6673// command should be interrupted if the user presses the return key, or if user loses any way to
6674// signal interrupt.
6675// If timeoutMs == 0, this function will always return false
6676bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6677 struct timeval startTime;
6678 int startTimeError = gettimeofday(&startTime, nullptr);
6679 if (startTimeError) {
6680 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6681 return true;
6682 }
6683
6684 const nfds_t numFds = 1;
6685 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6686
6687 struct timeval currTime;
6688 char buffer[2];
6689 while(true) {
6690 int currTimeError = gettimeofday(&currTime, nullptr);
6691 if (currTimeError) {
6692 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6693 return true;
6694 }
6695
6696 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6697 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6698 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6699
6700 if (remainingTimeMs <= 0) {
6701 // No user interrupt within timeoutMs, don't interrupt watch command
6702 return false;
6703 }
6704
6705 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6706 if (numFdsUpdated < 0) {
6707 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6708 return true;
6709 }
6710
6711 if (numFdsUpdated == 0) {
6712 // No user input within timeoutMs, don't interrupt watch command
6713 return false;
6714 }
6715
6716 if (!(pollFd.revents & POLLIN)) {
6717 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6718 return true;
6719 }
6720
6721 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6722 if (sizeRead < 0) {
6723 dprintf(outFd, "Error reading user input. Exiting.\n");
6724 return true;
6725 }
6726
6727 if (sizeRead == 0) {
6728 // Reached end of input fd (can happen if input is piped)
6729 // User has no way to signal an interrupt, so interrupt here
6730 return true;
6731 }
6732
6733 if (buffer[0] == '\n') {
6734 // User pressed return, interrupt watch command.
6735 return true;
6736 }
6737 }
6738}
6739
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006740status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6741 int inFd, int outFd) {
6742 // Figure out refresh interval, if present in args
6743 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006744 if (args.size() > 2) {
6745 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006746 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006747 intervalIdx++);
6748
6749 size_t intervalValIdx = intervalIdx + 1;
6750 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006751 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006752 if (errno) { return BAD_VALUE; }
6753 }
6754 }
6755
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006756 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6757 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006758
Avichal Rakesh84147132021-11-11 17:47:11 -08006759 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006760 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006761
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006762 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006763 bool serviceLock = tryLock(mServiceLock);
6764 auto cameraClients = mActiveClientManager.getAll();
6765 if (serviceLock) { mServiceLock.unlock(); }
6766
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006767 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006768 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006769 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006770
6771 sp<BasicClient> client = clientDescriptor->getValue();
6772 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006773 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006774
Austin Borgered99f642023-06-01 16:51:35 -07006775 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006776 // This also initializes the map entries with an empty string
6777 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6778
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006779 std::vector<std::string> latestEvents;
6780 client->dumpWatchedEventsToVector(latestEvents);
6781
6782 if (!latestEvents.empty()) {
6783 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006784 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006785 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006786 latestEvents,
6787 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006788 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006789 }
6790 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006791 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006792 break;
6793 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006794 }
6795 return OK;
6796}
6797
Austin Borgered99f642023-06-01 16:51:35 -07006798void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006799 mWatchedClientPackages.clear();
6800
Austin Borgered99f642023-06-01 16:51:35 -07006801 std::istringstream iss(clients);
6802 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006803
Austin Borgered99f642023-06-01 16:51:35 -07006804 while (std::getline(iss, nextClient, ',')) {
6805 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006806 // Don't need to track any other package if 'all' is present
6807 mWatchedClientPackages.clear();
6808 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6809 break;
6810 }
6811
6812 // track package names
6813 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006814 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006815}
6816
Svet Ganova453d0d2018-01-11 15:37:58 -08006817status_t CameraService::printHelp(int out) {
6818 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006819 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6820 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6821 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006822 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6823 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6824 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006825 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6826 " Valid values 0=false, 1=true, 2=auto\n"
6827 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006828 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6829 " Valid values 0=OFF, 1=ON for JPEG\n"
6830 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006831 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006832 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6833 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6834 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6835 " on. In case the number of usecases is smaller than the number of streams, the\n"
6836 " last use case is assigned to all the remaining streams. In case of multiple\n"
6837 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6838 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6839 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6840 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006841 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6842 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006843 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6844 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006845 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006846 " help print this message\n");
6847}
6848
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006849bool CameraService::isClientWatched(const BasicClient *client) {
6850 Mutex::Autolock lock(mLogLock);
6851 return isClientWatchedLocked(client);
6852}
6853
6854bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6855 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6856 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6857}
6858
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006859int32_t CameraService::updateAudioRestriction() {
6860 Mutex::Autolock lock(mServiceLock);
6861 return updateAudioRestrictionLocked();
6862}
6863
6864int32_t CameraService::updateAudioRestrictionLocked() {
6865 int32_t mode = 0;
6866 // iterate through all active client
6867 for (const auto& i : mActiveClientManager.getAll()) {
6868 const auto clientSp = i->getValue();
6869 mode |= clientSp->getAudioRestriction();
6870 }
6871
6872 bool modeChanged = (mAudioRestriction != mode);
6873 mAudioRestriction = mode;
6874 if (modeChanged) {
6875 mAppOps.setCameraAudioRestriction(mode);
6876 }
6877 return mode;
6878}
6879
Austin Borgered99f642023-06-01 16:51:35 -07006880status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006881 sp<BasicClient> clientSp) {
6882 std::unique_ptr<AutoConditionLock> lock =
6883 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6884 status_t res = NO_ERROR;
6885 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006886 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006887 mInjectionStatusListener->notifyInjectionError(
6888 externalCamId, UNKNOWN_TRANSACTION);
6889 clientSp->notifyError(
6890 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6891 CaptureResultExtras());
6892
6893 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6894 // other clients from connecting in mServiceLockWrapper if held
6895 mServiceLock.unlock();
6896
6897 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006898 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006899 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006900 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006901
6902 // Reacquire mServiceLock
6903 mServiceLock.lock();
6904 }
6905
6906 return res;
6907}
6908
Cliff Wud3a05312021-04-26 23:07:31 +08006909void CameraService::clearInjectionParameters() {
6910 {
6911 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006912 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006913 mInjectionInternalCamId = "";
6914 }
6915 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006916 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006917}
6918
Biswarup Pal37a75182024-01-16 15:53:35 +00006919} // namespace android