blob: 31a45c381b2d6cf753cfe3d0cc45139db714c7eb [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,
1495 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001496 // For HIDL devices
1497 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1498 // Create CameraClient based on device version reported by the HAL.
1499 int deviceVersion = deviceVersionAndTransport.first;
1500 switch(deviceVersion) {
1501 case CAMERA_DEVICE_API_VERSION_1_0:
1502 ALOGE("Camera using old HAL version: %d", deviceVersion);
1503 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1504 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001505 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001506 break;
1507 case CAMERA_DEVICE_API_VERSION_3_0:
1508 case CAMERA_DEVICE_API_VERSION_3_1:
1509 case CAMERA_DEVICE_API_VERSION_3_2:
1510 case CAMERA_DEVICE_API_VERSION_3_3:
1511 case CAMERA_DEVICE_API_VERSION_3_4:
1512 case CAMERA_DEVICE_API_VERSION_3_5:
1513 case CAMERA_DEVICE_API_VERSION_3_6:
1514 case CAMERA_DEVICE_API_VERSION_3_7:
1515 break;
1516 default:
1517 // Should not be reachable
1518 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1519 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1520 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001521 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001522 }
1523 }
1524 if (effectiveApiLevel == API_1) { // Camera1 API route
1525 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001526 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger2e772b82024-10-11 16:09:57 -07001527 cameraService->mAttributionAndPermissionUtils,
1528 clientAttribution, callingPid, cameraId, api1CameraId, facing,
1529 sensorOrientation, servicePid, overrideForPerfClass,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001530 rotationOverride, forceSlowJpegMode, /*sharedMode*/false);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001531 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1532 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001533 } else { // Camera2 API route
1534 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1535 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger2e772b82024-10-11 16:09:57 -07001536 *client = new CameraDeviceClient(
1537 cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1538 cameraService->mAttributionAndPermissionUtils, clientAttribution, callingPid,
1539 systemNativeClient, cameraId, facing, sensorOrientation, servicePid,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001540 overrideForPerfClass, rotationOverride, originalCameraId, sharedMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001541 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001542 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001543 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001544}
1545
Austin Borgered99f642023-06-01 16:51:35 -07001546std::string CameraService::toString(std::set<userid_t> intSet) {
1547 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001548 bool first = true;
1549 for (userid_t i : intSet) {
1550 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001551 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001552 first = false;
1553 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001554 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001555 }
1556 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001557 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001558}
1559
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001560int32_t CameraService::mapToInterface(TorchModeStatus status) {
1561 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1562 switch (status) {
1563 case TorchModeStatus::NOT_AVAILABLE:
1564 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1565 break;
1566 case TorchModeStatus::AVAILABLE_OFF:
1567 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1568 break;
1569 case TorchModeStatus::AVAILABLE_ON:
1570 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1571 break;
1572 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001573 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001574 }
1575 return serviceStatus;
1576}
1577
1578CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1579 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1580 switch (status) {
1581 case CameraDeviceStatus::NOT_PRESENT:
1582 serviceStatus = StatusInternal::NOT_PRESENT;
1583 break;
1584 case CameraDeviceStatus::PRESENT:
1585 serviceStatus = StatusInternal::PRESENT;
1586 break;
1587 case CameraDeviceStatus::ENUMERATING:
1588 serviceStatus = StatusInternal::ENUMERATING;
1589 break;
1590 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001591 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001592 }
1593 return serviceStatus;
1594}
1595
1596int32_t CameraService::mapToInterface(StatusInternal status) {
1597 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1598 switch (status) {
1599 case StatusInternal::NOT_PRESENT:
1600 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1601 break;
1602 case StatusInternal::PRESENT:
1603 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1604 break;
1605 case StatusInternal::ENUMERATING:
1606 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1607 break;
1608 case StatusInternal::NOT_AVAILABLE:
1609 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1610 break;
1611 case StatusInternal::UNKNOWN:
1612 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1613 break;
1614 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001615 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001616 }
1617 return serviceStatus;
1618}
1619
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001621 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001622
Austin Borgered99f642023-06-01 16:51:35 -07001623 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001624 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001625 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001626
Austin Borgerb01a8702024-07-22 16:20:34 -07001627 int callingPid = getCallingPid();
1628 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001629
Austin Borger23694432024-10-07 19:28:01 -07001630 AttributionSourceState clientAttribution =
1631 buildAttributionSource(callingPid, uid, kServiceName, kDefaultDeviceId);
1632
1633 if (!(ret = connectHelper<ICameraClient, Client>(
1634 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId, clientAttribution,
1635 /*systemNativeClient*/ false, API_1, /*shimUpdateOnly*/ true,
1636 /*oomScoreOffset*/ 0,
1637 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1638 /*rotationOverride*/
1639 hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001640 /*forceSlowJpegMode*/ false, cameraIdStr, /*isNonSystemNdk*/ false,
1641 /*sharedMode*/false, /*out*/ tmp))
Austin Borger23694432024-10-07 19:28:01 -07001642 .isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001643 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001644 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001645 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001646}
1647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001648Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001649 /*out*/
1650 CameraParameters* parameters) {
1651
1652 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1653
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001655
1656 if (parameters == NULL) {
1657 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001658 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001659 }
1660
malikakash98260df2024-05-10 23:33:57 +00001661 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001662
1663 // Check if we already have parameters
1664 {
1665 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001666 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001667 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001668 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001669 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001670 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001671 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001672 }
1673 CameraParameters p = cameraState->getShimParams();
1674 if (!p.isEmpty()) {
1675 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001676 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001677 }
1678 }
1679
Austin Borger22c5c852024-03-08 13:31:36 -08001680 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001681 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001682 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001683 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001684 // Error already logged by callee
1685 return ret;
1686 }
1687
1688 // Check for parameters again
1689 {
1690 // Scope for service lock
1691 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001692 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001693 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001694 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001695 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001696 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001697 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001698 CameraParameters p = cameraState->getShimParams();
1699 if (!p.isEmpty()) {
1700 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001701 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001702 }
1703 }
1704
Ruben Brunkcc776712015-02-17 20:18:47 -08001705 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1706 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001707 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001708}
1709
Austin Borgered99f642023-06-01 16:51:35 -07001710Status CameraService::validateConnectLocked(const std::string& cameraId,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001711 const AttributionSourceState& clientAttribution,
1712 bool sharedMode) const {
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001713#ifdef __BRILLO__
Austin Borger23694432024-10-07 19:28:01 -07001714 UNUSED(clientAttribution);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001715#else
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001716 Status allowed = validateClientPermissionsLocked(cameraId, clientAttribution, sharedMode);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001717 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001718 return allowed;
1719 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001720#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001721
Austin Borger22c5c852024-03-08 13:31:36 -08001722 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001723
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001724 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001725 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1726 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001727 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001728 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001729 }
1730
Ruben Brunkcc776712015-02-17 20:18:47 -08001731 if (getCameraState(cameraId) == nullptr) {
1732 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001733 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001734 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001735 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001736 }
1737
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001738 status_t err = checkIfDeviceIsUsable(cameraId);
1739 if (err != NO_ERROR) {
1740 switch(err) {
1741 case -ENODEV:
1742 case -EBUSY:
1743 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001744 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001745 default:
1746 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001747 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001748 }
1749 }
1750 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001751}
1752
Austin Borger23694432024-10-07 19:28:01 -07001753Status CameraService::validateClientPermissionsLocked(
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001754 const std::string& cameraId, const AttributionSourceState& clientAttribution,
1755 bool sharedMode) const {
Austin Borgerb01a8702024-07-22 16:20:34 -07001756 int callingPid = getCallingPid();
1757 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001758
Austin Borger23694432024-10-07 19:28:01 -07001759 int clientPid = clientAttribution.pid;
1760 int clientUid = clientAttribution.uid;
1761 const std::string clientName = clientAttribution.packageName.value_or(kUnknownPackageName);
1762
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001763 if (shouldRejectSystemCameraConnection(cameraId)) {
1764 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1765 cameraId.c_str());
1766 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001767 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001768 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001769 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1770 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001771 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001772 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001773 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001774 }
1775
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001776 if (flags::camera_multi_client() && sharedMode
1777 && (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA)) {
1778 ALOGE("%s: camera id %s is not system camera. Device sharing only supported for"
1779 " system cameras.", __FUNCTION__, cameraId.c_str());
1780 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "camera device sharing not supported for "
1781 "camera ID \"%s\"", cameraId.c_str());
1782 }
1783
Biswarup Pale506e732024-03-27 13:46:20 +00001784 // Get the device id that owns this camera.
1785 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Austin Borger23694432024-10-07 19:28:01 -07001786 AttributionSourceState clientAttributionWithDeviceId = clientAttribution;
1787 clientAttributionWithDeviceId.deviceId = deviceId;
Biswarup Pale506e732024-03-27 13:46:20 +00001788
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001789 // If it's not calling from cameraserver, check the permission if the
1790 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1791 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001792 bool checkPermissionForCamera =
Austin Borger23694432024-10-07 19:28:01 -07001793 hasPermissionsForCamera(cameraId, clientAttributionWithDeviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001794 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001795 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001796 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001797 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1798 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001799 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001800 }
1801
Svet Ganova453d0d2018-01-11 15:37:58 -08001802 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001803 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001804 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001805 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1806 clientPid, clientUid);
1807 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001808 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1809 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001810 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001811 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001812 }
1813
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001814 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1815 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1816 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1817 if ((!isAutomotivePrivilegedClient(callingUid) ||
1818 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1819 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001820 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1821 return STATUS_ERROR_FMT(ERROR_DISABLED,
1822 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001823 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001824 }
1825
Austin Borger6e831c42024-07-22 13:07:56 -07001826 userid_t clientUserId = multiuser_get_user_id(clientUid);
1827
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001828 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1829 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001830
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001831 // For non-system clients : Only allow clients who are being used by the current foreground
1832 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001833 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001834 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001835 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1836 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001837 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001838 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1839 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001840 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001841 }
1842
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001843 if (flags::camera_hsum_permission()) {
1844 // If the System User tries to access the camera when the device is running in
1845 // headless system user mode, ensure that client has the required permission
1846 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001847 if (isHeadlessSystemUserMode()
1848 && (clientUserId == USER_SYSTEM)
1849 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001850 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001851 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1852 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1853 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001854 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001855 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001856 }
1857
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001859}
1860
Austin Borgered99f642023-06-01 16:51:35 -07001861status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001863 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001864 if (cameraState == nullptr) {
1865 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001866 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001867 return -ENODEV;
1868 }
1869
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001870 StatusInternal currentStatus = cameraState->getStatus();
1871 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001872 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001873 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001874 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001875 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001876 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001877 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001878 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001879 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001880
Ruben Brunkcc776712015-02-17 20:18:47 -08001881 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001882}
1883
Ruben Brunkcc776712015-02-17 20:18:47 -08001884void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001885 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001886
Ruben Brunkcc776712015-02-17 20:18:47 -08001887 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001888 auto clientDescriptor =
1889 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001890 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001891 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1892
1893 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001894 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001895
1896 if (evicted.size() > 0) {
1897 // This should never happen - clients should already have been removed in disconnect
1898 for (auto& i : evicted) {
1899 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001900 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001901 }
1902
1903 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1904 __FUNCTION__);
1905 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001906
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001907 if (flags::camera_multi_client()) {
1908 sp<BasicClient> clientSp = clientDescriptor->getValue();
1909 auto primaryClient = mActiveClientManager.getPrimaryClient(desc->getKey());
1910 if (primaryClient == nullptr) {
1911 // There is no primary client yet. Assign this first client as
1912 // primary
1913 clientSp->setPrimaryClient(true);
1914 } else {
1915 // There is already primary client. If the incoming client has a
1916 // higher priority than the existing primary, then assign incoming
1917 // client as primary and change the existing client to secondary.
1918 // Otherwise incoming client is secondary client.
1919 if (clientDescriptor->getPriority() <= primaryClient->getPriority()) {
1920 clientSp->setPrimaryClient(true);
1921 primaryClient->getValue()->setPrimaryClient(false);
1922 primaryClient->getValue()->notifyClientSharedAccessPriorityChanged(false);
1923 } else {
1924 clientSp->setPrimaryClient(false);
1925 }
1926 }
1927 }
1928
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001929 // And register a death notification for the client callback. Do
1930 // this last to avoid Binder policy where a nested Binder
1931 // transaction might be pre-empted to service the client death
1932 // notification if the client process dies before linkToDeath is
1933 // invoked.
1934 sp<IBinder> remoteCallback = client->getRemote();
1935 if (remoteCallback != nullptr) {
1936 remoteCallback->linkToDeath(this);
1937 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001938}
1939
Austin Borgered99f642023-06-01 16:51:35 -07001940status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1941 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1942 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001943 bool sharedMode,
Ruben Brunkcc776712015-02-17 20:18:47 -08001944 /*out*/
1945 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001946 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001947 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001948 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001949 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001950 DescriptorPtr clientDescriptor;
1951 {
1952 if (effectiveApiLevel == API_1) {
1953 // If we are using API1, any existing client for this camera ID with the same remote
1954 // should be returned rather than evicted to allow MediaRecorder to work properly.
1955
1956 auto current = mActiveClientManager.get(cameraId);
1957 if (current != nullptr) {
1958 auto clientSp = current->getValue();
1959 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001960 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001961 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001962 " API level, evicting prior client...");
1963 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001964 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001965 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001966 *client = clientSp;
1967 return NO_ERROR;
1968 }
1969 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001970 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001971 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001972
Ruben Brunkcc776712015-02-17 20:18:47 -08001973 // Get state for the given cameraId
1974 auto state = getCameraState(cameraId);
1975 if (state == nullptr) {
1976 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001977 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001978 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001979 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001980 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001981
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001982 sp<IServiceManager> sm = defaultServiceManager();
1983 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001984 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001985 // If processinfo service is not available and the client is automotive privileged
1986 // client used for safety critical uses cases such as rear-view and surround-view which
1987 // needs to be available before android boot completes, then use the hardcoded values
1988 // for the process state and priority score. As this scenario is before android system
1989 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1990 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1991 // visible on the top.
1992 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1993 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1994 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07001995 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient,
1996 sharedMode);
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001997 } else {
1998 // Get current active client PIDs
1999 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2000 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002001
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002002 std::vector<int> priorityScores(ownerPids.size());
2003 std::vector<int> states(ownerPids.size());
2004
2005 // Get priority scores of all active PIDs
2006 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2007 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2008 if (err != OK) {
2009 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2010 return err;
2011 }
2012
2013 // Update all active clients' priorities
2014 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2015 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2016 pidToPriorityMap.emplace(ownerPids[i],
2017 resource_policy::ClientPriority(priorityScores[i], states[i],
2018 /* isVendorClient won't get copied over*/ false,
2019 /* oomScoreOffset won't get copied over*/ 0));
2020 }
2021 mActiveClientManager.updatePriorities(pidToPriorityMap);
2022
2023 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2024 int32_t actualState = states[states.size() - 1];
2025
2026 // Make descriptor for incoming client. We store the oomScoreOffset
2027 // since we might need it later on new handleEvictionsLocked and
2028 // ProcessInfoService would not take that into account.
2029 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2030 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2031 state->getConflicting(), actualScore, clientPid, actualState,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002032 oomScoreOffset, systemNativeClient, sharedMode);
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002033 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002034
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002035 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2036
Ruben Brunkcc776712015-02-17 20:18:47 -08002037 // Find clients that would be evicted
2038 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2039
2040 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2041 // background, so we cannot do evictions
2042 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2043 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2044 " priority).", clientPid);
2045
2046 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002047 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002048 auto incompatibleClients =
2049 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2050
Austin Borgered99f642023-06-01 16:51:35 -07002051 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2052 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2053 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002054 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002055
2056 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002057 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002058 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002059 i->getKey().c_str(),
2060 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002061 i->getOwnerId(), i->getPriority().getScore(),
2062 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002063 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002064 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2065 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002066 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002067 }
2068
2069 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002070 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002071 mEventLog.add(msg);
2072
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002073 auto current = mActiveClientManager.get(cameraId);
2074 if (current != nullptr) {
2075 return -EBUSY; // CAMERA_IN_USE
2076 } else {
2077 return -EUSERS; // MAX_CAMERAS_IN_USE
2078 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002079 }
2080
2081 for (auto& i : evicted) {
2082 sp<BasicClient> clientSp = i->getValue();
2083 if (clientSp.get() == nullptr) {
2084 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2085
2086 // TODO: Remove this
2087 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2088 __FUNCTION__);
2089 mActiveClientManager.remove(i);
2090 continue;
2091 }
2092
2093 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002094 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002095 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002096
Ruben Brunkcc776712015-02-17 20:18:47 -08002097 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002098 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002099 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2100 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002101 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002102 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002103 i->getPriority().getState(), cameraId.c_str(),
2104 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002105 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002106
2107 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002108 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002109 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002110 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002111 }
2112
Ruben Brunkcc776712015-02-17 20:18:47 -08002113 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2114 // other clients from connecting in mServiceLockWrapper if held
2115 mServiceLock.unlock();
2116
2117 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002118 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002119
2120 // Destroy evicted clients
2121 for (auto& i : evictedClients) {
2122 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002123 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002124 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002125
Austin Borger22c5c852024-03-08 13:31:36 -08002126 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002127
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002128 for (const auto& i : evictedClients) {
2129 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002130 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002131 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2132 if (ret == TIMED_OUT) {
2133 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002134 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2135 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002136 return -EBUSY;
2137 }
2138 if (ret != NO_ERROR) {
2139 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002140 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2141 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002142 return ret;
2143 }
2144 }
2145
2146 evictedClients.clear();
2147
Ruben Brunkcc776712015-02-17 20:18:47 -08002148 // Once clients have been disconnected, relock
2149 mServiceLock.lock();
2150
2151 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2152 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2153 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002154 }
2155
Ruben Brunkcc776712015-02-17 20:18:47 -08002156 *partial = clientDescriptor;
2157 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002158}
2159
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002160Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002161 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002162 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002163 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002164 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002165 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002166 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002167 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002168 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002169 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002170 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002171 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002172
Austin Borger65e64642024-06-11 15:58:23 -07002173 std::string cameraIdStr =
2174 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002175 if (cameraIdStr.empty()) {
2176 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002177 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002178 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2179 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2180 }
malikakashedb38962023-09-06 00:03:35 +00002181
Austin Borger7d2b9232024-07-22 14:17:14 -07002182 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2183 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002184
Austin Borger95a00152024-09-23 17:20:24 -07002185 AttributionSourceState resolvedClientAttribution(clientAttribution);
2186 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraIdStr);
2187 if (!ret.isOk()) {
2188 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002189 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002190 toStdString(ret.toString8()));
2191 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002192 }
2193
Austin Borger95a00152024-09-23 17:20:24 -07002194 const int clientPid = resolvedClientAttribution.pid;
2195 const int clientUid = resolvedClientAttribution.uid;
2196 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2197
2198 logConnectionAttempt(clientPid, clientPackageName, cameraIdStr, API_1);
Austin Borgerb01a8702024-07-22 16:20:34 -07002199
Ruben Brunkcc776712015-02-17 20:18:47 -08002200 sp<Client> client = nullptr;
Austin Borger23694432024-10-07 19:28:01 -07002201 ret = connectHelper<ICameraClient, Client>(
2202 cameraClient, cameraIdStr, api1CameraId, resolvedClientAttribution,
2203 /*systemNativeClient*/ false, API_1,
2204 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, rotationOverride,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002205 forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*sharedMode*/false, /*out*/ client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002206
Biswarup Pal37a75182024-01-16 15:53:35 +00002207 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002208 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002209 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002210 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002211 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002212 }
2213
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002214 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002215
2216 const sp<IServiceManager> sm(defaultServiceManager());
2217 const auto& mActivityManager = getActivityManager();
2218 if (mActivityManager) {
2219 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002220 getCallingUid(),
2221 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002222 }
2223
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002224 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002225}
2226
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002227bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2228 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002229 // If the client is not a vendor client, don't add listener if
2230 // a) the camera is a publicly hidden secure camera OR
2231 // b) the camera is a system only camera and the client doesn't
2232 // have android.permission.SYSTEM_CAMERA permissions.
2233 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2234 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002235 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002236 return true;
2237 }
2238 return false;
2239}
2240
Austin Borgered99f642023-06-01 16:51:35 -07002241bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002242 // Rules for rejection:
2243 // 1) If cameraserver tries to access this camera device, accept the
2244 // connection.
2245 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002246 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002247 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2248 // and the serving thread is a non hwbinder thread, the client must have
2249 // android.permission.SYSTEM_CAMERA permissions to connect.
2250
Austin Borger22c5c852024-03-08 13:31:36 -08002251 int cPid = getCallingPid();
2252 int cUid = getCallingUid();
2253 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002254 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2255 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002256 // This isn't a known camera ID, so it's not a system camera
2257 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2258 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002259 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002260
2261 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002262 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002263 return false;
2264 }
2265 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002266 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002267 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2268 return true;
2269 }
2270 // (3) Here we only check for permissions if it is a system only camera device. This is since
2271 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2272 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2273 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002274 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002275 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002276 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2277 cameraId.c_str());
2278 return true;
2279 }
2280
2281 return false;
2282}
2283
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002284Status CameraService::connectDevice(
2285 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002286 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002287 int oomScoreOffset, int targetSdkVersion,
2288 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002289 bool sharedMode, /*out*/sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002290 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002291 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002292 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002293 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002294 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002295 int callingPid = getCallingPid();
2296 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002297 bool systemNativeClient = false;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002298 AttributionSourceState resolvedClientAttribution(clientAttribution);
Austin Borger7d2b9232024-07-22 14:17:14 -07002299 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002300 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002301 clientPackageNameMaybe = systemClient;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002302 // Pass in packageName since AttributionAndPermissionUtils can't resolve vndk clients.
2303 resolvedClientAttribution.packageName = clientPackageNameMaybe;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002304 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002305 }
Austin Borger249e6592024-03-10 22:28:11 -07002306
Austin Borger65e64642024-06-11 15:58:23 -07002307 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2308 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002309 if (!cameraIdOptional.has_value()) {
2310 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002311 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002312 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2313 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2314 }
2315 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002316
Austin Borger7d2b9232024-07-22 14:17:14 -07002317 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002318
Austin Borger2a3f9a72024-11-07 12:24:49 -08002319 if (!flags::data_delivery_permission_checks()) {
Austin Borger95a00152024-09-23 17:20:24 -07002320 resolvedClientAttribution.pid = USE_CALLING_PID;
2321 }
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002322
Austin Borger95a00152024-09-23 17:20:24 -07002323 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraId);
2324 if (!ret.isOk()) {
2325 logRejected(cameraId, getCallingPid(), clientAttribution.packageName.value_or(""),
2326 toStdString(ret.toString8()));
2327 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002328 }
2329
Austin Borger95a00152024-09-23 17:20:24 -07002330 const int clientPid = resolvedClientAttribution.pid;
2331 const int clientUid = resolvedClientAttribution.uid;
2332 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2333 userid_t clientUserId = multiuser_get_user_id(resolvedClientAttribution.uid);
Austin Borgerb01a8702024-07-22 16:20:34 -07002334
Austin Borger95a00152024-09-23 17:20:24 -07002335 logConnectionAttempt(clientPid, clientPackageName, cameraId, API_2);
Austin Borgerb01a8702024-07-22 16:20:34 -07002336
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002337 if (oomScoreOffset < 0) {
Austin Borger95a00152024-09-23 17:20:24 -07002338 std::string msg = fmt::sprintf(
2339 "Cannot increase the priority of a client %s pid %d for "
2340 "camera id %s",
2341 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002342 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2343 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002344 }
2345
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002346 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2347 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002348 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2349 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002350 std::string msg = "Camera disabled by device policy";
2351 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2352 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002353 }
2354
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002355 // enforce system camera permissions
Austin Borger95a00152024-09-23 17:20:24 -07002356 if (oomScoreOffset > 0 && !hasPermissionsForSystemCamera(cameraId, clientPid, callingUid) &&
2357 !isTrustedCallingUid(callingUid)) {
2358 std::string msg = fmt::sprintf(
2359 "Cannot change the priority of a client %s pid %d for "
2360 "camera id %s without SYSTEM_CAMERA permissions",
2361 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002362 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2363 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002364 }
2365
Austin Borger95a00152024-09-23 17:20:24 -07002366 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks, CameraDeviceClient>(
Austin Borger23694432024-10-07 19:28:01 -07002367 cameraCb, cameraId, /*api1CameraId*/ -1, resolvedClientAttribution, systemNativeClient,
2368 API_2, /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002369 /*forceSlowJpegMode*/ false, unresolvedCameraId, isNonSystemNdk, sharedMode,
2370 /*out*/ client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002371
Biswarup Pal37a75182024-01-16 15:53:35 +00002372 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002373 logRejected(cameraId, clientPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002374 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002375 }
2376
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002377 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002378 Mutex::Autolock lock(mServiceLock);
2379
2380 // Clear the previous cached logs and reposition the
2381 // file offset to beginning of the file to log new data.
2382 // If either truncate or lseek fails, close the previous file and create a new one.
2383 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2384 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2385 // Close the previous memfd.
2386 close(mMemFd);
2387 // If failure to wipe the data, then create a new file and
2388 // assign the new value to mMemFd.
2389 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2390 if (mMemFd == -1) {
2391 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2392 }
2393 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002394 const sp<IServiceManager> sm(defaultServiceManager());
2395 const auto& mActivityManager = getActivityManager();
2396 if (mActivityManager) {
2397 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002398 callingUid,
2399 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002400 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002401 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002402}
2403
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002404bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2405 int callingPid, int callingUid) {
2406 if (!isAutomotiveDevice()) {
2407 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2408 }
2409
2410 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2411 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2412 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2413 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2414 "using camera %s", callingUid, cam_id.c_str());
2415 return false;
2416 }
2417
2418 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2419 return true;
2420 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2421 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002422 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2423 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002424 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2425 return false;
2426 } else {
2427 return true;
2428 }
2429 }
2430 return false;
2431}
2432
Austin Borger7d2b9232024-07-22 14:17:14 -07002433void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
Austin Borger95a00152024-09-23 17:20:24 -07002434 const std::string& cameraId,
2435 apiLevel effectiveApiLevel) const {
Austin Borger7d2b9232024-07-22 14:17:14 -07002436 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borger95a00152024-09-23 17:20:24 -07002437 "Camera API version %d",
2438 clientPid, clientPackageName.c_str(), cameraId.c_str(),
2439 static_cast<int>(effectiveApiLevel));
Austin Borger7d2b9232024-07-22 14:17:14 -07002440}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002441
Austin Borger23694432024-10-07 19:28:01 -07002442template <class CALLBACK, class CLIENT>
Austin Borger7d2b9232024-07-22 14:17:14 -07002443Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
Austin Borger23694432024-10-07 19:28:01 -07002444 int api1CameraId,
2445 const AttributionSourceState& clientAttribution,
2446 bool systemNativeClient, apiLevel effectiveApiLevel,
2447 bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2448 int rotationOverride, bool forceSlowJpegMode,
2449 const std::string& originalCameraId, bool isNonSystemNdk,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002450 bool sharedMode, /*out*/ sp<CLIENT>& device) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002451 binder::Status ret = binder::Status::ok();
2452
Shuzhen Wang316781a2020-08-18 18:11:01 -07002453 nsecs_t openTimeNs = systemTime();
2454
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002455 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002456 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002457 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002458
Austin Borger23694432024-10-07 19:28:01 -07002459 const std::string clientPackageName =
2460 clientAttribution.packageName.value_or(kUnknownPackageName);
2461
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002462 {
2463 // Acquire mServiceLock and prevent other clients from connecting
2464 std::unique_ptr<AutoConditionLock> lock =
2465 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2466
2467 if (lock == nullptr) {
Austin Borger23694432024-10-07 19:28:01 -07002468 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting).",
2469 clientAttribution.pid);
2470 return STATUS_ERROR_FMT(
2471 ERROR_MAX_CAMERAS_IN_USE,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002472 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borger23694432024-10-07 19:28:01 -07002473 cameraId.c_str(), clientPackageName.c_str(), clientAttribution.pid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002474 }
2475
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002476 // Enforce client permissions and do basic validity checks
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002477 if (!(ret = validateConnectLocked(cameraId, clientAttribution, sharedMode)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002478 return ret;
2479 }
2480
2481 // Check the shim parameters after acquiring lock, if they have already been updated and
2482 // we were doing a shim update, return immediately
2483 if (shimUpdateOnly) {
2484 auto cameraState = getCameraState(cameraId);
2485 if (cameraState != nullptr) {
2486 if (!cameraState->getShimParams().isEmpty()) return ret;
2487 }
2488 }
2489
2490 status_t err;
2491
2492 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002493 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger23694432024-10-07 19:28:01 -07002494 if ((err = handleEvictionsLocked(
2495 cameraId, clientAttribution.pid, effectiveApiLevel,
2496 IInterface::asBinder(cameraCb),
2497 clientAttribution.packageName.value_or(kUnknownPackageName), oomScoreOffset,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002498 systemNativeClient, sharedMode, /*out*/ &clientTmp,
Austin Borger23694432024-10-07 19:28:01 -07002499 /*out*/ &partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002500 switch (err) {
2501 case -ENODEV:
2502 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2503 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002504 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002505 case -EBUSY:
2506 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2507 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002508 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002509 case -EUSERS:
2510 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2511 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002512 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002513 default:
2514 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2515 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002516 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002517 }
2518 }
2519
2520 if (clientTmp.get() != nullptr) {
2521 // Handle special case for API1 MediaRecorder where the existing client is returned
2522 device = static_cast<CLIENT*>(clientTmp.get());
2523 return ret;
2524 }
2525
2526 // give flashlight a chance to close devices if necessary.
2527 mFlashlight->prepareDeviceOpen(cameraId);
2528
Austin Borger18b30a72022-10-27 12:20:29 -07002529 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002530 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002531 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002532 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002533 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002534 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002535 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002536 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002537 }
2538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002539 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002540 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002541 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002542
Austin Borger6e831c42024-07-22 13:07:56 -07002543 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2544 // that's connected to camera service directly.
Austin Borger2e772b82024-10-11 16:09:57 -07002545 if (!(ret = makeClient(this, cameraCb, clientAttribution, getCallingPid(),
2546 systemNativeClient, cameraId, api1CameraId, facing, orientation,
2547 getpid(), deviceVersionAndTransport, effectiveApiLevel,
2548 overrideForPerfClass, rotationOverride, forceSlowJpegMode,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002549 originalCameraId, sharedMode,
Austin Borger23694432024-10-07 19:28:01 -07002550 /*out*/ &tmp))
2551 .isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002552 return ret;
2553 }
2554 client = static_cast<CLIENT*>(tmp.get());
2555
2556 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2557 __FUNCTION__);
2558
Austin Borgered99f642023-06-01 16:51:35 -07002559 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002560 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002561 if (err != OK) {
2562 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002563 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002564 mServiceLock.unlock();
2565 client->disconnect();
2566 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002567 switch(err) {
2568 case BAD_VALUE:
2569 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002570 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002571 case -EBUSY:
2572 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002573 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002574 case -EUSERS:
2575 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2576 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002577 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002578 case PERMISSION_DENIED:
2579 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002580 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002581 case -EACCES:
2582 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002583 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002584 case -ENODEV:
2585 default:
2586 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002587 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002588 strerror(-err), err);
2589 }
2590 }
2591
2592 // Update shim paremeters for legacy clients
2593 if (effectiveApiLevel == API_1) {
2594 // Assume we have always received a Client subclass for API1
2595 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2596 String8 rawParams = shimClient->getParameters();
2597 CameraParameters params(rawParams);
2598
2599 auto cameraState = getCameraState(cameraId);
2600 if (cameraState != nullptr) {
2601 cameraState->setShimParams(params);
2602 } else {
2603 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002604 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002605 }
2606 }
2607
Ravneetaeb20dc2022-03-30 05:33:03 +00002608 // Enable/disable camera service watchdog
2609 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2610
Emilian Peev6d45db82024-01-18 20:11:54 +00002611 CameraMetadata chars;
2612 bool rotateAndCropSupported = true;
2613 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002614 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002615 if (err == OK) {
2616 auto availableRotateCropEntry = chars.find(
2617 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2618 if (availableRotateCropEntry.count <= 1) {
2619 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002620 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002621 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002622 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2623 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002624 }
2625
Emilian Peev6d45db82024-01-18 20:11:54 +00002626 if (rotateAndCropSupported) {
2627 // Set rotate-and-crop override behavior
2628 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2629 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002630 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2631 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002632 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2633 switch (portraitRotation) {
2634 case 90:
2635 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2636 break;
2637 case 180:
2638 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2639 break;
2640 case 270:
2641 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2642 break;
2643 default:
2644 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2645 break;
2646 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002647 // Here we're communicating to the client the chosen rotate
2648 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002649 client->setRotateAndCropOverride(rotateAndCropMode);
2650 } else {
2651 client->setRotateAndCropOverride(
Austin Borger23694432024-10-07 19:28:01 -07002652 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2653 clientPackageName, facing,
2654 multiuser_get_user_id(clientAttribution.uid)));
Emilian Peev6d45db82024-01-18 20:11:54 +00002655 }
2656 }
2657
2658 bool autoframingSupported = true;
2659 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2660 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2661 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2662 autoframingSupported = false;
2663 }
2664
2665 if (autoframingSupported) {
2666 // Set autoframing override behaviour
2667 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2668 client->setAutoframingOverride(mOverrideAutoframingMode);
2669 } else {
2670 client->setAutoframingOverride(
2671 mCameraServiceProxyWrapper->getAutoframingOverride(
2672 clientPackageName));
2673 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002674 }
2675
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002676 bool isCameraPrivacyEnabled;
2677 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002678 // Set camera muting behavior.
Austin Borger23694432024-10-07 19:28:01 -07002679 isCameraPrivacyEnabled =
2680 this->isCameraPrivacyEnabled(toString16(client->getPackageName()), cameraId,
2681 clientAttribution.pid, clientAttribution.uid);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002682 } else {
2683 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002684 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002685 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002686
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002687 if (client->supportsCameraMute()) {
2688 client->setCameraMute(
2689 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2690 } else if (isCameraPrivacyEnabled) {
2691 // no camera mute supported, but privacy is on! => disconnect
2692 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2693 client->getPackageName().c_str(), cameraId.c_str());
2694 // Do not hold mServiceLock while disconnecting clients, but
2695 // retain the condition blocking other clients from connecting
2696 // in mServiceLockWrapper if held.
2697 mServiceLock.unlock();
2698 // Clear caller identity temporarily so client disconnect PID
2699 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002700 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002701 // Note AppOp to trigger the "Unblock" dialog
2702 client->noteAppOp();
2703 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002704 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002705 // Reacquire mServiceLock
2706 mServiceLock.lock();
2707
2708 return STATUS_ERROR_FMT(ERROR_DISABLED,
2709 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002710 }
2711
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002712 if (shimUpdateOnly) {
2713 // If only updating legacy shim parameters, immediately disconnect client
2714 mServiceLock.unlock();
2715 client->disconnect();
2716 mServiceLock.lock();
2717 } else {
2718 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002719 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002720 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002721
2722 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002723 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002724 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002725 } // lock is destroyed, allow further connect calls
2726
2727 // Important: release the mutex here so the client can call back into the service from its
2728 // destructor (can be at the end of the call)
2729 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002730
2731 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002732 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002733 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002734
Cliff Wud3a05312021-04-26 23:07:31 +08002735 {
2736 Mutex::Autolock lock(mInjectionParametersLock);
2737 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2738 mInjectionInitPending = false;
2739 status_t res = NO_ERROR;
2740 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2741 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002742 sp<BasicClient> clientSp = clientDescriptor->getValue();
2743 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2744 if(res != OK) {
2745 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2746 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002747 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002748 }
2749 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002750 if (res != OK) {
2751 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2752 }
2753 } else {
2754 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002755 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002756 res = NO_INIT;
2757 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2758 }
2759 }
2760 }
2761
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002762 return ret;
2763}
2764
Austin Borgered99f642023-06-01 16:51:35 -07002765status_t CameraService::addOfflineClient(const std::string &cameraId,
2766 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002767 if (offlineClient.get() == nullptr) {
2768 return BAD_VALUE;
2769 }
2770
2771 {
2772 // Acquire mServiceLock and prevent other clients from connecting
2773 std::unique_ptr<AutoConditionLock> lock =
2774 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2775
2776 if (lock == nullptr) {
2777 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
Austin Borger2e772b82024-10-11 16:09:57 -07002778 , __FUNCTION__, offlineClient->getClientCallingPid());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002779 return TIMED_OUT;
2780 }
2781
2782 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2783 if (onlineClientDesc.get() == nullptr) {
2784 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2785 cameraId.c_str());
2786 return BAD_VALUE;
2787 }
2788
2789 // Offline clients do not evict or conflict with other online devices. Resource sharing
2790 // conflicts are handled by the camera provider which will either succeed or fail before
2791 // reaching this method.
2792 const auto& onlinePriority = onlineClientDesc->getPriority();
2793 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2794 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002795 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002796 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002797 // native clients don't have offline processing support.
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07002798 /*ommScoreOffset*/ 0, /*systemNativeClient*/false, /*sharedMode*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002799 if (offlineClientDesc == nullptr) {
2800 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2801 return BAD_VALUE;
2802 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002803
2804 // Allow only one offline device per camera
2805 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2806 if (!incompatibleClients.empty()) {
2807 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2808 return BAD_VALUE;
2809 }
2810
Austin Borgered99f642023-06-01 16:51:35 -07002811 std::string monitorTags = isClientWatched(offlineClient.get())
2812 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002813 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002814 if (err != OK) {
2815 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2816 return err;
2817 }
2818
2819 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2820 if (evicted.size() > 0) {
2821 for (auto& i : evicted) {
2822 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002823 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002824 }
2825
2826 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2827 "properly", __FUNCTION__);
2828
2829 return BAD_VALUE;
2830 }
2831
2832 logConnectedOffline(offlineClientDesc->getKey(),
2833 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002834 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002835
2836 sp<IBinder> remoteCallback = offlineClient->getRemote();
2837 if (remoteCallback != nullptr) {
2838 remoteCallback->linkToDeath(this);
2839 }
2840 } // lock is destroyed, allow further connect calls
2841
2842 return OK;
2843}
2844
Austin Borgered99f642023-06-01 16:51:35 -07002845Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002846 int32_t torchStrength, const sp<IBinder>& clientBinder,
2847 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002848 Mutex::Autolock lock(mServiceLock);
2849
2850 ATRACE_CALL();
2851 if (clientBinder == nullptr) {
2852 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2853 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2854 "Torch client binder in null.");
2855 }
2856
Austin Borger22c5c852024-03-08 13:31:36 -08002857 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002858 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2859 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002860 if (!cameraIdOptional.has_value()) {
2861 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002862 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002863 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2864 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2865 }
2866 std::string cameraId = cameraIdOptional.value();
2867
Austin Borgered99f642023-06-01 16:51:35 -07002868 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002869 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002870 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002871 }
2872
2873 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002874 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002875 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002876 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002878 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002879 }
2880
2881 StatusInternal cameraStatus = state->getStatus();
2882 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2883 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002884 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002885 (int)cameraStatus);
2886 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002887 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002888 }
2889
2890 {
2891 Mutex::Autolock al(mTorchStatusMutex);
2892 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002893 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002894 if (err != OK) {
2895 if (err == NAME_NOT_FOUND) {
2896 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002897 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002898 }
2899 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002900 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002901 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2902 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002903 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002904 }
2905
2906 if (status == TorchModeStatus::NOT_AVAILABLE) {
2907 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2908 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002909 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002910 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2911 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002912 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002913 } else {
2914 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002915 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002916 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2917 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002918 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002919 }
2920 }
2921 }
2922
2923 {
2924 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002925 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002926 }
2927 // Check if the current torch strength level is same as the new one.
2928 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002929 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002930
Austin Borgered99f642023-06-01 16:51:35 -07002931 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002932
2933 if (err != OK) {
2934 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002935 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002936 switch (err) {
2937 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002938 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2939 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002940 errorCode = ERROR_ILLEGAL_ARGUMENT;
2941 break;
2942 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002943 msg = fmt::sprintf("Camera \"%s\" is in use",
2944 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002945 errorCode = ERROR_CAMERA_IN_USE;
2946 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002947 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002948 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002949 "valid range.", torchStrength);
2950 errorCode = ERROR_ILLEGAL_ARGUMENT;
2951 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002952 default:
Austin Borgered99f642023-06-01 16:51:35 -07002953 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002954 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002955 }
Austin Borgered99f642023-06-01 16:51:35 -07002956 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2957 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002958 }
2959
2960 {
2961 // update the link to client's death
2962 // Store the last client that turns on each camera's torch mode.
2963 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002964 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002965 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002966 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002967 } else {
2968 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2969 mTorchClientMap.replaceValueAt(index, clientBinder);
2970 }
2971 clientBinder->linkToDeath(this);
2972 }
2973
Austin Borger22c5c852024-03-08 13:31:36 -08002974 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002975 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002976 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002977 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002978 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002979 }
2980 return Status::ok();
2981}
2982
malikakash73125c62023-07-21 22:44:34 +00002983Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002984 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2985 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002986 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002987
2988 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002989 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002990 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002991 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2992 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002993 }
2994
Austin Borger22c5c852024-03-08 13:31:36 -08002995 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002996 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2997 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002998 if (!cameraIdOptional.has_value()) {
2999 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003000 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00003001 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3002 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3003 }
3004 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003005
Austin Borgered99f642023-06-01 16:51:35 -07003006 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003007 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003008 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003009 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003010 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003011 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003012 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003013 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003014 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003015 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003016 }
3017
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003018 StatusInternal cameraStatus = state->getStatus();
3019 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003020 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003021 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3022 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003023 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003024 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003025 }
3026
3027 {
3028 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003029 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003030 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003031 if (err != OK) {
3032 if (err == NAME_NOT_FOUND) {
3033 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003034 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003035 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003036 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003037 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003038 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003039 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003040 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003041 }
3042
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003043 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003044 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003045 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003046 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003047 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3048 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003049 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003050 } else {
3051 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003052 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003053 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3054 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003055 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003056 }
3057 }
3058 }
3059
Ruben Brunk99e69712015-05-26 17:25:07 -07003060 {
3061 // Update UID map - this is used in the torch status changed callbacks, so must be done
3062 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003063 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003064 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003065 }
3066
Austin Borgered99f642023-06-01 16:51:35 -07003067 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003068
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003069 if (err != OK) {
3070 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003071 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003072 switch (err) {
3073 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003074 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3075 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003076 errorCode = ERROR_ILLEGAL_ARGUMENT;
3077 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003078 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003079 msg = fmt::sprintf("Camera \"%s\" is in use",
3080 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003081 errorCode = ERROR_CAMERA_IN_USE;
3082 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003083 default:
Austin Borgered99f642023-06-01 16:51:35 -07003084 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003085 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003086 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003087 errorCode = ERROR_INVALID_OPERATION;
3088 }
Austin Borgered99f642023-06-01 16:51:35 -07003089 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3090 logServiceError(msg, errorCode);
3091 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003092 }
3093
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003094 {
3095 // update the link to client's death
3096 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003097 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003098 if (enabled) {
3099 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003100 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003101 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003102 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003103 mTorchClientMap.replaceValueAt(index, clientBinder);
3104 }
3105 clientBinder->linkToDeath(this);
3106 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003107 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003108 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003109 }
3110
Austin Borger22c5c852024-03-08 13:31:36 -08003111 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003112 std::string torchState = enabled ? "on" : "off";
3113 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3114 torchState.c_str(), clientPid);
3115 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003116 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003117}
3118
Austin Borgered99f642023-06-01 16:51:35 -07003119void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3120 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3121 mTorchUidMap[cameraId].first = uid;
3122 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003123 } else {
3124 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003125 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003126 }
3127}
3128
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003129Status CameraService::notifySystemEvent(int32_t eventId,
3130 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003131 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003132 const int selfPid = getpid();
3133
3134 // Permission checks
3135 if (pid != selfPid) {
3136 // Ensure we're being called by system_server, or similar process with
3137 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003138 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003139 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003140 ALOGE("Permission Denial: cannot send updates to camera service about system"
3141 " events from pid=%d, uid=%d", pid, uid);
3142 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003143 "No permission to send updates to camera service about system events"
3144 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003145 }
3146 }
3147
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003148 ATRACE_CALL();
3149
Ruben Brunk36597b22015-03-20 22:15:57 -07003150 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003151 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003152 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003153 // from a system server crash
3154 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003155 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003156 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003157 break;
3158 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003159 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3160 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003161 if (args.size() != 1) {
3162 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3163 "USB Device Event requires 1 argument");
3164 }
3165
Valentin Iftime29e2e152021-08-13 15:17:33 +02003166 // Notify CameraProviderManager for lazy HALs
3167 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3168 std::to_string(args[0]));
3169 break;
3170 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003171 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003172 default: {
3173 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3174 eventId);
3175 break;
3176 }
3177 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003178 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003179}
3180
Emilian Peev53722fa2019-02-22 17:47:20 -08003181void CameraService::notifyMonitoredUids() {
3182 Mutex::Autolock lock(mStatusListenerLock);
3183
3184 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003185 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003186 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3187 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003188 }
3189}
3190
Austin Borgerdddb7552023-03-30 17:53:01 -07003191void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3192 Mutex::Autolock lock(mStatusListenerLock);
3193
3194 for (const auto& it : mListenerList) {
3195 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3196 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3197 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3198 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3199 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3200 }
3201 }
3202}
3203
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003204Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003205 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003206 const int selfPid = getpid();
3207
3208 // Permission checks
3209 if (pid != selfPid) {
3210 // Ensure we're being called by system_server, or similar process with
3211 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003212 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003213 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003214 ALOGE("Permission Denial: cannot send updates to camera service about device"
3215 " state changes from pid=%d, uid=%d", pid, uid);
3216 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3217 "No permission to send updates to camera service about device state"
3218 " changes from pid=%d, uid=%d", pid, uid);
3219 }
3220 }
3221
3222 ATRACE_CALL();
3223
Austin Borger18b30a72022-10-27 12:20:29 -07003224 {
3225 Mutex::Autolock lock(mServiceLock);
3226 mDeviceState = newState;
3227 }
3228
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003229 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003230
3231 return Status::ok();
3232}
3233
Emilian Peev8b64f282021-03-25 16:49:57 -07003234Status CameraService::notifyDisplayConfigurationChange() {
3235 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003236 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003237 const int selfPid = getpid();
3238
3239 // Permission checks
3240 if (callingPid != selfPid) {
3241 // Ensure we're being called by system_server, or similar process with
3242 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003243 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003244 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003245 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3246 " changes from pid=%d, uid=%d", callingPid, uid);
3247 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3248 "No permission to send updates to camera service about orientation"
3249 " changes from pid=%d, uid=%d", callingPid, uid);
3250 }
3251 }
3252
3253 Mutex::Autolock lock(mServiceLock);
3254
3255 // Don't do anything if rotate-and-crop override via cmd is active
3256 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3257
3258 const auto clients = mActiveClientManager.getAll();
3259 for (auto& current : clients) {
3260 if (current != nullptr) {
3261 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003262 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3263 basicClient->setRotateAndCropOverride(
3264 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3265 basicClient->getPackageName(),
3266 basicClient->getCameraFacing(),
3267 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003268 }
3269 }
3270 }
3271
3272 return Status::ok();
3273}
3274
3275Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003276 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3277 ATRACE_CALL();
3278 if (!concurrentCameraIds) {
3279 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3280 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3281 }
3282
3283 if (!mInitialized) {
3284 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003285 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003286 return STATUS_ERROR(ERROR_DISCONNECTED,
3287 "Camera subsystem is not available");
3288 }
3289 // First call into the provider and get the set of concurrent camera
3290 // combinations
3291 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003292 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003293 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003294 std::vector<std::pair<std::string, int32_t>> validCombination;
3295 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003296 for (auto &cameraId : combination) {
3297 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003298 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003299 if (state == nullptr) {
3300 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3301 continue;
3302 }
3303 StatusInternal status = state->getStatus();
3304 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3305 continue;
3306 }
Austin Borgered99f642023-06-01 16:51:35 -07003307 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003308 continue;
3309 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003310 auto [cameraOwnerDeviceId, mappedCameraId] =
3311 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3312 if (firstDeviceId == kInvalidDeviceId) {
3313 firstDeviceId = cameraOwnerDeviceId;
3314 } else if (firstDeviceId != cameraOwnerDeviceId) {
3315 // Found an invalid combination which contains cameras with different device id's,
3316 // hence discard it.
3317 validCombination.clear();
3318 break;
3319 }
3320 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003321 }
3322 if (validCombination.size() != 0) {
3323 concurrentCameraIds->push_back(std::move(validCombination));
3324 }
3325 }
3326 return Status::ok();
3327}
3328
3329Status CameraService::isConcurrentSessionConfigurationSupported(
3330 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003331 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003332 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003333 if (!isSupported) {
3334 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3335 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3336 }
3337
3338 if (!mInitialized) {
3339 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3340 return STATUS_ERROR(ERROR_DISCONNECTED,
3341 "Camera subsystem is not available");
3342 }
3343
Biswarup Pal7d072862024-04-17 15:24:47 +00003344 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3345 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003346 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3347 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003348 if (!cameraIdOptional.has_value()) {
3349 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003350 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003351 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3352 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3353 }
3354 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3355 }
3356
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003357 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003358 int callingPid = getCallingPid();
3359 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003360 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003361 hasPermissionsForCamera(callingPid, callingUid,
3362 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003363 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003364 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003365 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3366 "android.permission.CAMERA needed to call"
3367 "isConcurrentSessionConfigurationSupported");
3368 }
3369
3370 status_t res =
3371 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003372 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3373 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003374 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003375 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003376 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003377 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3378 "support %s (%d)", strerror(-res), res);
3379 }
3380 return Status::ok();
3381}
3382
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003383Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3384 /*out*/
3385 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003386 return addListenerHelper(listener, cameraStatuses);
3387}
3388
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003389binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3390 std::vector<hardware::CameraStatus>* cameraStatuses) {
3391 return addListenerHelper(listener, cameraStatuses, false, true);
3392}
3393
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003394Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3395 /*out*/
3396 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003397 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003398 ATRACE_CALL();
3399
Igor Murashkinbfc99152013-02-27 12:55:20 -08003400 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003401
Ruben Brunk3450ba72015-06-16 11:00:37 -07003402 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003403 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003404 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003405 }
3406
Austin Borger22c5c852024-03-08 13:31:36 -08003407 auto clientPid = getCallingPid();
3408 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003409 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003410
Igor Murashkinbfc99152013-02-27 12:55:20 -08003411 Mutex::Autolock lock(mServiceLock);
3412
Ruben Brunkcc776712015-02-17 20:18:47 -08003413 {
3414 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003415 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003416 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003417 ALOGW("%s: Tried to add listener %p which was already subscribed",
3418 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003419 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003420 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003421 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003422
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003423 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003424 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3425 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003426 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003427 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003428 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003429 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003430 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3431 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3432 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003433 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003434 // The listener still needs to be added to the list of listeners, regardless of what
3435 // permissions the listener process has / whether it is a vendor listener. Since it might be
3436 // eligible to listen to other camera ids.
3437 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003438 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003439 }
3440
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003441 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003442 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003443 Mutex::Autolock lock(mCameraStatesLock);
3444 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003445 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3446 auto [deviceId, mappedCameraId] =
3447 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3448
3449 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003450 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003451 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3452 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003453 }
3454 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003455 // Remove the camera statuses that should be hidden from the client, we do
3456 // this after collecting the states in order to avoid holding
3457 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3458 // the same time.
3459 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3460 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003461 std::string cameraId = s.cameraId;
3462 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003463 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003464 if (!cameraIdOptional.has_value()) {
3465 std::string msg =
3466 fmt::sprintf(
3467 "Camera %s: Invalid camera id for device id %d",
3468 s.cameraId.c_str(), s.deviceId);
3469 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3470 return true;
3471 }
3472 cameraId = cameraIdOptional.value();
3473 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3474 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3475 ALOGE("%s: Invalid camera id %s, skipping status update",
3476 __FUNCTION__, s.cameraId.c_str());
3477 return true;
3478 }
3479 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3480 clientUid);
3481 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003482
Biswarup Pal37a75182024-01-16 15:53:35 +00003483 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003484 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003485 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003486 // Add only default device cameras here, as virtual cameras currently don't support torch
3487 // anyway. Note that this is a simplification of the implementation here, and we should
3488 // change this when virtual cameras support torch.
3489 if (s.deviceId == kDefaultDeviceId) {
3490 idsChosenForCallback.insert(s.cameraId);
3491 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003492 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003493
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003494 /*
3495 * Immediately signal current torch status to this listener only
3496 * This may be a subset of all the devices, so don't include it in the response directly
3497 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003498 {
3499 Mutex::Autolock al(mTorchStatusMutex);
3500 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003501 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003502 // The camera id is visible to the client. Fine to send torch
3503 // callback.
3504 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003505 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3506 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003507 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003508 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003509 }
3510
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003511 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003512}
Ruben Brunkcc776712015-02-17 20:18:47 -08003513
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003514Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003515 ATRACE_CALL();
3516
Igor Murashkinbfc99152013-02-27 12:55:20 -08003517 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3518
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003519 if (listener == 0) {
3520 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003521 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003522 }
3523
Igor Murashkinbfc99152013-02-27 12:55:20 -08003524 Mutex::Autolock lock(mServiceLock);
3525
Ruben Brunkcc776712015-02-17 20:18:47 -08003526 {
3527 Mutex::Autolock lock(mStatusListenerLock);
3528 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003529 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003530 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003531 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003532 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003533 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003534 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003535 }
3536 }
3537
3538 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3539 __FUNCTION__, listener.get());
3540
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003541 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003542}
3543
Austin Borgered99f642023-06-01 16:51:35 -07003544Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003545
3546 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003547 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3548
3549 if (parameters == NULL) {
3550 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003551 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003552 }
3553
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003554 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003555
3556 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003557 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003558 // Error logged by caller
3559 return ret;
3560 }
3561
3562 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003563
Austin Borgered99f642023-06-01 16:51:35 -07003564 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003565
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003566 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003567}
3568
malikakash98260df2024-05-10 23:33:57 +00003569Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003570 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003571 ATRACE_CALL();
3572
Austin Borgered99f642023-06-01 16:51:35 -07003573 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003574
3575 switch (apiVersion) {
3576 case API_VERSION_1:
3577 case API_VERSION_2:
3578 break;
3579 default:
Austin Borgered99f642023-06-01 16:51:35 -07003580 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3581 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3582 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003583 }
3584
Austin Borger18b30a72022-10-27 12:20:29 -07003585 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003586 auto deviceVersionAndTransport =
3587 getDeviceVersion(cameraId,
3588 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3589 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003590 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003591 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3592 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3593 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003594 }
3595 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3596 int deviceVersion = deviceVersionAndTransport.first;
3597 switch (deviceVersion) {
3598 case CAMERA_DEVICE_API_VERSION_1_0:
3599 case CAMERA_DEVICE_API_VERSION_3_0:
3600 case CAMERA_DEVICE_API_VERSION_3_1:
3601 if (apiVersion == API_VERSION_2) {
3602 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003603 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003604 *isSupported = false;
3605 } else { // if (apiVersion == API_VERSION_1) {
3606 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003607 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003608 *isSupported = true;
3609 }
3610 break;
3611 case CAMERA_DEVICE_API_VERSION_3_2:
3612 case CAMERA_DEVICE_API_VERSION_3_3:
3613 case CAMERA_DEVICE_API_VERSION_3_4:
3614 case CAMERA_DEVICE_API_VERSION_3_5:
3615 case CAMERA_DEVICE_API_VERSION_3_6:
3616 case CAMERA_DEVICE_API_VERSION_3_7:
3617 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003618 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003619 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003620 break;
3621 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003622 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3623 deviceVersion, cameraId.c_str());
3624 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3625 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003626 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003627 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003628 } else {
3629 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003630 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003631 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003632}
3633
malikakash98260df2024-05-10 23:33:57 +00003634Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003635 /*out*/ bool *isSupported) {
3636 ATRACE_CALL();
3637
Austin Borgered99f642023-06-01 16:51:35 -07003638 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3639 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003640
3641 return Status::ok();
3642}
3643
Cliff Wud8cae102021-03-11 01:37:42 +08003644Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003645 const std::string& packageName, const std::string& internalCamId,
3646 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003647 const sp<ICameraInjectionCallback>& callback,
3648 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003649 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003650 ATRACE_CALL();
3651
Austin Borgered99f642023-06-01 16:51:35 -07003652 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003653 const int pid = getCallingPid();
3654 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003655 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3656 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003657 "Permission Denial: no permission to inject camera");
3658 }
3659
3660 // Do not allow any camera injection that injects or replaces a virtual camera.
3661 auto [deviceIdForInternalCamera, _] =
3662 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3663 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3664 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3665 "Cannot replace a virtual camera");
3666 }
3667 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3668 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3669 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3670 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3671 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003672 }
3673
3674 ALOGV(
3675 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3676 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003677 __FUNCTION__, packageName.c_str(),
3678 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003679
Cliff Wud3a05312021-04-26 23:07:31 +08003680 {
3681 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003682 mInjectionInternalCamId = internalCamId;
3683 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003684 mInjectionStatusListener->addListener(callback);
3685 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003686 status_t res = NO_ERROR;
3687 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3688 // If the client already exists, we can directly connect to the camera device through the
3689 // client's injectCamera(), otherwise we need to wait until the client is established
3690 // (execute connectHelper()) before injecting the camera to the camera device.
3691 if (clientDescriptor != nullptr) {
3692 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003693 sp<BasicClient> clientSp = clientDescriptor->getValue();
3694 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3695 if(res != OK) {
3696 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3697 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003698 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003699 }
3700 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003701 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003702 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3703 }
3704 } else {
3705 mInjectionInitPending = true;
3706 }
3707 }
Cliff Wud8cae102021-03-11 01:37:42 +08003708
Cliff Wud3a05312021-04-26 23:07:31 +08003709 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003710}
3711
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003712Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003713 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003714 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3715 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3716 return Status::ok();
3717}
3718
Ruben Brunkcc776712015-02-17 20:18:47 -08003719void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003720 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003721 for (auto& i : mActiveClientManager.getAll()) {
3722 auto clientSp = i->getValue();
3723 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003724 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003725 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003726 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003727 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003728 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003729}
3730
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003731bool CameraService::isOnlyClient(const BasicClient* client) {
3732 Mutex::Autolock lock(mServiceLock);
3733 bool ret = true;
3734 if (!flags::camera_multi_client()) {
3735 return ret;
3736 }
3737 if (client != nullptr) {
3738 std::string camId = client->mCameraIdStr;
3739 for (const auto& i : mActiveClientManager.getAll()) {
3740 auto clientSp = i->getValue();
3741 auto curCamId = i->getKey();
3742 if (!curCamId.compare(camId) && clientSp.get() != client) {
3743 return false;
3744 }
3745 }
3746 }
3747 return ret;
3748}
3749
Ruben Brunkcc776712015-02-17 20:18:47 -08003750bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003751 bool ret = false;
3752 {
3753 // Acquire mServiceLock and prevent other clients from connecting
3754 std::unique_ptr<AutoConditionLock> lock =
3755 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003756
Ruben Brunkcc776712015-02-17 20:18:47 -08003757 std::vector<sp<BasicClient>> evicted;
3758 for (auto& i : mActiveClientManager.getAll()) {
3759 auto clientSp = i->getValue();
3760 if (clientSp.get() == nullptr) {
3761 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3762 mActiveClientManager.remove(i);
3763 continue;
3764 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003765 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003766 mActiveClientManager.remove(i);
3767 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003768
Ruben Brunkcc776712015-02-17 20:18:47 -08003769 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003770 clientSp->notifyError(
3771 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003772 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003773 }
3774 }
3775
Ruben Brunkcc776712015-02-17 20:18:47 -08003776 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3777 // other clients from connecting in mServiceLockWrapper if held
3778 mServiceLock.unlock();
3779
Ruben Brunk36597b22015-03-20 22:15:57 -07003780 // Do not clear caller identity, remote caller should be client proccess
3781
Ruben Brunkcc776712015-02-17 20:18:47 -08003782 for (auto& i : evicted) {
3783 if (i.get() != nullptr) {
3784 i->disconnect();
3785 ret = true;
3786 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003787 }
3788
Ruben Brunkcc776712015-02-17 20:18:47 -08003789 // Reacquire mServiceLock
3790 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003791
Ruben Brunkcc776712015-02-17 20:18:47 -08003792 } // lock is destroyed, allow further connect calls
3793
3794 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003795}
3796
Ruben Brunkcc776712015-02-17 20:18:47 -08003797std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003798 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003799 std::shared_ptr<CameraState> state;
3800 {
3801 Mutex::Autolock lock(mCameraStatesLock);
3802 auto iter = mCameraStates.find(cameraId);
3803 if (iter != mCameraStates.end()) {
3804 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003805 }
3806 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003807 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003808}
3809
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003810std::vector<sp<CameraService::BasicClient>> CameraService::removeClientsLocked(
3811 const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003812 // Remove from active clients list
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003813 std::vector<sp<CameraService::BasicClient>> clients;
Jyoti Bhayana1a586fd2024-11-20 19:54:35 -08003814 if (flags::camera_multi_client()) {
3815 std::vector<CameraService::DescriptorPtr> clientDescriptors;
3816 clientDescriptors = mActiveClientManager.removeAll(cameraId);
3817 for (const auto& clientDescriptorPtr : clientDescriptors) {
3818 if (clientDescriptorPtr != nullptr) {
3819 sp<BasicClient> client = clientDescriptorPtr->getValue();
3820 if (client.get() != nullptr) {
3821 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3822 clients.push_back(client);
3823 }
3824 }
3825 }
3826 } else {
3827 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3828 if (clientDescriptorPtr == nullptr) {
3829 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
3830 cameraId.c_str());
3831 return clients;
3832 }
3833
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003834 sp<BasicClient> client = clientDescriptorPtr->getValue();
3835 if (client.get() != nullptr) {
3836 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
Jyoti Bhayana1a586fd2024-11-20 19:54:35 -08003837 clients.push_back(client);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003838 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003839 }
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07003840 return clients;
Keun young Parkd8973a72012-03-28 14:13:09 -07003841}
3842
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003843void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003844 // Acquire mServiceLock and prevent other clients from connecting
3845 std::unique_ptr<AutoConditionLock> lock =
3846 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3847
Ruben Brunk6267b532015-04-30 17:44:07 -07003848 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003849 for (size_t i = 0; i < newUserIds.size(); i++) {
3850 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003851 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003852 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003853 return;
3854 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003855 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003856 }
3857
Ruben Brunka8ca9152015-04-07 14:23:40 -07003858
Ruben Brunk6267b532015-04-30 17:44:07 -07003859 if (newAllowedUsers == mAllowedUsers) {
3860 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3861 return;
3862 }
3863
3864 logUserSwitch(mAllowedUsers, newAllowedUsers);
3865
3866 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003867
3868 // Current user has switched, evict all current clients.
3869 std::vector<sp<BasicClient>> evicted;
3870 for (auto& i : mActiveClientManager.getAll()) {
3871 auto clientSp = i->getValue();
3872
3873 if (clientSp.get() == nullptr) {
3874 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3875 continue;
3876 }
3877
Ruben Brunk6267b532015-04-30 17:44:07 -07003878 // Don't evict clients that are still allowed.
3879 uid_t clientUid = clientSp->getClientUid();
3880 userid_t clientUserId = multiuser_get_user_id(clientUid);
3881 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3882 continue;
3883 }
3884
Ruben Brunk36597b22015-03-20 22:15:57 -07003885 evicted.push_back(clientSp);
3886
Ruben Brunk36597b22015-03-20 22:15:57 -07003887 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003888 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003889
Ruben Brunk36597b22015-03-20 22:15:57 -07003890 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003891 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003892 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003893 " to user switch.", i->getKey().c_str(),
3894 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003895 i->getOwnerId(), i->getPriority().getScore(),
3896 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003897
3898 }
3899
3900 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3901 // blocking other clients from connecting in mServiceLockWrapper if held.
3902 mServiceLock.unlock();
3903
3904 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003905 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003906
3907 for (auto& i : evicted) {
3908 i->disconnect();
3909 }
3910
Austin Borger22c5c852024-03-08 13:31:36 -08003911 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003912
3913 // Reacquire mServiceLock
3914 mServiceLock.lock();
3915}
Ruben Brunkcc776712015-02-17 20:18:47 -08003916
Austin Borgered99f642023-06-01 16:51:35 -07003917void CameraService::logEvent(const std::string &event) {
3918 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003919 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003920 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003921 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003922 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003923 mEventLog.add(msg);
3924 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3925 // Error event not added to the dumpsys log before
3926 mEventLog.add(msg);
3927 sServiceErrorEventSet.insert(msg);
3928 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929}
3930
Austin Borgered99f642023-06-01 16:51:35 -07003931void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3932 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003933 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003934 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3935 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003936}
3937
Austin Borgered99f642023-06-01 16:51:35 -07003938void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3939 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003940 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003941 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3942 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003943}
3944
Austin Borgered99f642023-06-01 16:51:35 -07003945void CameraService::logConnected(const std::string &cameraId, int clientPid,
3946 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003947 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003948 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3949 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003950}
3951
Austin Borgered99f642023-06-01 16:51:35 -07003952void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3953 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003954 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003955 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3956 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003957}
3958
Austin Borgered99f642023-06-01 16:51:35 -07003959void CameraService::logRejected(const std::string &cameraId, int clientPid,
3960 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003961 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003962 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3963 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003964}
3965
Austin Borgered99f642023-06-01 16:51:35 -07003966void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3967 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003968 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003969 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3970 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003971}
3972
Ruben Brunk6267b532015-04-30 17:44:07 -07003973void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3974 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003975 std::string newUsers = toString(newUserIds);
3976 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003977 if (oldUsers.size() == 0) {
3978 oldUsers = "<None>";
3979 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003980 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003981 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3982 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003983}
3984
Austin Borgered99f642023-06-01 16:51:35 -07003985void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003986 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003987 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003988}
3989
Austin Borgered99f642023-06-01 16:51:35 -07003990void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003991 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003992 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003993}
3994
Austin Borgered99f642023-06-01 16:51:35 -07003995void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003996 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003997 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003998}
3999
Austin Borgered99f642023-06-01 16:51:35 -07004000void CameraService::logServiceError(const std::string &msg, int errorCode) {
4001 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4002 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004003}
4004
Ruben Brunk36597b22015-03-20 22:15:57 -07004005status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4006 uint32_t flags) {
4007
Mathias Agopian65ab4712010-07-14 17:59:35 -07004008 // Permission checks
4009 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004010 case SHELL_COMMAND_TRANSACTION: {
4011 int in = data.readFileDescriptor();
4012 int out = data.readFileDescriptor();
4013 int err = data.readFileDescriptor();
4014 int argc = data.readInt32();
4015 Vector<String16> args;
4016 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4017 args.add(data.readString16());
4018 }
4019 sp<IBinder> unusedCallback;
4020 sp<IResultReceiver> resultReceiver;
4021 status_t status;
4022 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4023 return status;
4024 }
4025 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4026 return status;
4027 }
4028 status = shellCommand(in, out, err, args);
4029 if (resultReceiver != nullptr) {
4030 resultReceiver->send(status);
4031 }
4032 return NO_ERROR;
4033 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 }
4035
4036 return BnCameraService::onTransact(code, data, reply, flags);
4037}
4038
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039// We share the media players for shutter and recording sound for all clients.
4040// A reference count is kept to determine when we will actually release the
4041// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004042sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4043 sp<MediaPlayer> mp = new MediaPlayer();
4044 status_t error;
4045 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004046 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004047 error = mp->prepare();
4048 }
4049 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004050 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004051 mp->disconnect();
4052 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004053 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004054 }
4055 return mp;
4056}
4057
username5755fea2018-12-27 09:48:08 +08004058void CameraService::increaseSoundRef() {
4059 Mutex::Autolock lock(mSoundLock);
4060 mSoundRef++;
4061}
4062
4063void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004064 ATRACE_CALL();
4065
username5755fea2018-12-27 09:48:08 +08004066 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4067 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4068 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4069 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4070 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4071 }
4072 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4073 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4074 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4075 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004076 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004077 }
4078 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4079 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4080 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4081 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4082 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004083 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084}
4085
username5755fea2018-12-27 09:48:08 +08004086void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004087 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004088 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004089 if (--mSoundRef) return;
4090
4091 for (int i = 0; i < NUM_SOUNDS; i++) {
4092 if (mSoundPlayer[i] != 0) {
4093 mSoundPlayer[i]->disconnect();
4094 mSoundPlayer[i].clear();
4095 }
4096 }
4097}
4098
4099void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004100 ATRACE_CALL();
4101
Mathias Agopian65ab4712010-07-14 17:59:35 -07004102 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004103 if (kind < 0 || kind >= NUM_SOUNDS) {
4104 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4105 return;
4106 }
4107
Mathias Agopian65ab4712010-07-14 17:59:35 -07004108 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004109 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004110 sp<MediaPlayer> player = mSoundPlayer[kind];
4111 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004112 player->seekTo(0);
4113 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004114 }
4115}
4116
4117// ----------------------------------------------------------------------------
4118
Austin Borger2e772b82024-10-11 16:09:57 -07004119CameraService::Client::Client(
4120 const sp<CameraService>& cameraService, const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004121 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004122 const AttributionSourceState& clientAttribution, int callingPid, bool systemNativeClient,
4123 const std::string& cameraIdStr, int api1CameraId, int cameraFacing, int sensorOrientation,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004124 int servicePid, int rotationOverride, bool sharedMode)
Austin Borger2e772b82024-10-11 16:09:57 -07004125 : CameraService::BasicClient(cameraService, IInterface::asBinder(cameraClient),
4126 attributionAndPermissionUtils, clientAttribution, callingPid,
4127 systemNativeClient, cameraIdStr, cameraFacing, sensorOrientation,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004128 servicePid, rotationOverride, sharedMode),
Austin Borger2e772b82024-10-11 16:09:57 -07004129 mCameraId(api1CameraId) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004130 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004132 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004133
username5755fea2018-12-27 09:48:08 +08004134 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004135
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004136 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137}
4138
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139// tear down the client
4140CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004141 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004142 mDestructionStarted = true;
4143
username5755fea2018-12-27 09:48:08 +08004144 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004145 // unconditionally disconnect. function is idempotent
4146 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004147}
4148
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004149sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4150
Austin Borger2e772b82024-10-11 16:09:57 -07004151CameraService::BasicClient::BasicClient(
4152 const sp<CameraService>& cameraService, const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004153 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004154 const AttributionSourceState& clientAttribution, int callingPid, bool nativeClient,
4155 const std::string& cameraIdStr, int cameraFacing, int sensorOrientation, int servicePid,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004156 int rotationOverride, bool sharedMode)
Austin Borger2e772b82024-10-11 16:09:57 -07004157 : AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
4158 mDestructionStarted(false),
4159 mCameraIdStr(cameraIdStr),
4160 mCameraFacing(cameraFacing),
4161 mOrientation(sensorOrientation),
4162 mClientAttribution(clientAttribution),
4163 mCallingPid(callingPid),
4164 mSystemNativeClient(nativeClient),
4165 mServicePid(servicePid),
4166 mDisconnected(false),
4167 mUidIsTrusted(false),
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004168 mRotationOverride(rotationOverride), mSharedMode(sharedMode),
Austin Borger2e772b82024-10-11 16:09:57 -07004169 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
4170 mRemoteBinder(remoteCallback),
Austin Borgera0c61f12024-10-11 13:38:35 -07004171 mCameraOpen(false),
4172 mCameraStreaming(false) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004173 if (sCameraService == nullptr) {
4174 sCameraService = cameraService;
4175 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004176
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004177 // There are 2 scenarios in which a client won't have AppOps operations
4178 // (both scenarios : native clients)
4179 // 1) It's an system native client*, the package name will be empty
4180 // and it will return from this function in the previous if condition
4181 // (This is the same as the previously existing behavior).
4182 // 2) It is a system native client, but its package name has been
4183 // modified for debugging, however it still must not use AppOps since
4184 // the package name is not a real one.
4185 //
4186 // * system native client - native client with UID < AID_APP_START. It
4187 // doesn't exclude clients not on the system partition.
4188 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004189 mAppOpsManager = std::make_unique<AppOpsManager>();
4190 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004191
Austin Borger32163932024-10-25 13:56:52 -07004192 mUidIsTrusted = isTrustedCallingUid(mClientAttribution.uid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004193}
4194
4195CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004196 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004197 mDestructionStarted = true;
4198}
4199
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004200binder::Status CameraService::BasicClient::disconnect() {
4201 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004202 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004203 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004204 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004205 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004206
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004207 sCameraService->removeByClient(this);
Austin Borger2e772b82024-10-11 16:09:57 -07004208 sCameraService->logDisconnected(mCameraIdStr, mCallingPid, getPackageName());
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004209 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode &&
4210 sCameraService->isOnlyClient(this))) {
4211 // Remove the HAL reference for the camera in either of the following scenarios :
4212 // 1) Camera was opened in non-shared mode.
4213 // 2) Camera was opened in shared mode and this is the last client using
4214 // the camera which is being disconnected
4215 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
4216 mCameraIdStr);
4217 }
Ruben Brunkcc776712015-02-17 20:18:47 -08004218
4219 sp<IBinder> remote = getRemote();
4220 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004221 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004222 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004223
Austin Borgera0c61f12024-10-11 13:38:35 -07004224 notifyCameraClosing();
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004225 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode &&
4226 sCameraService->isOnlyClient(this))) {
4227 // Notify flashlight that a camera device is closed.
4228 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
4229 }
Austin Borgered99f642023-06-01 16:51:35 -07004230 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004231 mCallingPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004232
Igor Murashkincba2c162013-03-20 15:56:31 -07004233 // client shouldn't be able to call into us anymore
Austin Borger2e772b82024-10-11 16:09:57 -07004234 mCallingPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004235
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004236 const auto& mActivityManager = getActivityManager();
4237 if (mActivityManager) {
4238 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004239 getCallingUid(),
4240 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004241 }
4242
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004243 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004244}
4245
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004246status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4247 // No dumping of clients directly over Binder,
4248 // must go through CameraService::dump
4249 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004250 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004251 return OK;
4252}
4253
Austin Borgered99f642023-06-01 16:51:35 -07004254status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004255 // Can't watch tags directly, must go through CameraService::startWatchingTags
4256 return OK;
4257}
4258
4259status_t CameraService::BasicClient::stopWatchingTags(int) {
4260 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4261 return OK;
4262}
4263
4264status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4265 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4266 return OK;
4267}
4268
Austin Borgered99f642023-06-01 16:51:35 -07004269std::string CameraService::BasicClient::getPackageName() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004270 return mClientAttribution.packageName.value_or(kUnknownPackageName);
Ruben Brunkcc776712015-02-17 20:18:47 -08004271}
4272
Emilian Peev8b64f282021-03-25 16:49:57 -07004273int CameraService::BasicClient::getCameraFacing() const {
4274 return mCameraFacing;
4275}
4276
4277int CameraService::BasicClient::getCameraOrientation() const {
4278 return mOrientation;
4279}
Ruben Brunkcc776712015-02-17 20:18:47 -08004280
Austin Borger2e772b82024-10-11 16:09:57 -07004281int CameraService::BasicClient::getClientCallingPid() const {
4282 return mCallingPid;
Ruben Brunkcc776712015-02-17 20:18:47 -08004283}
4284
Ruben Brunk6267b532015-04-30 17:44:07 -07004285uid_t CameraService::BasicClient::getClientUid() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004286 return mClientAttribution.uid;
4287}
4288
4289const std::optional<std::string>& CameraService::BasicClient::getClientAttributionTag() const {
4290 return mClientAttribution.attributionTag;
Ruben Brunk6267b532015-04-30 17:44:07 -07004291}
4292
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004293bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4294 // Defaults to API2.
4295 return level == API_2;
4296}
4297
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004298status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004299 {
4300 Mutex::Autolock l(mAudioRestrictionLock);
4301 mAudioRestriction = mode;
4302 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004303 sCameraService->updateAudioRestriction();
4304 return OK;
4305}
4306
4307int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004308 return sCameraService->updateAudioRestriction();
4309}
4310
4311int32_t CameraService::BasicClient::getAudioRestriction() const {
4312 Mutex::Autolock l(mAudioRestrictionLock);
4313 return mAudioRestriction;
4314}
4315
4316bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4317 switch (mode) {
4318 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4319 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4320 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4321 return true;
4322 default:
4323 return false;
4324 }
4325}
4326
Austin Borgera0c61f12024-10-11 13:38:35 -07004327status_t CameraService::BasicClient::handlePermissionResult(
4328 PermissionChecker::PermissionResult result) {
4329 if (result == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004330 ALOGI("Camera %s: Access for \"%s\" has been revoked", mCameraIdStr.c_str(),
4331 getPackageName().c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004332 return PERMISSION_DENIED;
Austin Borgera0c61f12024-10-11 13:38:35 -07004333 } else if (!mUidIsTrusted && result == PermissionChecker::PERMISSION_SOFT_DENIED) {
4334 // If the calling Uid is trusted (a native service), the AppOpsManager/PermissionChecker
4335 // could return MODE_IGNORED/PERMISSION_SOFT_DENIED. Do not treat such case as error.
Austin Borger2e772b82024-10-11 16:09:57 -07004336 bool isUidActive =
4337 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004338
4339 bool isCameraPrivacyEnabled;
4340 if (flags::camera_privacy_allowlist()) {
4341 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004342 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004343 } else {
4344 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004345 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004346 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004347 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4348 // We prefer to successfully open the camera and perform camera muting
4349 // or blocking in connectHelper as handleAppOpMode can be called before the
4350 // connection has been fully established and at that time camera muting
4351 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004352 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004353 ALOGI("Camera %s: Access for \"%s\" has been restricted."
Austin Borger2e772b82024-10-11 16:09:57 -07004354 "uid active: %s, privacy enabled: %s",
4355 mCameraIdStr.c_str(), getPackageName().c_str(), isUidActive ? "true" : "false",
4356 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004357 // Return the same error as for device policy manager rejection
4358 return -EACCES;
4359 }
4360 }
4361 return OK;
4362}
4363
Austin Borgera0c61f12024-10-11 13:38:35 -07004364status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4365 return handlePermissionResult(appOpModeToPermissionResult(mode));
4366}
4367
4368status_t CameraService::BasicClient::notifyCameraOpening() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004369 ATRACE_CALL();
4370
Austin Borgera0c61f12024-10-11 13:38:35 -07004371 // Don't start watching until we're streaming when using permissionChecker for data delivery
Austin Borger2a3f9a72024-11-07 12:24:49 -08004372 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004373 ALOGD("%s: Start camera ops, package name = %s, client UID = %d", __FUNCTION__,
Austin Borger2e772b82024-10-11 16:09:57 -07004374 getPackageName().c_str(), getClientUid());
Austin Borgerca1e0062023-06-28 11:32:55 -07004375
Austin Borgera0c61f12024-10-11 13:38:35 -07004376 if (mAppOpsManager != nullptr) {
4377 // Notify app ops that the camera is not available
4378 mOpsCallback = new OpsCallback(this);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004379
Austin Borgera0c61f12024-10-11 13:38:35 -07004380 mAppOpsManager->startWatchingMode(
4381 AppOpsManager::OP_CAMERA, toString16(getPackageName()),
4382 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4383
4384 // Just check for camera access here on open - delay startOp until
4385 // camera frames start streaming in startCameraStreamingOps
4386 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4387 toString16(getPackageName()));
4388 status_t res = handleAppOpMode(mode);
4389 if (res != OK) {
4390 return res;
4391 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004392 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004393 } else {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004394 // TODO: Remove when removing the data_delivery_permission_checks flag
Austin Borgera0c61f12024-10-11 13:38:35 -07004395 ALOGD("%s: Bypassing checkOp for uid %d", __FUNCTION__, getClientUid());
Svetoslav28e8ef72015-05-11 19:21:31 -07004396 }
4397
Austin Borgera0c61f12024-10-11 13:38:35 -07004398 mCameraOpen = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004399
4400 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004401 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004402
Austin Borger2e772b82024-10-11 16:09:57 -07004403 sCameraService->mUidPolicy->registerMonitorUid(getClientUid(), /*openCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004404
Shuzhen Wang695044d2020-03-06 09:02:23 -08004405 // Notify listeners of camera open/close status
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004406 sCameraService->updateOpenCloseStatus(mCameraIdStr, true /*open*/, getPackageName(),
4407 mSharedMode);
Shuzhen Wang695044d2020-03-06 09:02:23 -08004408
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004409 return OK;
4410}
4411
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004412status_t CameraService::BasicClient::startCameraStreamingOps() {
4413 ATRACE_CALL();
4414
Austin Borgera0c61f12024-10-11 13:38:35 -07004415 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004416 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4417 return INVALID_OPERATION;
4418 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004419
4420 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004421 ALOGV("%s: Streaming already active!", __FUNCTION__);
4422 return OK;
4423 }
4424
Austin Borger2e772b82024-10-11 16:09:57 -07004425 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d", __FUNCTION__,
4426 getPackageName().c_str(), getClientUid());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004427
4428 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004429 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004430 ALOGD("%s: Start data delivery for uid %d", __FUNCTION__, getClientUid());
4431
4432 const PermissionChecker::PermissionResult result =
4433 checkPermissionsForCameraForStartDataDelivery(mCameraIdStr, mClientAttribution);
4434 status_t res = handlePermissionResult(result);
4435 if (res != OK) {
4436 return res;
4437 }
4438
4439 mOpsCallback = new OpsCallback(this);
4440 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4441 [&](const auto& attr) {
4442 mAppOpsManager->startWatchingMode(
4443 AppOpsManager::OP_CAMERA,
4444 toString16(attr.packageName.value_or("")),
4445 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4446 });
4447 } else {
4448 ALOGD("%s: startOp for uid %d", __FUNCTION__, getClientUid());
4449 int32_t mode = mAppOpsManager->startOpNoThrow(
4450 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4451 /*startIfModeDefault*/ false, toString16(getClientAttributionTag()),
4452 toString16("start camera ") + toString16(mCameraIdStr));
4453 status_t res = handleAppOpMode(mode);
4454 if (res != OK) {
4455 return res;
4456 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004457 }
4458 }
4459
Austin Borgera0c61f12024-10-11 13:38:35 -07004460 mCameraStreaming = true;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004461
4462 return OK;
4463}
4464
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004465status_t CameraService::BasicClient::noteAppOp() {
4466 ATRACE_CALL();
4467
Austin Borger2e772b82024-10-11 16:09:57 -07004468 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d", __FUNCTION__,
4469 getPackageName().c_str(), getClientUid());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004470
4471 // noteAppOp is only used for when camera mute is not supported, in order
4472 // to trigger the sensor privacy "Unblock" dialog
Austin Borger2a3f9a72024-11-07 12:24:49 -08004473 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004474 // Ignore the result, since we're only triggering the dialog
4475 ALOGD("%s: Check data delivery permissions for uid %d", __FUNCTION__, getClientUid());
4476 hasPermissionsForCameraForDataDelivery(std::string(), mClientAttribution);
4477 } else if (mAppOpsManager != nullptr) {
4478 ALOGD("%s: noteOp for uid %d", __FUNCTION__, getClientUid());
Austin Borger2e772b82024-10-11 16:09:57 -07004479 int32_t mode = mAppOpsManager->noteOp(
4480 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4481 toString16(getClientAttributionTag()),
Austin Borgered99f642023-06-01 16:51:35 -07004482 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004483 status_t res = handleAppOpMode(mode);
4484 if (res != OK) {
4485 return res;
4486 }
4487 }
4488
4489 return OK;
4490}
4491
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004492status_t CameraService::BasicClient::finishCameraStreamingOps() {
4493 ATRACE_CALL();
4494
Austin Borgera0c61f12024-10-11 13:38:35 -07004495 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004496 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4497 return INVALID_OPERATION;
4498 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004499 if (!mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004500 ALOGV("%s: Streaming not active!", __FUNCTION__);
4501 return OK;
4502 }
4503
4504 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004505 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004506 ALOGD("%s: finishDataDelivery for uid %d", __FUNCTION__, getClientUid());
4507 finishDataDelivery(mClientAttribution);
4508
4509 // Stop watching app op changes after stop streaming
4510 if (mOpsCallback != nullptr) {
4511 mAppOpsManager->stopWatchingMode(mOpsCallback);
4512 mOpsCallback.clear();
4513 }
4514 } else {
4515 ALOGD("%s: finishOp for uid %d", __FUNCTION__, getClientUid());
4516 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, getClientUid(),
4517 toString16(getPackageName()),
4518 toString16(getClientAttributionTag()));
4519 }
4520 mCameraStreaming = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004521 }
4522
4523 return OK;
4524}
4525
Austin Borgera0c61f12024-10-11 13:38:35 -07004526status_t CameraService::BasicClient::notifyCameraClosing() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004527 ATRACE_CALL();
4528
Austin Borgera0c61f12024-10-11 13:38:35 -07004529 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004530 // Make sure we've notified everyone about camera stopping
4531 finishCameraStreamingOps();
4532 }
4533
Austin Borgera0c61f12024-10-11 13:38:35 -07004534 // Check if notifyCameraOpening succeeded, and if so, finish the camera op if necessary
4535 if (mCameraOpen) {
4536 mCameraOpen = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004537
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004538 // This function is called when a client disconnects. This should
4539 // release the camera, but actually only if it was in a proper
4540 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004541 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004542 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004543
Ruben Brunkcc776712015-02-17 20:18:47 -08004544 // Transition to PRESENT if the camera is not in either of the rejected states
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004545 if (!flags::camera_multi_client() || !mSharedMode || (mSharedMode
4546 && sCameraService->isOnlyClient(this))) {
4547 sCameraService->updateStatus(StatusInternal::PRESENT,
4548 mCameraIdStr, rejected);
4549 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004550 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004551
4552 // When using the data delivery permission checks, the open state does not involve AppOps
Austin Borger2a3f9a72024-11-07 12:24:49 -08004553 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004554 // Always stop watching, even if no camera op is active
4555 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4556 mAppOpsManager->stopWatchingMode(mOpsCallback);
4557 }
4558 mOpsCallback.clear();
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004559 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004560
Austin Borger2e772b82024-10-11 16:09:57 -07004561 sCameraService->mUidPolicy->unregisterMonitorUid(getClientUid(), /*closeCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004562
Shuzhen Wang695044d2020-03-06 09:02:23 -08004563 // Notify listeners of camera open/close status
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004564 sCameraService->updateOpenCloseStatus(mCameraIdStr, false /*open*/, getPackageName(),
4565 mSharedMode);
Shuzhen Wang695044d2020-03-06 09:02:23 -08004566
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004567 return OK;
4568}
4569
Austin Borgerf2da9c72024-11-12 13:45:28 -08004570int32_t CameraService::getUidProcessState(int32_t uid) {
4571 const auto& activityManager = getActivityManager();
4572 int32_t procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
4573 if (activityManager != nullptr) {
4574 procState = activityManager->getUidProcessState(uid, toString16(kServiceName));
4575 } else {
4576 ALOGE("%s: getActivityManager returned nullptr.", __FUNCTION__);
4577 }
4578 return procState;
4579}
4580
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004581void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004582 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004583 if (mAppOpsManager == nullptr) {
4584 return;
4585 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004586 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004587 if (op != AppOpsManager::OP_CAMERA) {
4588 ALOGW("Unexpected app ops notification received: %d", op);
4589 return;
4590 }
4591
Austin Borgera0c61f12024-10-11 13:38:35 -07004592 PermissionChecker::PermissionResult res;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004593 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004594 int32_t appOpMode = AppOpsManager::MODE_ALLOWED;
4595 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4596 [&](const auto& attr) {
4597 appOpMode = std::max(appOpMode, mAppOpsManager->checkOp(
4598 AppOpsManager::OP_CAMERA, attr.uid,
4599 toString16(attr.packageName.value_or(""))));
4600 });
4601 ALOGV("checkOp returns: %d, %s ", res,
4602 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4603 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4604 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4605 : "UNKNOWN");
4606 res = appOpModeToPermissionResult(appOpMode);
4607 } else {
4608 int32_t appOpMode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4609 toString16(getPackageName()));
4610 ALOGV("checkOp returns: %d, %s ", res,
4611 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4612 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4613 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4614 : "UNKNOWN");
4615 res = appOpModeToPermissionResult(appOpMode);
4616 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004617
Austin Borgera0c61f12024-10-11 13:38:35 -07004618 if (res == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borgered99f642023-06-01 16:51:35 -07004619 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004620 getPackageName().c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004621 block();
Austin Borgera0c61f12024-10-11 13:38:35 -07004622 } else if (res == PermissionChecker::PERMISSION_SOFT_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004623 bool isUidActive =
4624 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004625
Austin Borgerca1e0062023-06-28 11:32:55 -07004626 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4627 // If not visible, but still active, then we want to block instead of muting the camera.
Austin Borgera0c61f12024-10-11 13:38:35 -07004628 int32_t procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004629 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004630 // Use the proc state of the last uid in the chain (ultimately receiving the data)
4631 // when determining whether to mute or block
4632 int32_t uid = -1;
4633 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4634 [&](const auto& attr) {
4635 uid = static_cast<uid_t>(attr.uid);
4636 });
Austin Borgerf2da9c72024-11-12 13:45:28 -08004637 procState = getUidProcessState(uid);
4638 } else if (flags::query_process_state()) {
4639 procState = getUidProcessState(getClientUid());
Austin Borgera0c61f12024-10-11 13:38:35 -07004640 } else {
4641 procState = sCameraService->mUidPolicy->getProcState(getClientUid());
4642 }
Austin Borgerca1e0062023-06-28 11:32:55 -07004643 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4644
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004645 bool isCameraPrivacyEnabled;
4646 if (flags::camera_privacy_allowlist()) {
4647 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004648 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004649 } else {
4650 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004651 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004652 }
4653
4654 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgera0c61f12024-10-11 13:38:35 -07004655 " isUidVisible %d, isCameraPrivacyEnabled %d procState %d",
Austin Borger2e772b82024-10-11 16:09:57 -07004656 mCameraIdStr.c_str(), getPackageName().c_str(), mUidIsTrusted, isUidActive,
Austin Borgera0c61f12024-10-11 13:38:35 -07004657 isUidVisible, isCameraPrivacyEnabled, procState);
Austin Borgerca1e0062023-06-28 11:32:55 -07004658 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4659 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4660 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004661 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004662 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4663 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004664 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004665 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004666 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004667 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004668 } else if (res == PermissionChecker::PERMISSION_GRANTED) {
Evan Severson09ab4002021-02-10 14:15:19 -08004669 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004670 }
4671}
4672
Svet Ganova453d0d2018-01-11 15:37:58 -08004673void CameraService::BasicClient::block() {
4674 ATRACE_CALL();
4675
4676 // Reset the client PID to allow server-initiated disconnect,
4677 // and to prevent further calls by client.
Austin Borger2e772b82024-10-11 16:09:57 -07004678 mCallingPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004679 CaptureResultExtras resultExtras; // a dummy result (invalid)
4680 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4681 disconnect();
4682}
4683
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07004684status_t CameraService::BasicClient::isPrimaryClient(bool* isPrimary) {
4685 ATRACE_CALL();
4686 if (!flags::camera_multi_client()) {
4687 return INVALID_OPERATION;
4688 }
4689
4690 if (!mSharedMode) {
4691 ALOGW("%s: Invalid operation when camera is not opened in shared mode", __FUNCTION__);
4692 return INVALID_OPERATION;
4693 }
4694 *isPrimary = mIsPrimaryClient;
4695 return OK;
4696}
4697
4698status_t CameraService::BasicClient::setPrimaryClient(bool isPrimary) {
4699 ATRACE_CALL();
4700
4701 if (!flags::camera_multi_client()) {
4702 return INVALID_OPERATION;
4703 }
4704
4705 if (!mSharedMode) {
4706 ALOGW("%s:Invalid operation when camera is not opened in shared mode", __FUNCTION__);
4707 return INVALID_OPERATION;
4708 }
4709 mIsPrimaryClient = isPrimary;
4710 return OK;
4711}
4712
Mathias Agopian65ab4712010-07-14 17:59:35 -07004713// ----------------------------------------------------------------------------
4714
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004715void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004716 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004717 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004718 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4719 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4720 api1ErrorCode = CAMERA_ERROR_DISABLED;
4721 }
4722 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004723 } else {
4724 ALOGE("mRemoteCallback is NULL!!");
4725 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004726}
4727
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004728// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004729binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004730 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004731 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004732}
4733
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004734bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4735 return level == API_1;
4736}
4737
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004738CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4739 mClient(client) {
4740}
4741
4742void CameraService::Client::OpsCallback::opChanged(int32_t op,
4743 const String16& packageName) {
4744 sp<BasicClient> client = mClient.promote();
4745 if (client != NULL) {
4746 client->opChanged(op, packageName);
4747 }
4748}
4749
Mathias Agopian65ab4712010-07-14 17:59:35 -07004750// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004751// UidPolicy
4752// ----------------------------------------------------------------------------
4753
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004754void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004755 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004756 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004757
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004758 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004759 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004760 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004761 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004762 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4763 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004764 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004765 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004766 if (res == OK) {
4767 mRegistered = true;
4768 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004769 } else {
4770 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004771 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004772}
4773
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004774void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004775 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004776 return;
4777 }
4778
4779 registerWithActivityManager();
4780}
4781
4782void CameraService::UidPolicy::registerSelf() {
4783 // Use check service to see if the activity service is available
4784 // If not available then register for notifications, instead of blocking
4785 // till the service is ready
4786 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004787 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004788 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004789 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004790 } else {
4791 registerWithActivityManager();
4792 }
4793}
4794
Svet Ganova453d0d2018-01-11 15:37:58 -08004795void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004796 Mutex::Autolock _l(mUidLock);
4797
Steven Moreland2f348142019-07-02 15:59:07 -07004798 mAm.unregisterUidObserver(this);
4799 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004800 mRegistered = false;
4801 mActiveUids.clear();
4802 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004803}
4804
4805void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4806 onUidIdle(uid, disabled);
4807}
4808
4809void CameraService::UidPolicy::onUidActive(uid_t uid) {
4810 Mutex::Autolock _l(mUidLock);
4811 mActiveUids.insert(uid);
4812}
4813
4814void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4815 bool deleted = false;
4816 {
4817 Mutex::Autolock _l(mUidLock);
4818 if (mActiveUids.erase(uid) > 0) {
4819 deleted = true;
4820 }
4821 }
4822 if (deleted) {
4823 sp<CameraService> service = mService.promote();
4824 if (service != nullptr) {
4825 service->blockClientsForUid(uid);
4826 }
4827 }
4828}
4829
Emilian Peev53722fa2019-02-22 17:47:20 -08004830void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004831 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004832 bool procStateChange = false;
4833 {
4834 Mutex::Autolock _l(mUidLock);
4835 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4836 mMonitoredUids[uid].procState != procState) {
4837 mMonitoredUids[uid].procState = procState;
4838 procStateChange = true;
4839 }
4840 }
4841
4842 if (procStateChange) {
4843 sp<CameraService> service = mService.promote();
4844 if (service != nullptr) {
4845 service->notifyMonitoredUids();
4846 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004847 }
4848}
4849
Austin Borgerdddb7552023-03-30 17:53:01 -07004850/**
4851 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4852 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4853 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4854 * monitoredUids. If it is revised above some other monitoredUid, signal
4855 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4856 * foreground apps in split screen - state changes will capture all other cases.
4857 */
4858void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4859 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004860 {
4861 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004862 auto it = mMonitoredUids.find(uid);
4863
4864 if (it != mMonitoredUids.end()) {
4865 if (it->second.hasCamera) {
4866 for (auto &monitoredUid : mMonitoredUids) {
4867 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004868 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004869 notifyUidSet.emplace(monitoredUid.first);
4870 }
4871 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004872 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004873 notifyUidSet.emplace(uid);
4874 } else {
4875 for (auto &monitoredUid : mMonitoredUids) {
4876 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004877 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004878 notifyUidSet.emplace(uid);
4879 }
4880 }
4881 }
4882 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004883 }
4884 }
4885
Austin Borgerdddb7552023-03-30 17:53:01 -07004886 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004887 sp<CameraService> service = mService.promote();
4888 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004889 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004890 }
4891 }
4892}
4893
Austin Borgerdddb7552023-03-30 17:53:01 -07004894/**
4895 * Register a uid for monitoring, and note whether it owns a camera.
4896 */
4897void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004898 Mutex::Autolock _l(mUidLock);
4899 auto it = mMonitoredUids.find(uid);
4900 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004901 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004902 } else {
Austin Borger65577682022-02-17 00:25:43 +00004903 MonitoredUid monitoredUid;
4904 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004905 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004906 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004907 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004908 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004909 if (res != OK) {
4910 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4911 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004912 }
4913
4914 if (openCamera) {
4915 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004916 }
4917}
4918
Austin Borgerdddb7552023-03-30 17:53:01 -07004919/**
4920 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4921 */
4922void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004923 Mutex::Autolock _l(mUidLock);
4924 auto it = mMonitoredUids.find(uid);
4925 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004926 it->second.refCount--;
4927 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004928 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004929 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004930 if (res != OK) {
4931 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4932 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004933 } else if (closeCamera) {
4934 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004935 }
4936 } else {
4937 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4938 }
4939}
4940
Austin Borgered99f642023-06-01 16:51:35 -07004941bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004942 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004943 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004944}
4945
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004946static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4947static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004948
Austin Borgered99f642023-06-01 16:51:35 -07004949bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004950 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004951 // If activity manager is unreachable, assume everything is active
4952 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004953 return true;
4954 }
4955 auto it = mOverrideUids.find(uid);
4956 if (it != mOverrideUids.end()) {
4957 return it->second;
4958 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004959 bool active = mActiveUids.find(uid) != mActiveUids.end();
4960 if (!active) {
4961 // We want active UIDs to always access camera with their first attempt since
4962 // there is no guarantee the app is robustly written and would retry getting
4963 // the camera on failure. The inverse case is not a problem as we would take
4964 // camera away soon once we get the callback that the uid is no longer active.
4965 ActivityManager am;
4966 // Okay to access with a lock held as UID changes are dispatched without
4967 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004968 int64_t startTimeMillis = 0;
4969 do {
4970 // TODO: Fix this b/109950150!
4971 // Okay this is a hack. There is a race between the UID turning active and
4972 // activity being resumed. The proper fix is very risky, so we temporary add
4973 // some polling which should happen pretty rarely anyway as the race is hard
4974 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004975 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004976 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004977 if (active) {
4978 break;
4979 }
4980 if (startTimeMillis <= 0) {
4981 startTimeMillis = uptimeMillis();
4982 }
4983 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004984 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004985 if (remainingTimeMillis <= 0) {
4986 break;
4987 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004988 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4989
4990 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004991 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004992 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004993 } while (true);
4994
Svet Ganov7b4ab782018-03-25 12:48:10 -07004995 if (active) {
4996 // Now that we found out the UID is actually active, cache that
4997 mActiveUids.insert(uid);
4998 }
4999 }
5000 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08005001}
5002
Varun Shahb42f1eb2019-04-16 14:45:13 -07005003int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
5004 Mutex::Autolock _l(mUidLock);
5005 return getProcStateLocked(uid);
5006}
5007
5008int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
5009 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
5010 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00005011 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07005012 }
5013 return procState;
5014}
5015
Austin Borgered99f642023-06-01 16:51:35 -07005016void CameraService::UidPolicy::addOverrideUid(uid_t uid,
5017 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005018 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08005019}
5020
Austin Borgered99f642023-06-01 16:51:35 -07005021void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005022 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005023}
5024
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005025void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5026 Mutex::Autolock _l(mUidLock);
5027 ALOGV("UidPolicy: ActivityManager has died");
5028 mRegistered = false;
5029 mActiveUids.clear();
5030}
5031
Austin Borgered99f642023-06-01 16:51:35 -07005032void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005033 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005034 bool wasActive = false;
5035 bool isActive = false;
5036 {
5037 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005038 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005039 mOverrideUids.erase(uid);
5040 if (insert) {
5041 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5042 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005043 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005044 }
5045 if (wasActive != isActive && !isActive) {
5046 sp<CameraService> service = mService.promote();
5047 if (service != nullptr) {
5048 service->blockClientsForUid(uid);
5049 }
5050 }
5051}
5052
5053// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005054// SensorPrivacyPolicy
5055// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005056
5057void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5058{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005059 Mutex::Autolock _l(mSensorPrivacyLock);
5060 if (mRegistered) {
5061 return;
5062 }
Evan Severson09ab4002021-02-10 14:15:19 -08005063 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005064 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005065 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005066 mSpm.addToggleSensorPrivacyListener(this);
5067 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005068 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005069 if (flags::camera_privacy_allowlist()) {
5070 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5071 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5072 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5073 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005074 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005075 if (res == OK) {
5076 mRegistered = true;
5077 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5078 }
5079}
5080
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005081void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5082 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005083 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005084 return;
5085 }
5086
5087 registerWithSensorPrivacyManager();
5088}
5089
5090void CameraService::SensorPrivacyPolicy::registerSelf() {
5091 // Use checkservice to see if the sensor_privacy service is available
5092 // If service is not available then register for notification
5093 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005094 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005095 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005096 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005097 } else {
5098 registerWithSensorPrivacyManager();
5099 }
5100}
5101
Michael Grooverd1d435a2018-12-18 17:39:42 -08005102void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5103 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005104 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005105 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005106 mSpm.removeToggleSensorPrivacyListener(this);
5107 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005108 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005109 mRegistered = false;
5110 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5111}
5112
5113bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005114 if (!mRegistered) {
5115 registerWithSensorPrivacyManager();
5116 }
5117
Michael Grooverd1d435a2018-12-18 17:39:42 -08005118 Mutex::Autolock _l(mSensorPrivacyLock);
5119 return mSensorPrivacyEnabled;
5120}
5121
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005122int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5123 if (!mRegistered) {
5124 registerWithSensorPrivacyManager();
5125 }
5126
5127 Mutex::Autolock _l(mSensorPrivacyLock);
5128 return mCameraPrivacyState;
5129}
5130
Evan Seversond0b69922022-01-27 10:47:34 -08005131bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005132 if (!hasCameraPrivacyFeature()) {
5133 return false;
5134 }
Evan Seversond0b69922022-01-27 10:47:34 -08005135 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005136}
5137
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005138bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5139 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07005140 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005141 }
5142 return mSpm.isCameraPrivacyEnabled(packageName);
5143}
5144
Evan Seversond0b69922022-01-27 10:47:34 -08005145binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005146 int toggleType, int sensor, bool enabled) {
5147 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5148 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5149 {
5150 Mutex::Autolock _l(mSensorPrivacyLock);
5151 mSensorPrivacyEnabled = enabled;
5152 }
5153 // if sensor privacy is enabled then block all clients from accessing the camera
5154 if (enabled) {
5155 sp<CameraService> service = mService.promote();
5156 if (service != nullptr) {
5157 service->blockAllClients();
5158 }
5159 }
5160 }
5161 return binder::Status::ok();
5162}
5163
5164binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5165 int, int sensor, int state) {
5166 if (!flags::camera_privacy_allowlist()
5167 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5168 return binder::Status::ok();
5169 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005170 {
5171 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005172 mCameraPrivacyState = state;
5173 }
5174 sp<CameraService> service = mService.promote();
5175 if (!service) {
5176 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005177 }
5178 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005179 if (state == SensorPrivacyManager::ENABLED) {
5180 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005181 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005182 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005183 }
5184 return binder::Status::ok();
5185}
5186
5187void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5188 Mutex::Autolock _l(mSensorPrivacyLock);
5189 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5190 mRegistered = false;
5191}
5192
Evan Severson09ab4002021-02-10 14:15:19 -08005193bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005194 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5195 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5196 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5197 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5198 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005199}
5200
Michael Grooverd1d435a2018-12-18 17:39:42 -08005201// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005202// CameraState
5203// ----------------------------------------------------------------------------
5204
Austin Borgered99f642023-06-01 16:51:35 -07005205CameraService::CameraState::CameraState(const std::string& id, int cost,
5206 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005207 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005208 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005209 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005210
5211CameraService::CameraState::~CameraState() {}
5212
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005213CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005214 Mutex::Autolock lock(mStatusLock);
5215 return mStatus;
5216}
5217
Austin Borgered99f642023-06-01 16:51:35 -07005218std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005219 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005220 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005221 return res;
5222}
5223
Ruben Brunkcc776712015-02-17 20:18:47 -08005224CameraParameters CameraService::CameraState::getShimParams() const {
5225 return mShimParams;
5226}
5227
5228void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5229 mShimParams = params;
5230}
5231
5232int CameraService::CameraState::getCost() const {
5233 return mCost;
5234}
5235
Austin Borgered99f642023-06-01 16:51:35 -07005236std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005237 return mConflicting;
5238}
5239
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005240SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5241 return mSystemCameraKind;
5242}
5243
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005244bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5245 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5246 != mPhysicalCameras.end();
5247}
5248
Austin Borgered99f642023-06-01 16:51:35 -07005249bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005250 Mutex::Autolock lock(mStatusLock);
5251 auto result = mUnavailablePhysicalIds.insert(physicalId);
5252 return result.second;
5253}
5254
Austin Borgered99f642023-06-01 16:51:35 -07005255bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005256 Mutex::Autolock lock(mStatusLock);
5257 auto count = mUnavailablePhysicalIds.erase(physicalId);
5258 return count > 0;
5259}
5260
Austin Borgered99f642023-06-01 16:51:35 -07005261void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005262 Mutex::Autolock lock(mStatusLock);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005263 mClientPackages.clear();
5264 mClientPackages.insert(clientPackage);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005265}
5266
Austin Borgered99f642023-06-01 16:51:35 -07005267std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005268 Mutex::Autolock lock(mStatusLock);
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005269 if (!mClientPackages.empty()) {
5270 std::set<std::string>::iterator it = mClientPackages.begin();
5271 return *it;
5272 }
5273 return std::string();
5274}
5275
5276void CameraService::CameraState::addClientPackage(const std::string& clientPackage) {
5277 Mutex::Autolock lock(mStatusLock);
5278 mClientPackages.insert(clientPackage);
5279}
5280
5281void CameraService::CameraState::removeClientPackage(const std::string& clientPackage) {
5282 Mutex::Autolock lock(mStatusLock);
5283 mClientPackages.erase(clientPackage);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005284}
5285
Ruben Brunkcc776712015-02-17 20:18:47 -08005286// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005287// ClientEventListener
5288// ----------------------------------------------------------------------------
5289
5290void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005291 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005292 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005293 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005294 if (basicClient.get() != nullptr) {
5295 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005296 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005297 static_cast<int>(basicClient->getClientUid()));
5298 }
5299}
5300
5301void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005302 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005303 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005304 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005305 if (basicClient.get() != nullptr) {
5306 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005307 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005308 static_cast<int>(basicClient->getClientUid()));
5309 }
5310}
5311
Ruben Brunk99e69712015-05-26 17:25:07 -07005312// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005313// CameraClientManager
5314// ----------------------------------------------------------------------------
5315
Ruben Brunk99e69712015-05-26 17:25:07 -07005316CameraService::CameraClientManager::CameraClientManager() {
5317 setListener(std::make_shared<ClientEventListener>());
5318}
5319
Ruben Brunkcc776712015-02-17 20:18:47 -08005320CameraService::CameraClientManager::~CameraClientManager() {}
5321
5322sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005323 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005324 auto descriptor = get(id);
5325 if (descriptor == nullptr) {
5326 return sp<BasicClient>{nullptr};
5327 }
5328 return descriptor->getValue();
5329}
5330
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005331void CameraService::CameraClientManager::remove(const CameraService::DescriptorPtr& value) {
5332 ClientManager::remove(value);
5333 if (!flags::camera_multi_client()) {
5334 return;
5335 }
5336 auto clientToRemove = value->getValue();
5337 if ((clientToRemove.get() != nullptr) && clientToRemove->mSharedMode) {
5338 bool primaryClient = false;
5339 status_t ret = clientToRemove->isPrimaryClient(&primaryClient);
5340 if ((ret == OK) && primaryClient) {
5341 // Primary client is being removed. Find the next higher priority
5342 // client to become primary client.
5343 auto clientDescriptor = get(value->getKey());
5344 if (clientDescriptor == nullptr) {
5345 ALOGV("CameraService::CameraClientManager::no other clients are using same camera");
5346 return;
5347 }
5348 resource_policy::ClientPriority highestPriority = clientDescriptor->getPriority();
5349 sp<BasicClient> highestPriorityClient = clientDescriptor->getValue();
5350 if (highestPriorityClient.get() != nullptr) {
5351 for (auto& i : getAll()) {
5352 if ((i->getKey() == value->getKey()) && (i->getPriority() < highestPriority)) {
5353 highestPriority = i->getPriority();
5354 highestPriorityClient = i->getValue();
5355 }
5356 }
5357 highestPriorityClient->setPrimaryClient(true);
5358 highestPriorityClient->notifyClientSharedAccessPriorityChanged(true);
5359 }
5360 }
5361 }
5362}
5363
Austin Borgered99f642023-06-01 16:51:35 -07005364std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005365 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005366 std::ostringstream ret;
5367 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005368 bool hasAny = false;
5369 for (auto& i : all) {
5370 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005371 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005372 int32_t cost = i->getCost();
5373 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005374 int32_t score = i->getPriority().getScore();
5375 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005376 auto conflicting = i->getConflicting();
5377 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005378 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005379 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005380 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005381 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005382 uid_t clientUid = clientSp->getClientUid();
5383 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005384 }
Austin Borgered99f642023-06-01 16:51:35 -07005385 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5386 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005387
Ruben Brunk6267b532015-04-30 17:44:07 -07005388 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005389 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005390 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005391 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005392 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005393 }
5394
Austin Borgered99f642023-06-01 16:51:35 -07005395 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005396 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005397 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005398 }
Austin Borgered99f642023-06-01 16:51:35 -07005399 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005400 }
Austin Borgered99f642023-06-01 16:51:35 -07005401 if (hasAny) ret << "\n";
5402 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005403 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005404}
5405
5406CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005407 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5408 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005409 int32_t state, int32_t oomScoreOffset, bool systemNativeClient, bool sharedMode) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005410
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005411 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005412 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005413
Austin Borgered99f642023-06-01 16:51:35 -07005414 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005415 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005416 systemNativeClient, oomScoreOffset, sharedMode);
Ruben Brunkcc776712015-02-17 20:18:47 -08005417}
5418
5419CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005420 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005421 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005422 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005423 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005424 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005425 systemNativeClient, partial->getSharedMode());
Ruben Brunkcc776712015-02-17 20:18:47 -08005426}
5427
5428// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005429// InjectionStatusListener
5430// ----------------------------------------------------------------------------
5431
5432void CameraService::InjectionStatusListener::addListener(
5433 const sp<ICameraInjectionCallback>& callback) {
5434 Mutex::Autolock lock(mListenerLock);
5435 if (mCameraInjectionCallback) return;
5436 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5437 if (res == OK) {
5438 mCameraInjectionCallback = callback;
5439 }
5440}
5441
5442void CameraService::InjectionStatusListener::removeListener() {
5443 Mutex::Autolock lock(mListenerLock);
5444 if (mCameraInjectionCallback == nullptr) {
5445 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5446 return;
5447 }
5448 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5449 mCameraInjectionCallback = nullptr;
5450}
5451
5452void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005453 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005454 if (mCameraInjectionCallback == nullptr) {
5455 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5456 return;
5457 }
Cliff Wud3a05312021-04-26 23:07:31 +08005458
5459 switch (err) {
5460 case -ENODEV:
5461 mCameraInjectionCallback->onInjectionError(
5462 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5463 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005464 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005465 break;
5466 case -EBUSY:
5467 mCameraInjectionCallback->onInjectionError(
5468 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5469 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005470 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005471 break;
5472 case DEAD_OBJECT:
5473 mCameraInjectionCallback->onInjectionError(
5474 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5475 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005476 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005477 break;
5478 case INVALID_OPERATION:
5479 mCameraInjectionCallback->onInjectionError(
5480 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5481 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005482 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005483 break;
5484 case UNKNOWN_TRANSACTION:
5485 mCameraInjectionCallback->onInjectionError(
5486 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5487 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005488 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005489 break;
5490 default:
5491 mCameraInjectionCallback->onInjectionError(
5492 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5493 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005494 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005495 }
Cliff Wud8cae102021-03-11 01:37:42 +08005496}
5497
5498void CameraService::InjectionStatusListener::binderDied(
5499 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005500 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5501 auto parent = mParent.promote();
5502 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005503 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5504 if (clientDescriptor != nullptr) {
5505 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5506 baseClientPtr->stopInjection();
5507 }
Cliff Wu3b268182021-07-06 15:44:43 +08005508 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005509 }
5510}
5511
5512// ----------------------------------------------------------------------------
5513// CameraInjectionSession
5514// ----------------------------------------------------------------------------
5515
5516binder::Status CameraService::CameraInjectionSession::stopInjection() {
5517 Mutex::Autolock lock(mInjectionSessionLock);
5518 auto parent = mParent.promote();
5519 if (parent == nullptr) {
5520 ALOGE("CameraInjectionSession: Parent is gone");
5521 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5522 "Camera service encountered error");
5523 }
Cliff Wud3a05312021-04-26 23:07:31 +08005524
5525 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005526 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5527 if (clientDescriptor != nullptr) {
5528 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5529 res = baseClientPtr->stopInjection();
5530 if (res != OK) {
5531 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5532 " ret != NO_ERROR: %d", res);
5533 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5534 "Camera session encountered error");
5535 }
5536 }
Cliff Wu3b268182021-07-06 15:44:43 +08005537 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005538 return binder::Status::ok();
5539}
5540
5541// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005542
5543static const int kDumpLockRetries = 50;
5544static const int kDumpLockSleep = 60000;
5545
5546static bool tryLock(Mutex& mutex)
5547{
5548 bool locked = false;
5549 for (int i = 0; i < kDumpLockRetries; ++i) {
5550 if (mutex.tryLock() == NO_ERROR) {
5551 locked = true;
5552 break;
5553 }
5554 usleep(kDumpLockSleep);
5555 }
5556 return locked;
5557}
5558
Rucha Katakwardf223072021-06-15 10:21:00 -07005559void CameraService::cacheDump() {
5560 if (mMemFd != -1) {
5561 const Vector<String16> args;
5562 ATRACE_CALL();
5563 // Acquiring service lock here will avoid the deadlock since
5564 // cacheDump will not be called during the second disconnect.
5565 Mutex::Autolock lock(mServiceLock);
5566
5567 Mutex::Autolock l(mCameraStatesLock);
5568 // Start collecting the info for open sessions and store it in temp file.
5569 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005570 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005571 auto clientDescriptor = mActiveClientManager.get(cameraId);
5572 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005573 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005574 // Log the current open session info before device is disconnected.
5575 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5576 }
5577 }
5578 }
5579}
5580
Mathias Agopian65ab4712010-07-14 17:59:35 -07005581status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005582 ATRACE_CALL();
5583
Austin Borgered99f642023-06-01 16:51:35 -07005584 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005585 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005586 getCallingPid(),
5587 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005588 return NO_ERROR;
5589 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005590 bool locked = tryLock(mServiceLock);
5591 // failed to lock - CameraService is probably deadlocked
5592 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005593 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005594 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005595
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005596 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005597 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005598
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005599 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005600 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005601
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005602 if (locked) mServiceLock.unlock();
5603 return NO_ERROR;
5604 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005605 dprintf(fd, "\n== Service global info: ==\n\n");
5606 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005607 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005608 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5609 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005610 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5611 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5612 }
Austin Borgered99f642023-06-01 16:51:35 -07005613 std::string activeClientString = mActiveClientManager.toString();
5614 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5615 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005616 if (mStreamUseCaseOverrides.size() > 0) {
5617 dprintf(fd, "Active stream use case overrides:");
5618 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5619 dprintf(fd, " %" PRId64, useCaseOverride);
5620 }
5621 dprintf(fd, "\n");
5622 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005623
5624 dumpEventLog(fd);
5625
5626 bool stateLocked = tryLock(mCameraStatesLock);
5627 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005628 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005629 }
5630
Emilian Peevbd8c5032018-02-14 23:05:40 +00005631 int argSize = args.size();
5632 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005633 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005634 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005635 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005636 }
5637 break;
5638 }
5639 }
5640
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005641 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005642 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005643
Austin Borgered99f642023-06-01 16:51:35 -07005644 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005645
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005646 CameraParameters p = state.second->getShimParams();
5647 if (!p.isEmpty()) {
5648 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5649 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005650 }
5651
5652 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005653 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005654 // log the current open session info
5655 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005656 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005657 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005658 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005659
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005660 }
5661
5662 if (stateLocked) mCameraStatesLock.unlock();
5663
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005664 if (locked) mServiceLock.unlock();
5665
Emilian Peevf53f66e2017-04-11 14:29:43 +01005666 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005667
5668 dprintf(fd, "\n== Vendor tags: ==\n\n");
5669
5670 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5671 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005672 sp<VendorTagDescriptorCache> cache =
5673 VendorTagDescriptorCache::getGlobalVendorTagCache();
5674 if (cache == NULL) {
5675 dprintf(fd, "No vendor tags.\n");
5676 } else {
5677 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5678 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005679 } else {
5680 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5681 }
5682
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005683 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005684 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005685 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005686
5687 // Process dump arguments, if any
5688 int n = args.size();
5689 String16 verboseOption("-v");
5690 String16 unreachableOption("--unreachable");
5691 for (int i = 0; i < n; i++) {
5692 if (args[i] == verboseOption) {
5693 // change logging level
5694 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005695 std::string levelStr = toStdString(args[i+1]);
5696 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005697 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005698 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005699 } else if (args[i] == unreachableOption) {
5700 // Dump memory analysis
5701 // TODO - should limit be an argument parameter?
5702 UnreachableMemoryInfo info;
5703 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5704 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005705 dprintf(fd, "\n== Unable to dump unreachable memory. "
5706 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005707 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005708 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005709 std::string s = info.ToString(/*log_contents*/ true);
5710 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005711 }
5712 }
5713 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005714
5715 bool serviceLocked = tryLock(mServiceLock);
5716
5717 // Dump info from previous open sessions.
5718 // Reposition the offset to beginning of the file before reading
5719
5720 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5721 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5722 ssize_t size_read;
5723 char buf[4096];
5724 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5725 // Read data from file to a small buffer and write it to fd.
5726 write(fd, buf, size_read);
5727 if (size_read == -1) {
5728 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5729 break;
5730 }
5731 }
5732 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5733 } else {
5734 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5735 }
5736
5737 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005738 return NO_ERROR;
5739}
5740
Rucha Katakwardf223072021-06-15 10:21:00 -07005741void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005742 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005743 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005744 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005745 getFormattedCurrentTime().c_str(),
5746 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005747 dprintf(fd, " Client priority score: %d state: %d\n",
5748 clientDescriptor->getPriority().getScore(),
5749 clientDescriptor->getPriority().getState());
5750 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5751
5752 auto client = clientDescriptor->getValue();
5753 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005754 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005755
5756 client->dumpClient(fd, args);
5757}
5758
Austin Borgered99f642023-06-01 16:51:35 -07005759void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005760 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005761 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005762}
5763
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005764void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005765 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005766
5767 Mutex::Autolock l(mLogLock);
5768 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005769 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005770 }
5771
5772 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005773 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005774 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005775 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005776 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005777 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005778}
5779
Austin Borgered99f642023-06-01 16:51:35 -07005780void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005781 Mutex::Autolock lock(mLogLock);
5782 if (!isClientWatchedLocked(client)) { return; }
5783
5784 std::vector<std::string> dumpVector;
5785 client->dumpWatchedEventsToVector(dumpVector);
5786
5787 if (dumpVector.empty()) { return; }
5788
Austin Borgered99f642023-06-01 16:51:35 -07005789 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005790
Austin Borgered99f642023-06-01 16:51:35 -07005791 std::string currentTime = getFormattedCurrentTime();
5792 dumpString << "Cached @ ";
5793 dumpString << currentTime;
5794 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005795
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005796 size_t i = dumpVector.size();
5797
5798 // Store the string in reverse order (latest last)
5799 while (i > 0) {
5800 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005801 dumpString << cameraId;
5802 dumpString << ":";
5803 dumpString << client->getPackageName();
5804 dumpString << " ";
5805 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005806 }
5807
Austin Borgered99f642023-06-01 16:51:35 -07005808 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005809}
5810
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005811void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005812 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005813 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5814 if (mTorchClientMap[i] == who) {
5815 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005816 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005817 status_t res = mFlashlight->setTorchMode(cameraId, false);
5818 if (res) {
5819 ALOGE("%s: torch client died but couldn't turn off torch: "
5820 "%s (%d)", __FUNCTION__, strerror(-res), res);
5821 return;
5822 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005823 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005824 break;
5825 }
5826 }
5827}
5828
Ruben Brunkcc776712015-02-17 20:18:47 -08005829/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005830
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005831 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005832 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5833 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005834 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005835 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005836 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005837
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005838 // check torch client
5839 handleTorchClientBinderDied(who);
5840
5841 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005842 if(!evictClientIdByRemote(who)) {
5843 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005844 return;
5845 }
5846
Ruben Brunkcc776712015-02-17 20:18:47 -08005847 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5848 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005849}
5850
Austin Borgered99f642023-06-01 16:51:35 -07005851void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005852 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005853}
5854
Austin Borgered99f642023-06-01 16:51:35 -07005855void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005856 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005857 // Do not lock mServiceLock here or can get into a deadlock from
5858 // connect() -> disconnect -> updateStatus
5859
5860 auto state = getCameraState(cameraId);
5861
5862 if (state == nullptr) {
5863 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005864 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005865 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005866 }
5867
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005868 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5869 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5870 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005871 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005872 return;
5873 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005874
Biswarup Pal37a75182024-01-16 15:53:35 +00005875 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5876 CameraMetadata cameraInfo;
5877 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005878 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005879 if (res != OK) {
5880 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5881 __FUNCTION__, cameraId.c_str());
5882 } else {
5883 int32_t deviceId = getDeviceId(cameraInfo);
5884 if (deviceId != kDefaultDeviceId) {
5885 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5886 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5887 static_cast<camera_metadata_enum_android_lens_facing_t>(
5888 lensFacingEntry.data.u8[0]);
5889 std::string mappedCameraId;
5890 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5891 mappedCameraId = kVirtualDeviceBackCameraId;
5892 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5893 mappedCameraId = kVirtualDeviceFrontCameraId;
5894 } else {
5895 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5896 __func__);
5897 }
5898 if (!mappedCameraId.empty()) {
5899 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5900 }
5901 }
5902 }
5903 }
5904
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005905 // Collect the logical cameras without holding mStatusLock in updateStatus
5906 // as that can lead to a deadlock(b/162192331).
5907 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005908 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005909 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005910 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005911 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005912 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005913 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5914 auto [deviceId, mappedCameraId] =
5915 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005916
Biswarup Pal37a75182024-01-16 15:53:35 +00005917 if (status != StatusInternal::ENUMERATING) {
5918 // Update torch status if it has a flash unit.
5919 Mutex::Autolock al(mTorchStatusMutex);
5920 TorchModeStatus torchStatus;
5921 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5922 NAME_NOT_FOUND) {
5923 TorchModeStatus newTorchStatus =
5924 status == StatusInternal::PRESENT ?
5925 TorchModeStatus::AVAILABLE_OFF :
5926 TorchModeStatus::NOT_AVAILABLE;
5927 if (torchStatus != newTorchStatus) {
5928 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5929 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005930 }
5931 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005932
Biswarup Pal37a75182024-01-16 15:53:35 +00005933 Mutex::Autolock lock(mStatusListenerLock);
5934 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5935 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005936
Biswarup Pal37a75182024-01-16 15:53:35 +00005937 for (auto& listener : mListenerList) {
5938 bool isVendorListener = listener->isVendorListener();
5939 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5940 listener->getListenerPid(), listener->getListenerUid())) {
5941 ALOGV("Skipping discovery callback for system-only camera device %s",
5942 cameraId.c_str());
5943 continue;
5944 }
5945
5946 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5947 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005948 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005949 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005950 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5951 ret.exceptionCode());
5952 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005953 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005954}
5955
Austin Borgered99f642023-06-01 16:51:35 -07005956void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005957 const std::string& clientPackageName, bool sharedMode) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005958 auto state = getCameraState(cameraId);
5959 if (state == nullptr) {
5960 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005961 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005962 return;
5963 }
5964 if (open) {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005965 if (flags::camera_multi_client() && sharedMode) {
5966 state->addClientPackage(clientPackageName);
5967 } else {
5968 state->setClientPackage(clientPackageName);
5969 }
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005970 } else {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005971 if (flags::camera_multi_client() && sharedMode) {
5972 state->removeClientPackage(clientPackageName);
5973 } else {
5974 state->setClientPackage(std::string());
5975 }
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005976 }
5977
Biswarup Pal37a75182024-01-16 15:53:35 +00005978 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5979 auto [deviceId, mappedCameraId] =
5980 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5981
Shuzhen Wang695044d2020-03-06 09:02:23 -08005982 Mutex::Autolock lock(mStatusListenerLock);
5983
5984 for (const auto& it : mListenerList) {
5985 if (!it->isOpenCloseCallbackAllowed()) {
5986 continue;
5987 }
5988
5989 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005990 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005991 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5992 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005993 } else {
Jyoti Bhayana1f9600b2024-10-29 20:25:32 -07005994 if (!flags::camera_multi_client() || !sharedMode || (sharedMode &&
5995 mActiveClientManager.getCameraClient(cameraId) == nullptr)) {
5996 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
5997 }
Shuzhen Wang695044d2020-03-06 09:02:23 -08005998 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005999
6000 it->handleBinderStatus(ret,
6001 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
6002 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08006003 }
6004}
6005
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006006template<class Func>
6007void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07006008 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006009 std::initializer_list<StatusInternal> rejectSourceStates,
6010 Func onStatusUpdatedLocked) {
6011 Mutex::Autolock lock(mStatusLock);
6012 StatusInternal oldStatus = mStatus;
6013 mStatus = status;
6014
6015 if (oldStatus == status) {
6016 return;
6017 }
6018
6019 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07006020 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006021
6022 if (oldStatus == StatusInternal::NOT_PRESENT &&
6023 (status != StatusInternal::PRESENT &&
6024 status != StatusInternal::ENUMERATING)) {
6025
6026 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
6027 __FUNCTION__);
6028 mStatus = oldStatus;
6029 return;
6030 }
6031
6032 /**
6033 * Sometimes we want to conditionally do a transition.
6034 * For example if a client disconnects, we want to go to PRESENT
6035 * only if we weren't already in NOT_PRESENT or ENUMERATING.
6036 */
6037 for (auto& rejectStatus : rejectSourceStates) {
6038 if (oldStatus == rejectStatus) {
6039 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07006040 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006041 mStatus = oldStatus;
6042 return;
6043 }
6044 }
6045
6046 onStatusUpdatedLocked(cameraId, status);
6047}
6048
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006049status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07006050 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006051 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006052 if (!status) {
6053 return BAD_VALUE;
6054 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006055 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6056 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006057 // invalid camera ID or the camera doesn't have a flash unit
6058 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006059 }
6060
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006061 *status = mTorchStatusMap.valueAt(index);
6062 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006063}
6064
Austin Borgered99f642023-06-01 16:51:35 -07006065status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006066 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006067 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6068 if (index == NAME_NOT_FOUND) {
6069 return BAD_VALUE;
6070 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006071 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006072
6073 return OK;
6074}
6075
Austin Borgered99f642023-06-01 16:51:35 -07006076std::list<std::string> CameraService::getLogicalCameras(
6077 const std::string& physicalCameraId) {
6078 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006079 Mutex::Autolock lock(mCameraStatesLock);
6080 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006081 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6082 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006083 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006084 }
6085 return retList;
6086}
6087
6088void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006089 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006090 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006091 // mStatusListenerLock is expected to be locked
6092 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006093 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006094 // Note: we check only the deviceKind of the physical camera id
6095 // since, logical camera ids and their physical camera ids are
6096 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006097 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6098 listener->getListenerPid(), listener->getListenerUid())) {
6099 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006100 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006101 continue;
6102 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006103 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006104 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006105 listener->handleBinderStatus(ret,
6106 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6107 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6108 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006109 }
6110 }
6111}
6112
Svet Ganova453d0d2018-01-11 15:37:58 -08006113void CameraService::blockClientsForUid(uid_t uid) {
6114 const auto clients = mActiveClientManager.getAll();
6115 for (auto& current : clients) {
6116 if (current != nullptr) {
6117 const auto basicClient = current->getValue();
6118 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6119 basicClient->block();
6120 }
6121 }
6122 }
6123}
6124
Michael Grooverd1d435a2018-12-18 17:39:42 -08006125void CameraService::blockAllClients() {
6126 const auto clients = mActiveClientManager.getAll();
6127 for (auto& current : clients) {
6128 if (current != nullptr) {
6129 const auto basicClient = current->getValue();
6130 if (basicClient.get() != nullptr) {
6131 basicClient->block();
6132 }
6133 }
6134 }
6135}
6136
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006137void CameraService::blockPrivacyEnabledClients() {
6138 const auto clients = mActiveClientManager.getAll();
6139 for (auto& current : clients) {
6140 if (current != nullptr) {
6141 const auto basicClient = current->getValue();
6142 if (basicClient.get() != nullptr) {
6143 std::string pkgName = basicClient->getPackageName();
6144 bool cameraPrivacyEnabled =
6145 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6146 if (cameraPrivacyEnabled) {
6147 basicClient->block();
6148 }
6149 }
6150 }
6151 }
6152}
6153
Svet Ganova453d0d2018-01-11 15:37:58 -08006154// NOTE: This is a remote API - make sure all args are validated
6155status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006156 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006157 return PERMISSION_DENIED;
6158 }
6159 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6160 return BAD_VALUE;
6161 }
Austin Borgered99f642023-06-01 16:51:35 -07006162 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006163 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006164 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006165 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006166 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006167 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006168 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006169 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006170 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006171 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006172 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006173 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006174 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006175 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006176 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006177 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006178 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006179 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006180 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006181 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006182 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006183 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006184 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006185 handleClearStreamUseCaseOverrides();
6186 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006187 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006188 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006189 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006190 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006191 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006192 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006193 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006194 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006195 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006196 }
6197 printHelp(err);
6198 return BAD_VALUE;
6199}
6200
6201status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006202 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006203
Svet Ganova453d0d2018-01-11 15:37:58 -08006204 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006205 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006206 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006207 } else if ((args[2] != toString16("idle"))) {
6208 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006209 return BAD_VALUE;
6210 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006211
6212 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006213 if (args.size() >= 5 && args[3] == toString16("--user")) {
6214 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006215 }
6216
6217 uid_t uid;
6218 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6219 return BAD_VALUE;
6220 }
6221
6222 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006223 return NO_ERROR;
6224}
6225
6226status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006227 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006228
6229 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006230 if (args.size() >= 4 && args[2] == toString16("--user")) {
6231 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006232 }
6233
6234 uid_t uid;
6235 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006236 return BAD_VALUE;
6237 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006238
6239 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006240 return NO_ERROR;
6241}
6242
6243status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006244 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006245
6246 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006247 if (args.size() >= 4 && args[2] == toString16("--user")) {
6248 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006249 }
6250
6251 uid_t uid;
6252 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006253 return BAD_VALUE;
6254 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006255
6256 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006257 return dprintf(out, "active\n");
6258 } else {
6259 return dprintf(out, "idle\n");
6260 }
6261}
6262
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006263status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006264 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006265 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6266 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6267 Mutex::Autolock lock(mServiceLock);
6268
6269 mOverrideRotateAndCropMode = rotateValue;
6270
6271 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6272
6273 const auto clients = mActiveClientManager.getAll();
6274 for (auto& current : clients) {
6275 if (current != nullptr) {
6276 const auto basicClient = current->getValue();
6277 if (basicClient.get() != nullptr) {
6278 basicClient->setRotateAndCropOverride(rotateValue);
6279 }
6280 }
6281 }
6282
6283 return OK;
6284}
6285
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006286status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6287 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006288 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006289 if ((*end != '\0') ||
6290 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6291 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6292 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6293 return BAD_VALUE;
6294 }
6295
6296 Mutex::Autolock lock(mServiceLock);
6297 mOverrideAutoframingMode = autoframingValue;
6298
6299 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6300
6301 const auto clients = mActiveClientManager.getAll();
6302 for (auto& current : clients) {
6303 if (current != nullptr) {
6304 const auto basicClient = current->getValue();
6305 if (basicClient.get() != nullptr) {
6306 basicClient->setAutoframingOverride(autoframingValue);
6307 }
6308 }
6309 }
6310
6311 return OK;
6312}
6313
Ravneetaeb20dc2022-03-30 05:33:03 +00006314status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006315 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006316
6317 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6318
6319 Mutex::Autolock lock(mServiceLock);
6320
6321 mCameraServiceWatchdogEnabled = enableWatchdog;
6322
6323 const auto clients = mActiveClientManager.getAll();
6324 for (auto& current : clients) {
6325 if (current != nullptr) {
6326 const auto basicClient = current->getValue();
6327 if (basicClient.get() != nullptr) {
6328 basicClient->setCameraServiceWatchdog(enableWatchdog);
6329 }
6330 }
6331 }
6332
6333 return OK;
6334}
6335
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006336status_t CameraService::handleGetRotateAndCrop(int out) {
6337 Mutex::Autolock lock(mServiceLock);
6338
6339 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6340}
6341
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006342status_t CameraService::handleGetAutoframing(int out) {
6343 Mutex::Autolock lock(mServiceLock);
6344
6345 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6346}
6347
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006348status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6349 char *endPtr;
6350 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006351 std::string maskString = toStdString(args[1]);
6352 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006353
6354 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006355 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006356 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6357
6358 Mutex::Autolock lock(mServiceLock);
6359
6360 mImageDumpMask = maskValue;
6361
6362 return OK;
6363}
6364
6365status_t CameraService::handleGetImageDumpMask(int out) {
6366 Mutex::Autolock lock(mServiceLock);
6367
6368 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6369}
6370
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006371status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006372 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006373 if (errno != 0) return BAD_VALUE;
6374
6375 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6376 Mutex::Autolock lock(mServiceLock);
6377
6378 mOverrideCameraMuteMode = (muteValue == 1);
6379
6380 const auto clients = mActiveClientManager.getAll();
6381 for (auto& current : clients) {
6382 if (current != nullptr) {
6383 const auto basicClient = current->getValue();
6384 if (basicClient.get() != nullptr) {
6385 if (basicClient->supportsCameraMute()) {
6386 basicClient->setCameraMute(mOverrideCameraMuteMode);
6387 }
6388 }
6389 }
6390 }
6391
6392 return OK;
6393}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006394
Shuzhen Wang16610a62022-12-15 22:38:07 -08006395status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6396 std::vector<int64_t> useCasesOverride;
6397 for (size_t i = 1; i < args.size(); i++) {
6398 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006399 std::string arg = toStdString(args[i]);
6400 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006401 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006402 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006403 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006404 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006405 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006406 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006407 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006408 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006409 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006410 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006411 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006412 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006413 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6414 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006415 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006416 return BAD_VALUE;
6417 }
6418 useCasesOverride.push_back(useCase);
6419 }
6420
6421 Mutex::Autolock lock(mServiceLock);
6422 mStreamUseCaseOverrides = std::move(useCasesOverride);
6423
6424 return OK;
6425}
6426
6427void CameraService::handleClearStreamUseCaseOverrides() {
6428 Mutex::Autolock lock(mServiceLock);
6429 mStreamUseCaseOverrides.clear();
6430}
6431
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006432status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6433 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006434 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006435 if ((*end != '\0') ||
6436 (zoomOverrideValue != -1 &&
6437 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6438 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6439 return BAD_VALUE;
6440 }
6441
6442 Mutex::Autolock lock(mServiceLock);
6443 mZoomOverrideValue = zoomOverrideValue;
6444
6445 const auto clients = mActiveClientManager.getAll();
6446 for (auto& current : clients) {
6447 if (current != nullptr) {
6448 const auto basicClient = current->getValue();
6449 if (basicClient.get() != nullptr) {
6450 if (basicClient->supportsZoomOverride()) {
6451 basicClient->setZoomOverride(mZoomOverrideValue);
6452 }
6453 }
6454 }
6455 }
6456
6457 return OK;
6458}
6459
Avichal Rakesh84147132021-11-11 17:47:11 -08006460status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006461 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006462 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006463 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006464 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006465 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006466 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006467 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006468 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006469 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006470 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006471 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006472 dprintf(outFd, "Camera service watch commands:\n"
6473 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6474 " starts watching the provided tags for clients with provided package\n"
6475 " recognizes tag shorthands like '3a'\n"
6476 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006477 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006478 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006479 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006480 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006481 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006482 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006483 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006484}
6485
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006486status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6487 Mutex::Autolock lock(mLogLock);
6488 size_t tagsIdx; // index of '-m'
6489 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006490 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006491 if (tagsIdx < args.size() - 1) {
6492 tags = args[tagsIdx + 1];
6493 } else {
6494 dprintf(outFd, "No tags provided.\n");
6495 return BAD_VALUE;
6496 }
6497
6498 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006499 // watch all clients if no clients are provided
6500 String16 clients = toString16(kWatchAllClientsFlag);
6501 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006502 clientsIdx++);
6503 if (clientsIdx < args.size() - 1) {
6504 clients = args[clientsIdx + 1];
6505 }
Austin Borgered99f642023-06-01 16:51:35 -07006506 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006507
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006508 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006509 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006510
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006511 bool serviceLock = tryLock(mServiceLock);
6512 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006513 auto cameraClients = mActiveClientManager.getAll();
6514 for (const auto &clientDescriptor: cameraClients) {
6515 if (clientDescriptor == nullptr) { continue; }
6516 sp<BasicClient> client = clientDescriptor->getValue();
6517 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006518
6519 if (isClientWatchedLocked(client.get())) {
6520 client->startWatchingTags(mMonitorTags, outFd);
6521 numWatchedClients++;
6522 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006523 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006524 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6525
6526 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006527 return OK;
6528}
6529
6530status_t CameraService::stopWatchingTags(int outFd) {
6531 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006532 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006533 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006534
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006535 mWatchedClientPackages.clear();
6536 mWatchedClientsDumpCache.clear();
6537
6538 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006539 auto cameraClients = mActiveClientManager.getAll();
6540 for (const auto &clientDescriptor : cameraClients) {
6541 if (clientDescriptor == nullptr) { continue; }
6542 sp<BasicClient> client = clientDescriptor->getValue();
6543 if (client.get() == nullptr) { continue; }
6544 client->stopWatchingTags(outFd);
6545 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006546 dprintf(outFd, "Stopped watching all clients.\n");
6547 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006548 return OK;
6549}
6550
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006551status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6552 Mutex::Autolock lock(mLogLock);
6553 size_t clearedSize = mWatchedClientsDumpCache.size();
6554 mWatchedClientsDumpCache.clear();
6555 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6556 return OK;
6557}
6558
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006559status_t CameraService::printWatchedTags(int outFd) {
6560 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006561 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006562
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006563 bool printedSomething = false; // tracks if any monitoring information was printed
6564 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006565
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006566 bool serviceLock = tryLock(mServiceLock);
6567 // get all watched clients that are currently connected
6568 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6569 if (clientDescriptor == nullptr) { continue; }
6570
6571 sp<BasicClient> client = clientDescriptor->getValue();
6572 if (client.get() == nullptr) { continue; }
6573 if (!isClientWatchedLocked(client.get())) { continue; }
6574
6575 std::vector<std::string> dumpVector;
6576 client->dumpWatchedEventsToVector(dumpVector);
6577
6578 size_t printIdx = dumpVector.size();
6579 if (printIdx == 0) {
6580 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006581 }
6582
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006583 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006584 const std::string &cameraId = clientDescriptor->getKey();
6585 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006586 while(printIdx > 0) {
6587 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006588 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006589 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006590 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006591 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006592 printedSomething = true;
6593
6594 connectedMonitoredClients.emplace(client->getPackageName());
6595 }
6596 if (serviceLock) { mServiceLock.unlock(); }
6597
6598 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6599 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006600 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006601 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6602 continue;
6603 }
6604
Austin Borgered99f642023-06-01 16:51:35 -07006605 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006606 dprintf(outFd, "%s\n", kv.second.c_str());
6607 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006608 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006609
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006610 if (!printedSomething) {
6611 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006612 }
6613
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006614 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006615}
6616
Avichal Rakesh84147132021-11-11 17:47:11 -08006617// Print all events in vector `events' that came after lastPrintedEvent
6618void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006619 const std::string &cameraId,
6620 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006621 const std::vector<std::string> &events,
6622 const std::string &lastPrintedEvent) {
6623 if (events.empty()) { return; }
6624
6625 // index of lastPrintedEvent in events.
6626 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6627 size_t lastPrintedIdx;
6628 for (lastPrintedIdx = 0;
6629 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6630 lastPrintedIdx++);
6631
6632 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6633
Avichal Rakesh84147132021-11-11 17:47:11 -08006634 // print events in chronological order (latest event last)
6635 size_t idxToPrint = lastPrintedIdx;
6636 do {
6637 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006638 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6639 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006640 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006641}
6642
6643// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6644// command should be interrupted if the user presses the return key, or if user loses any way to
6645// signal interrupt.
6646// If timeoutMs == 0, this function will always return false
6647bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6648 struct timeval startTime;
6649 int startTimeError = gettimeofday(&startTime, nullptr);
6650 if (startTimeError) {
6651 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6652 return true;
6653 }
6654
6655 const nfds_t numFds = 1;
6656 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6657
6658 struct timeval currTime;
6659 char buffer[2];
6660 while(true) {
6661 int currTimeError = gettimeofday(&currTime, nullptr);
6662 if (currTimeError) {
6663 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6664 return true;
6665 }
6666
6667 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6668 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6669 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6670
6671 if (remainingTimeMs <= 0) {
6672 // No user interrupt within timeoutMs, don't interrupt watch command
6673 return false;
6674 }
6675
6676 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6677 if (numFdsUpdated < 0) {
6678 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6679 return true;
6680 }
6681
6682 if (numFdsUpdated == 0) {
6683 // No user input within timeoutMs, don't interrupt watch command
6684 return false;
6685 }
6686
6687 if (!(pollFd.revents & POLLIN)) {
6688 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6689 return true;
6690 }
6691
6692 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6693 if (sizeRead < 0) {
6694 dprintf(outFd, "Error reading user input. Exiting.\n");
6695 return true;
6696 }
6697
6698 if (sizeRead == 0) {
6699 // Reached end of input fd (can happen if input is piped)
6700 // User has no way to signal an interrupt, so interrupt here
6701 return true;
6702 }
6703
6704 if (buffer[0] == '\n') {
6705 // User pressed return, interrupt watch command.
6706 return true;
6707 }
6708 }
6709}
6710
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006711status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6712 int inFd, int outFd) {
6713 // Figure out refresh interval, if present in args
6714 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006715 if (args.size() > 2) {
6716 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006717 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006718 intervalIdx++);
6719
6720 size_t intervalValIdx = intervalIdx + 1;
6721 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006722 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006723 if (errno) { return BAD_VALUE; }
6724 }
6725 }
6726
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006727 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6728 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006729
Avichal Rakesh84147132021-11-11 17:47:11 -08006730 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006731 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006732
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006733 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006734 bool serviceLock = tryLock(mServiceLock);
6735 auto cameraClients = mActiveClientManager.getAll();
6736 if (serviceLock) { mServiceLock.unlock(); }
6737
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006738 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006739 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006740 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006741
6742 sp<BasicClient> client = clientDescriptor->getValue();
6743 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006744 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006745
Austin Borgered99f642023-06-01 16:51:35 -07006746 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006747 // This also initializes the map entries with an empty string
6748 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6749
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006750 std::vector<std::string> latestEvents;
6751 client->dumpWatchedEventsToVector(latestEvents);
6752
6753 if (!latestEvents.empty()) {
6754 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006755 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006756 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006757 latestEvents,
6758 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006759 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006760 }
6761 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006762 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006763 break;
6764 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006765 }
6766 return OK;
6767}
6768
Austin Borgered99f642023-06-01 16:51:35 -07006769void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006770 mWatchedClientPackages.clear();
6771
Austin Borgered99f642023-06-01 16:51:35 -07006772 std::istringstream iss(clients);
6773 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006774
Austin Borgered99f642023-06-01 16:51:35 -07006775 while (std::getline(iss, nextClient, ',')) {
6776 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006777 // Don't need to track any other package if 'all' is present
6778 mWatchedClientPackages.clear();
6779 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6780 break;
6781 }
6782
6783 // track package names
6784 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006785 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006786}
6787
Svet Ganova453d0d2018-01-11 15:37:58 -08006788status_t CameraService::printHelp(int out) {
6789 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006790 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6791 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6792 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006793 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6794 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6795 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006796 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6797 " Valid values 0=false, 1=true, 2=auto\n"
6798 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006799 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6800 " Valid values 0=OFF, 1=ON for JPEG\n"
6801 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006802 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006803 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6804 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6805 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6806 " on. In case the number of usecases is smaller than the number of streams, the\n"
6807 " last use case is assigned to all the remaining streams. In case of multiple\n"
6808 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6809 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6810 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6811 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006812 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6813 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006814 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6815 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006816 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006817 " help print this message\n");
6818}
6819
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006820bool CameraService::isClientWatched(const BasicClient *client) {
6821 Mutex::Autolock lock(mLogLock);
6822 return isClientWatchedLocked(client);
6823}
6824
6825bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6826 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6827 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6828}
6829
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006830int32_t CameraService::updateAudioRestriction() {
6831 Mutex::Autolock lock(mServiceLock);
6832 return updateAudioRestrictionLocked();
6833}
6834
6835int32_t CameraService::updateAudioRestrictionLocked() {
6836 int32_t mode = 0;
6837 // iterate through all active client
6838 for (const auto& i : mActiveClientManager.getAll()) {
6839 const auto clientSp = i->getValue();
6840 mode |= clientSp->getAudioRestriction();
6841 }
6842
6843 bool modeChanged = (mAudioRestriction != mode);
6844 mAudioRestriction = mode;
6845 if (modeChanged) {
6846 mAppOps.setCameraAudioRestriction(mode);
6847 }
6848 return mode;
6849}
6850
Austin Borgered99f642023-06-01 16:51:35 -07006851status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006852 sp<BasicClient> clientSp) {
6853 std::unique_ptr<AutoConditionLock> lock =
6854 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6855 status_t res = NO_ERROR;
6856 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006857 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006858 mInjectionStatusListener->notifyInjectionError(
6859 externalCamId, UNKNOWN_TRANSACTION);
6860 clientSp->notifyError(
6861 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6862 CaptureResultExtras());
6863
6864 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6865 // other clients from connecting in mServiceLockWrapper if held
6866 mServiceLock.unlock();
6867
6868 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006869 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006870 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006871 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006872
6873 // Reacquire mServiceLock
6874 mServiceLock.lock();
6875 }
6876
6877 return res;
6878}
6879
Cliff Wud3a05312021-04-26 23:07:31 +08006880void CameraService::clearInjectionParameters() {
6881 {
6882 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006883 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006884 mInjectionInternalCamId = "";
6885 }
6886 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006887 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006888}
6889
Biswarup Pal37a75182024-01-16 15:53:35 +00006890} // namespace android