blob: 8d44e06906e07d69c50e4dbb55b33e67a4aa2f1e [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
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800567 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
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
Austin Borgered99f642023-06-01 16:51:35 -0700577 clientToDisconnectOnline = removeClientLocked(cameraId);
578 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700579 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800580
Austin Borgered99f642023-06-01 16:51:35 -0700581 disconnectClient(cameraId, clientToDisconnectOnline);
582 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
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
Austin Borgered99f642023-06-01 16:51:35 -0700656void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800657 if (clientToDisconnect.get() != nullptr) {
658 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700659 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800660 // Notify the client of disconnection
661 clientToDisconnect->notifyError(
662 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
663 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800664 clientToDisconnect->disconnect();
665 }
666}
667
Austin Borgered99f642023-06-01 16:51:35 -0700668void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800669 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700670 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
671 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
672 if (res != OK) {
673 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700674 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700675 return;
676 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800677 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700678 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800679}
680
Austin Borgered99f642023-06-01 16:51:35 -0700681void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700682 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
683 Mutex::Autolock al(mTorchStatusMutex);
684 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
685}
686
Austin Borgered99f642023-06-01 16:51:35 -0700687void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800688 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000689 // Get the device id and app-visible camera id for the given HAL-visible camera id.
690 auto [deviceId, mappedCameraId] =
691 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
692
Rucha Katakwar38284522021-11-10 11:25:21 -0800693 Mutex::Autolock lock(mStatusListenerLock);
694 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000695 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
696 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700697 i->handleBinderStatus(ret,
698 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
699 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800700 }
701}
702
Austin Borgered99f642023-06-01 16:51:35 -0700703void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700704 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800705 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700706 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800707
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800708 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800709 status_t res = getTorchStatusLocked(cameraId, &status);
710 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700711 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700712 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800713 return;
714 }
715 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800716 return;
717 }
718
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800719 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800720 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800721 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
722 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800723 return;
724 }
725
Ruben Brunkcc776712015-02-17 20:18:47 -0800726 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700727 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700728 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700729 auto iter = mTorchUidMap.find(cameraId);
730 if (iter != mTorchUidMap.end()) {
731 int oldUid = iter->second.second;
732 int newUid = iter->second.first;
733 BatteryNotifier& notifier(BatteryNotifier::getInstance());
734 if (oldUid != newUid) {
735 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800736 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700737 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700738 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800739 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700740 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700741 }
742 iter->second.second = newUid;
743 } else {
744 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800745 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700746 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700747 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700748 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700749 }
750 }
751 }
752 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700753 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800754}
755
Austin Borger249e6592024-03-10 22:28:11 -0700756bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700757 // Returns false if this is not an automotive device type.
758 if (!isAutomotiveDevice())
759 return false;
760
761 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700762 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700763 return false;
764
765 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
766 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
767 // This isn't a known camera ID, so it's not a system camera.
768 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
769 return false;
770 }
771
772 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
773 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
774 return false;
775 }
776
777 CameraMetadata cameraInfo;
778 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000779 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700780 if (res != OK){
781 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
782 cam_id.c_str());
783 return false;
784 }
785
786 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
787 if (auto_location.count != 1)
788 return false;
789
790 uint8_t location = auto_location.data.u8[0];
791 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
792 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
793 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
794 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
795 return false;
796 }
797
798 return true;
799}
800
Austin Borger65e64642024-06-11 15:58:23 -0700801Status CameraService::getNumberOfCameras(int32_t type,
802 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000803 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700804 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700805 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000806 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700807 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000808 return Status::ok();
809 }
810
Emilian Peevaee727d2017-05-04 16:35:48 +0100811 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700812 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800813 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
814 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 switch (type) {
816 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700817 if (hasSystemCameraPermissions) {
818 *numCameras = static_cast<int>(mNormalDeviceIds.size());
819 } else {
820 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
821 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700823 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700824 if (hasSystemCameraPermissions) {
825 *numCameras = mNumberOfCameras;
826 } else {
827 *numCameras = mNumberOfCamerasWithoutSystemCamera;
828 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700830 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700832 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800833 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
834 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700835 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837}
838
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700839Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700840 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700841 /* out */
842 hardware::camera2::impl::CameraMetadataNative* request) {
843 ATRACE_CALL();
844
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700845 if (!mInitialized) {
846 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
847 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
848 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
849 }
850
Austin Borger65e64642024-06-11 15:58:23 -0700851 std::optional<std::string> cameraIdOptional =
852 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000853 if (!cameraIdOptional.has_value()) {
854 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700855 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000856 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
857 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
858 }
859 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700860
861 binder::Status res;
862 if (request == nullptr) {
863 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
864 "Camera %s: Error creating default request", cameraId.c_str());
865 return res;
866 }
867 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
868 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
869 cameraId, templateId, &tempId);
870 if (!res.isOk()) {
871 ALOGE("%s: Camera %s: failed to map request Template %d",
872 __FUNCTION__, cameraId.c_str(), templateId);
873 return res;
874 }
875
876 if (shouldRejectSystemCameraConnection(cameraId)) {
877 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
878 "request for system only device %s: ", cameraId.c_str());
879 }
880
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700881 CameraMetadata metadata;
882 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
883 if (err == OK) {
884 request->swap(metadata);
885 } else if (err == BAD_VALUE) {
886 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
887 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
888 cameraId.c_str(), templateId, strerror(-err), err);
889 } else {
890 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
891 "Camera %s: Error creating default request for template %d: %s (%d)",
892 cameraId.c_str(), templateId, strerror(-err), err);
893 }
894 return res;
895}
896
897Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700898 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700899 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700900 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700901 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700902 ATRACE_CALL();
903
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700904 if (!mInitialized) {
905 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
906 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
907 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
908 }
909
Austin Borger65e64642024-06-11 15:58:23 -0700910 std::optional<std::string> cameraIdOptional =
911 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000912 if (!cameraIdOptional.has_value()) {
913 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700914 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000915 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
916 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
917 }
918 std::string cameraId = cameraIdOptional.value();
919
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700920 if (supported == nullptr) {
921 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
922 unresolvedCameraId.c_str());
923 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
924 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
925 }
926
927 if (shouldRejectSystemCameraConnection(cameraId)) {
928 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
929 "session configuration with parameters support for system only device %s: ",
930 cameraId.c_str());
931 }
932
Avichal Rakeshe005df52024-09-25 17:13:27 -0700933 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700934 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
935
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700936 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
937 sessionConfiguration, overrideForPerfClass, supported);
938 if (flags::analytics_24q3()) {
939 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
940 getCallingUid(), sessionConfiguration, ret);
941 }
942 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700943}
944
945Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
946 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
947 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700948 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700949 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
950 cameraId, sessionConfiguration, overrideForPerfClass,
951 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700952 binder::Status res;
953 switch (ret) {
954 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700955 // Expected. Do Nothing.
956 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700957 case INVALID_OPERATION: {
958 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700959 "Camera %s: Session configuration with parameters supported query not "
960 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700961 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700962 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
963 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
964 *supported = false;
965 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700966 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700967 break;
968 case NAME_NOT_FOUND: {
969 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
970 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
971 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
972 *supported = false;
973 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
974 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700975 break;
976 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700977 std::string msg = fmt::sprintf(
978 "Unable to retrieve session configuration support for camera "
979 "device %s: Error: %s (%d)",
980 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700981 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700982 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
983 *supported = false;
984 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700985 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700986 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700987 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700988}
989
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800990Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000991 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700992 const SessionConfiguration& sessionConfiguration,
993 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000994 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800995 ATRACE_CALL();
996
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800997 if (outMetadata == nullptr) {
998 std::string msg =
999 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1000 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1001 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1002 }
1003
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001004 if (!mInitialized) {
1005 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1006 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1007 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1008 }
1009
Austin Borger65e64642024-06-11 15:58:23 -07001010 std::optional<std::string> cameraIdOptional =
1011 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001012 if (!cameraIdOptional.has_value()) {
1013 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001014 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001015 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1016 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1017 }
1018 std::string cameraId = cameraIdOptional.value();
1019
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001020 if (shouldRejectSystemCameraConnection(cameraId)) {
1021 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1022 "Unable to retrieve camera"
1023 "characteristics for system only device %s: ",
1024 cameraId.c_str());
1025 }
1026
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001027 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1028 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesheb961c72024-09-25 17:26:26 -07001029
1030 bool sessionConfigSupported;
1031 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1032 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1033 if (!res.isOk()) {
1034 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1035 // report the correct Status to send to the client. Simply forward the error to
1036 // the client.
1037 outMetadata->clear();
1038 return res;
1039 }
1040
1041 if (!sessionConfigSupported) {
1042 std::string msg = fmt::sprintf("Session configuration not supported for camera device %s.",
1043 cameraId.c_str());
1044 outMetadata->clear();
1045 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001046 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001047
1048 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001049 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001050
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001051 switch (ret) {
1052 case OK:
1053 // Expected, no handling needed.
1054 break;
1055 case INVALID_OPERATION: {
1056 std::string msg = fmt::sprintf(
1057 "Camera %s: Session characteristics query not supported!",
1058 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001059 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001060 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1061 outMetadata->clear();
1062 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1063 }
1064 break;
1065 case NAME_NOT_FOUND: {
1066 std::string msg = fmt::sprintf(
1067 "Camera %s: Unknown camera ID.",
1068 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001069 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001070 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1071 outMetadata->clear();
1072 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001073 }
1074 break;
1075 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001076 std::string msg = fmt::sprintf(
1077 "Unable to retrieve session characteristics for camera device %s: "
1078 "Error: %s (%d)",
1079 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001080 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001081 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1082 outMetadata->clear();
1083 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001084 }
1085 }
1086
Avichal Rakesheb961c72024-09-25 17:26:26 -07001087 res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001088 if (flags::analytics_24q3()) {
1089 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1090 getCallingUid(), sessionConfiguration, res);
1091 }
1092 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001093}
1094
1095Status CameraService::filterSensitiveMetadataIfNeeded(
1096 const std::string& cameraId, CameraMetadata* metadata) {
1097 int callingPid = getCallingPid();
1098 int callingUid = getCallingUid();
1099
1100 if (callingPid == getpid()) {
1101 // Caller is cameraserver; no need to remove keys
1102 return Status::ok();
1103 }
1104
1105 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1106 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1107 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1108 metadata->clear();
1109 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1110 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1111 }
1112 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1113 // Attempting to query system only camera without system camera permission would have
1114 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1115 // for a system only camera, then the caller has the required permission.
1116 // No need to remove keys
1117 return Status::ok();
1118 }
1119
1120 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001121 // Get the device id that owns this camera.
1122 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1123 cameraId);
1124 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1125 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001126 if (hasCameraPermission) {
1127 // Caller has camera permission; no need to remove keys
1128 return Status::ok();
1129 }
1130
1131 status_t ret = metadata->removePermissionEntries(
1132 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1133 if (ret != OK) {
1134 metadata->clear();
1135 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1136 "Failed to remove camera characteristics needing camera permission "
1137 "for device %s:%s (%d)",
1138 cameraId.c_str(), strerror(-ret), ret);
1139 }
1140
1141 if (!tagsRemoved.empty()) {
1142 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1143 tagsRemoved.data(), tagsRemoved.size());
1144 if (ret != OK) {
1145 metadata->clear();
1146 return STATUS_ERROR_FMT(
1147 ERROR_INVALID_OPERATION,
1148 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1149 cameraId.c_str(), strerror(-ret), ret);
1150 }
1151 }
1152 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001153}
1154
malikakash22af94c2023-12-04 18:13:14 +00001155Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001156 const std::string& cameraId,
1157 const CameraMetadata& sessionParams) {
1158 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001159 const int pid = getCallingPid();
1160 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001161 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1162 __FUNCTION__, pid, uid);
1163 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1164 "Permission Denial: no permission to inject session params");
1165 }
1166
Biswarup Pal37a75182024-01-16 15:53:35 +00001167 // Do not allow session params injection for a virtual camera.
1168 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1169 if (deviceId != kDefaultDeviceId) {
1170 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1171 "Cannot inject session params for a virtual camera");
1172 }
1173
malikakash22af94c2023-12-04 18:13:14 +00001174 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1175 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1176
1177 auto clientDescriptor = mActiveClientManager.get(cameraId);
1178 if (clientDescriptor == nullptr) {
1179 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1180 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1181 "No active client for camera id %s", cameraId.c_str());
1182 }
1183
1184 sp<BasicClient> clientSp = clientDescriptor->getValue();
1185 status_t res = clientSp->injectSessionParams(sessionParams);
1186
1187 if (res != OK) {
1188 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1189 "Error injecting session params into camera \"%s\": %s (%d)",
1190 cameraId.c_str(), strerror(-res), res);
1191 }
1192 return Status::ok();
1193}
1194
Biswarup Pal37a75182024-01-16 15:53:35 +00001195std::optional<std::string> CameraService::resolveCameraId(
1196 const std::string& inputCameraId,
1197 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001198 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001199 if ((deviceId == kDefaultDeviceId)
1200 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1201 auto [storedDeviceId, _] =
1202 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1203 if (storedDeviceId != kDefaultDeviceId) {
1204 // Trying to access a virtual camera from default-policy device context, we should fail.
1205 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1206 inputCameraId.c_str(), deviceId);
1207 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1208 return std::nullopt;
1209 }
malikakash98260df2024-05-10 23:33:57 +00001210 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001211 }
1212
1213 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1214}
1215
Austin Borger65e64642024-06-11 15:58:23 -07001216Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1217 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1218 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001219 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001220 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001221 std::string cameraIdStr =
1222 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001223 if (cameraIdStr.empty()) {
1224 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001225 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001226 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1227 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1228 }
malikakashedb38962023-09-06 00:03:35 +00001229
Austin Borgered99f642023-06-01 16:51:35 -07001230 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001231 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1232 "characteristics for system only device %s: ", cameraIdStr.c_str());
1233 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001234
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001235 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001236 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001237 return STATUS_ERROR(ERROR_DISCONNECTED,
1238 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001239 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001240 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001241 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001242 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1243 if (hasSystemCameraPermissions) {
1244 cameraIdBound = mNumberOfCameras;
1245 }
1246 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001247 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1248 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001249 }
1250
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001251 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001252 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001253 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001254 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001255 if (err != OK) {
1256 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1257 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1258 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001259 logServiceError(std::string("Error retrieving camera info from device ")
1260 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001261 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001262
Ruben Brunkcc776712015-02-17 20:18:47 -08001263 return ret;
1264}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001265
Biswarup Pal37a75182024-01-16 15:53:35 +00001266std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1267 int32_t deviceId, int32_t devicePolicy) {
1268 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1269 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1270 std::optional<std::string> cameraIdOptional =
1271 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1272 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1273 }
1274
1275 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001276 auto callingPid = getCallingPid();
1277 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001278 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1279 callingPid, callingUid, /* checkCameraPermissions= */ false);
1280 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001281 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001282 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001283 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1284 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1285 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001286 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001287 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001288
malikakash98260df2024-05-10 23:33:57 +00001289 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001290}
1291
Biswarup Pal37a75182024-01-16 15:53:35 +00001292std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1293 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001294 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001295 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001296}
1297
Austin Borgered99f642023-06-01 16:51:35 -07001298Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001299 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1300 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001301 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001302
Zhijun He2b59be82013-09-25 10:14:30 -07001303 if (!cameraInfo) {
1304 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001305 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001306 }
1307
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001308 if (!mInitialized) {
1309 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001310 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001311 return STATUS_ERROR(ERROR_DISCONNECTED,
1312 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001313 }
1314
Austin Borger65e64642024-06-11 15:58:23 -07001315 std::optional<std::string> cameraIdOptional =
1316 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001317 if (!cameraIdOptional.has_value()) {
1318 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001319 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001320 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1321 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1322 }
1323 std::string cameraId = cameraIdOptional.value();
1324
Austin Borgered99f642023-06-01 16:51:35 -07001325 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001326 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001327 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001328 }
1329
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001330 bool overrideForPerfClass =
1331 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001332 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001333 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001334 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001335 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001336 if (res == NAME_NOT_FOUND) {
1337 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001338 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001339 strerror(-res), res);
1340 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001341 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1342 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001343 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001344 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001345 strerror(-res), res);
1346 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001347 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001348
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001349 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001350}
1351
Austin Borger65e64642024-06-11 15:58:23 -07001352Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1353 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001354 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001355 ATRACE_CALL();
1356 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001357
Austin Borger65e64642024-06-11 15:58:23 -07001358 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1359 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001360 if (!cameraIdOptional.has_value()) {
1361 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001362 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001363 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1364 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1365 }
1366 std::string cameraId = cameraIdOptional.value();
1367
Rucha Katakwar38284522021-11-10 11:25:21 -08001368 if (!mInitialized) {
1369 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1370 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1371 }
1372
Biswarup Pal37a75182024-01-16 15:53:35 +00001373 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001374 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1375 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1376 }
1377
Austin Borgered99f642023-06-01 16:51:35 -07001378 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001379 if (res != OK) {
1380 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001381 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001382 strerror(-res), res);
1383 }
1384 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1385 return Status::ok();
1386}
1387
Austin Borgered99f642023-06-01 16:51:35 -07001388std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001389 time_t now = time(nullptr);
1390 char formattedTime[64];
1391 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001392 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001393}
1394
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001395Status CameraService::getCameraVendorTagDescriptor(
1396 /*out*/
1397 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001398 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001399 if (!mInitialized) {
1400 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001401 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001402 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001403 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1404 if (globalDescriptor != nullptr) {
1405 *desc = *(globalDescriptor.get());
1406 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001407 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001408}
1409
Emilian Peev71c73a22017-03-21 16:35:51 +00001410Status CameraService::getCameraVendorTagCache(
1411 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1412 ATRACE_CALL();
1413 if (!mInitialized) {
1414 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1415 return STATUS_ERROR(ERROR_DISCONNECTED,
1416 "Camera subsystem not available");
1417 }
1418 sp<VendorTagDescriptorCache> globalCache =
1419 VendorTagDescriptorCache::getGlobalVendorTagCache();
1420 if (globalCache != nullptr) {
1421 *cache = *(globalCache.get());
1422 }
1423 return Status::ok();
1424}
1425
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001426void CameraService::clearCachedVariables() {
1427 BasicClient::BasicClient::sCameraService = nullptr;
1428}
1429
Austin Borgered99f642023-06-01 16:51:35 -07001430std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001431 int rotationOverride, int* portraitRotation, int* facing,
1432 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001433 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001434
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001435 int deviceVersion = 0;
1436
Emilian Peevf53f66e2017-04-11 14:29:43 +01001437 status_t res;
1438 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001439 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001440 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001441 if (res != OK || transport == IPCTransport::INVALID) {
1442 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001443 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001444 return std::make_pair(-1, IPCTransport::INVALID) ;
1445 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001446 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001447
Emilian Peevf53f66e2017-04-11 14:29:43 +01001448 hardware::CameraInfo info;
1449 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001450 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001451 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001452 if (res != OK) {
1453 return std::make_pair(-1, IPCTransport::INVALID);
1454 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001455 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001456 if (orientation) {
1457 *orientation = info.orientation;
1458 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001459 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001460
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001461 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001462}
1463
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001465 switch(err) {
1466 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001468 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1470 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001471 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001472 return STATUS_ERROR(ERROR_DISCONNECTED,
1473 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001474 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001475 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1476 "Camera HAL encountered error %d: %s",
1477 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001478 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001479}
1480
Austin Borger2e772b82024-10-11 16:09:57 -07001481Status CameraService::makeClient(
1482 const sp<CameraService>& cameraService, const sp<IInterface>& cameraCb,
1483 const AttributionSourceState& clientAttribution, int callingPid, bool systemNativeClient,
1484 const std::string& cameraId, int api1CameraId, int facing, int sensorOrientation,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001485 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001486 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001487 bool forceSlowJpegMode, const std::string& originalCameraId,
Austin Borger2e772b82024-10-11 16:09:57 -07001488 /*out*/ sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001489 // For HIDL devices
1490 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1491 // Create CameraClient based on device version reported by the HAL.
1492 int deviceVersion = deviceVersionAndTransport.first;
1493 switch(deviceVersion) {
1494 case CAMERA_DEVICE_API_VERSION_1_0:
1495 ALOGE("Camera using old HAL version: %d", deviceVersion);
1496 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1497 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001498 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001499 break;
1500 case CAMERA_DEVICE_API_VERSION_3_0:
1501 case CAMERA_DEVICE_API_VERSION_3_1:
1502 case CAMERA_DEVICE_API_VERSION_3_2:
1503 case CAMERA_DEVICE_API_VERSION_3_3:
1504 case CAMERA_DEVICE_API_VERSION_3_4:
1505 case CAMERA_DEVICE_API_VERSION_3_5:
1506 case CAMERA_DEVICE_API_VERSION_3_6:
1507 case CAMERA_DEVICE_API_VERSION_3_7:
1508 break;
1509 default:
1510 // Should not be reachable
1511 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1512 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1513 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001514 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001515 }
1516 }
1517 if (effectiveApiLevel == API_1) { // Camera1 API route
1518 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001519 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger2e772b82024-10-11 16:09:57 -07001520 cameraService->mAttributionAndPermissionUtils,
1521 clientAttribution, callingPid, cameraId, api1CameraId, facing,
1522 sensorOrientation, servicePid, overrideForPerfClass,
1523 rotationOverride, forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001524 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1525 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001526 } else { // Camera2 API route
1527 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1528 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger2e772b82024-10-11 16:09:57 -07001529 *client = new CameraDeviceClient(
1530 cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
1531 cameraService->mAttributionAndPermissionUtils, clientAttribution, callingPid,
1532 systemNativeClient, cameraId, facing, sensorOrientation, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001533 overrideForPerfClass, rotationOverride, originalCameraId);
1534 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001535 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001536 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001537}
1538
Austin Borgered99f642023-06-01 16:51:35 -07001539std::string CameraService::toString(std::set<userid_t> intSet) {
1540 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001541 bool first = true;
1542 for (userid_t i : intSet) {
1543 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001544 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001545 first = false;
1546 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001547 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001548 }
1549 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001550 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001551}
1552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001553int32_t CameraService::mapToInterface(TorchModeStatus status) {
1554 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1555 switch (status) {
1556 case TorchModeStatus::NOT_AVAILABLE:
1557 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1558 break;
1559 case TorchModeStatus::AVAILABLE_OFF:
1560 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1561 break;
1562 case TorchModeStatus::AVAILABLE_ON:
1563 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1564 break;
1565 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001566 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001567 }
1568 return serviceStatus;
1569}
1570
1571CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1572 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1573 switch (status) {
1574 case CameraDeviceStatus::NOT_PRESENT:
1575 serviceStatus = StatusInternal::NOT_PRESENT;
1576 break;
1577 case CameraDeviceStatus::PRESENT:
1578 serviceStatus = StatusInternal::PRESENT;
1579 break;
1580 case CameraDeviceStatus::ENUMERATING:
1581 serviceStatus = StatusInternal::ENUMERATING;
1582 break;
1583 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001584 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001585 }
1586 return serviceStatus;
1587}
1588
1589int32_t CameraService::mapToInterface(StatusInternal status) {
1590 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1591 switch (status) {
1592 case StatusInternal::NOT_PRESENT:
1593 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1594 break;
1595 case StatusInternal::PRESENT:
1596 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1597 break;
1598 case StatusInternal::ENUMERATING:
1599 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1600 break;
1601 case StatusInternal::NOT_AVAILABLE:
1602 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1603 break;
1604 case StatusInternal::UNKNOWN:
1605 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1606 break;
1607 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001608 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001609 }
1610 return serviceStatus;
1611}
1612
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001613Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001614 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001615
Austin Borgered99f642023-06-01 16:51:35 -07001616 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001617 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001618 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001619
Austin Borgerb01a8702024-07-22 16:20:34 -07001620 int callingPid = getCallingPid();
1621 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001622
Austin Borger23694432024-10-07 19:28:01 -07001623 AttributionSourceState clientAttribution =
1624 buildAttributionSource(callingPid, uid, kServiceName, kDefaultDeviceId);
1625
1626 if (!(ret = connectHelper<ICameraClient, Client>(
1627 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId, clientAttribution,
1628 /*systemNativeClient*/ false, API_1, /*shimUpdateOnly*/ true,
1629 /*oomScoreOffset*/ 0,
1630 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1631 /*rotationOverride*/
1632 hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
1633 /*forceSlowJpegMode*/ false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp))
1634 .isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001635 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001636 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001637 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001638}
1639
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001641 /*out*/
1642 CameraParameters* parameters) {
1643
1644 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1645
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001646 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001647
1648 if (parameters == NULL) {
1649 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001650 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001651 }
1652
malikakash98260df2024-05-10 23:33:57 +00001653 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001654
1655 // Check if we already have parameters
1656 {
1657 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001658 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001659 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001660 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001661 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001662 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001663 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001664 }
1665 CameraParameters p = cameraState->getShimParams();
1666 if (!p.isEmpty()) {
1667 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001668 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001669 }
1670 }
1671
Austin Borger22c5c852024-03-08 13:31:36 -08001672 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001673 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001674 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001675 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001676 // Error already logged by callee
1677 return ret;
1678 }
1679
1680 // Check for parameters again
1681 {
1682 // Scope for service lock
1683 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001684 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001685 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001686 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001687 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001688 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001689 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001690 CameraParameters p = cameraState->getShimParams();
1691 if (!p.isEmpty()) {
1692 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001693 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001694 }
1695 }
1696
Ruben Brunkcc776712015-02-17 20:18:47 -08001697 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1698 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001699 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001700}
1701
Austin Borgered99f642023-06-01 16:51:35 -07001702Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borger23694432024-10-07 19:28:01 -07001703 const AttributionSourceState& clientAttribution) const {
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001704#ifdef __BRILLO__
Austin Borger23694432024-10-07 19:28:01 -07001705 UNUSED(clientAttribution);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001706#else
Austin Borger23694432024-10-07 19:28:01 -07001707 Status allowed = validateClientPermissionsLocked(cameraId, clientAttribution);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001708 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001709 return allowed;
1710 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001711#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001712
Austin Borger22c5c852024-03-08 13:31:36 -08001713 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001714
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001715 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001716 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1717 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001718 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001719 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001720 }
1721
Ruben Brunkcc776712015-02-17 20:18:47 -08001722 if (getCameraState(cameraId) == nullptr) {
1723 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001724 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001725 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001726 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001727 }
1728
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001729 status_t err = checkIfDeviceIsUsable(cameraId);
1730 if (err != NO_ERROR) {
1731 switch(err) {
1732 case -ENODEV:
1733 case -EBUSY:
1734 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001735 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001736 default:
1737 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001738 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001739 }
1740 }
1741 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001742}
1743
Austin Borger23694432024-10-07 19:28:01 -07001744Status CameraService::validateClientPermissionsLocked(
1745 const std::string& cameraId, const AttributionSourceState& clientAttribution) const {
Austin Borgerb01a8702024-07-22 16:20:34 -07001746 int callingPid = getCallingPid();
1747 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001748
Austin Borger23694432024-10-07 19:28:01 -07001749 int clientPid = clientAttribution.pid;
1750 int clientUid = clientAttribution.uid;
1751 const std::string clientName = clientAttribution.packageName.value_or(kUnknownPackageName);
1752
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001753 if (shouldRejectSystemCameraConnection(cameraId)) {
1754 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1755 cameraId.c_str());
1756 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001757 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001758 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001759 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1760 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001761 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001762 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001763 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001764 }
1765
Biswarup Pale506e732024-03-27 13:46:20 +00001766 // Get the device id that owns this camera.
1767 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Austin Borger23694432024-10-07 19:28:01 -07001768 AttributionSourceState clientAttributionWithDeviceId = clientAttribution;
1769 clientAttributionWithDeviceId.deviceId = deviceId;
Biswarup Pale506e732024-03-27 13:46:20 +00001770
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001771 // If it's not calling from cameraserver, check the permission if the
1772 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1773 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001774 bool checkPermissionForCamera =
Austin Borger23694432024-10-07 19:28:01 -07001775 hasPermissionsForCamera(cameraId, clientAttributionWithDeviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001776 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001777 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001778 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001779 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1780 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001781 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001782 }
1783
Svet Ganova453d0d2018-01-11 15:37:58 -08001784 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001785 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001786 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001787 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1788 clientPid, clientUid);
1789 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001790 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1791 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001792 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001793 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001794 }
1795
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001796 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1797 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1798 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1799 if ((!isAutomotivePrivilegedClient(callingUid) ||
1800 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1801 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001802 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1803 return STATUS_ERROR_FMT(ERROR_DISABLED,
1804 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001805 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001806 }
1807
Austin Borger6e831c42024-07-22 13:07:56 -07001808 userid_t clientUserId = multiuser_get_user_id(clientUid);
1809
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001810 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1811 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001812
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001813 // For non-system clients : Only allow clients who are being used by the current foreground
1814 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001815 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001816 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001817 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1818 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001819 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001820 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1821 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001822 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001823 }
1824
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001825 if (flags::camera_hsum_permission()) {
1826 // If the System User tries to access the camera when the device is running in
1827 // headless system user mode, ensure that client has the required permission
1828 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001829 if (isHeadlessSystemUserMode()
1830 && (clientUserId == USER_SYSTEM)
1831 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001832 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001833 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1834 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1835 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001836 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001837 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001838 }
1839
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001840 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001841}
1842
Austin Borgered99f642023-06-01 16:51:35 -07001843status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001844 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001845 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001846 if (cameraState == nullptr) {
1847 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001848 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001849 return -ENODEV;
1850 }
1851
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001852 StatusInternal currentStatus = cameraState->getStatus();
1853 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001854 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001855 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001856 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001857 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001858 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001859 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001860 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001861 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001862
Ruben Brunkcc776712015-02-17 20:18:47 -08001863 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001864}
1865
Ruben Brunkcc776712015-02-17 20:18:47 -08001866void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001867 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001868
Ruben Brunkcc776712015-02-17 20:18:47 -08001869 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001870 auto clientDescriptor =
1871 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001872 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1874
1875 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001876 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001877
1878 if (evicted.size() > 0) {
1879 // This should never happen - clients should already have been removed in disconnect
1880 for (auto& i : evicted) {
1881 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001882 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001883 }
1884
1885 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1886 __FUNCTION__);
1887 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001888
1889 // And register a death notification for the client callback. Do
1890 // this last to avoid Binder policy where a nested Binder
1891 // transaction might be pre-empted to service the client death
1892 // notification if the client process dies before linkToDeath is
1893 // invoked.
1894 sp<IBinder> remoteCallback = client->getRemote();
1895 if (remoteCallback != nullptr) {
1896 remoteCallback->linkToDeath(this);
1897 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001898}
1899
Austin Borgered99f642023-06-01 16:51:35 -07001900status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1901 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1902 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001903 /*out*/
1904 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001905 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001906 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001907 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001908 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001909 DescriptorPtr clientDescriptor;
1910 {
1911 if (effectiveApiLevel == API_1) {
1912 // If we are using API1, any existing client for this camera ID with the same remote
1913 // should be returned rather than evicted to allow MediaRecorder to work properly.
1914
1915 auto current = mActiveClientManager.get(cameraId);
1916 if (current != nullptr) {
1917 auto clientSp = current->getValue();
1918 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001919 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001920 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001921 " API level, evicting prior client...");
1922 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001923 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001924 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001925 *client = clientSp;
1926 return NO_ERROR;
1927 }
1928 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001929 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001930 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001931
Ruben Brunkcc776712015-02-17 20:18:47 -08001932 // Get state for the given cameraId
1933 auto state = getCameraState(cameraId);
1934 if (state == nullptr) {
1935 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001936 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001937 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001938 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001939 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001940
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001941 sp<IServiceManager> sm = defaultServiceManager();
1942 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001943 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001944 // If processinfo service is not available and the client is automotive privileged
1945 // client used for safety critical uses cases such as rear-view and surround-view which
1946 // needs to be available before android boot completes, then use the hardcoded values
1947 // for the process state and priority score. As this scenario is before android system
1948 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1949 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1950 // visible on the top.
1951 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1952 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1953 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1954 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1955 } else {
1956 // Get current active client PIDs
1957 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1958 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001959
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001960 std::vector<int> priorityScores(ownerPids.size());
1961 std::vector<int> states(ownerPids.size());
1962
1963 // Get priority scores of all active PIDs
1964 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1965 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1966 if (err != OK) {
1967 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1968 return err;
1969 }
1970
1971 // Update all active clients' priorities
1972 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1973 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1974 pidToPriorityMap.emplace(ownerPids[i],
1975 resource_policy::ClientPriority(priorityScores[i], states[i],
1976 /* isVendorClient won't get copied over*/ false,
1977 /* oomScoreOffset won't get copied over*/ 0));
1978 }
1979 mActiveClientManager.updatePriorities(pidToPriorityMap);
1980
1981 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1982 int32_t actualState = states[states.size() - 1];
1983
1984 // Make descriptor for incoming client. We store the oomScoreOffset
1985 // since we might need it later on new handleEvictionsLocked and
1986 // ProcessInfoService would not take that into account.
1987 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1988 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1989 state->getConflicting(), actualScore, clientPid, actualState,
1990 oomScoreOffset, systemNativeClient);
1991 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001992
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001993 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1994
Ruben Brunkcc776712015-02-17 20:18:47 -08001995 // Find clients that would be evicted
1996 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1997
1998 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1999 // background, so we cannot do evictions
2000 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2001 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2002 " priority).", clientPid);
2003
2004 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002005 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002006 auto incompatibleClients =
2007 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2008
Austin Borgered99f642023-06-01 16:51:35 -07002009 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2010 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2011 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002012 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002013
2014 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002015 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002016 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002017 i->getKey().c_str(),
2018 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002019 i->getOwnerId(), i->getPriority().getScore(),
2020 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002021 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002022 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2023 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002024 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002025 }
2026
2027 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002028 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002029 mEventLog.add(msg);
2030
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002031 auto current = mActiveClientManager.get(cameraId);
2032 if (current != nullptr) {
2033 return -EBUSY; // CAMERA_IN_USE
2034 } else {
2035 return -EUSERS; // MAX_CAMERAS_IN_USE
2036 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002037 }
2038
2039 for (auto& i : evicted) {
2040 sp<BasicClient> clientSp = i->getValue();
2041 if (clientSp.get() == nullptr) {
2042 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2043
2044 // TODO: Remove this
2045 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2046 __FUNCTION__);
2047 mActiveClientManager.remove(i);
2048 continue;
2049 }
2050
2051 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002052 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002053 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002054
Ruben Brunkcc776712015-02-17 20:18:47 -08002055 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002056 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002057 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2058 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002059 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002060 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002061 i->getPriority().getState(), cameraId.c_str(),
2062 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002063 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002064
2065 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002066 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002067 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002068 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002069 }
2070
Ruben Brunkcc776712015-02-17 20:18:47 -08002071 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2072 // other clients from connecting in mServiceLockWrapper if held
2073 mServiceLock.unlock();
2074
2075 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002076 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002077
2078 // Destroy evicted clients
2079 for (auto& i : evictedClients) {
2080 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002081 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002082 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002083
Austin Borger22c5c852024-03-08 13:31:36 -08002084 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002085
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002086 for (const auto& i : evictedClients) {
2087 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002088 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002089 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2090 if (ret == TIMED_OUT) {
2091 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002092 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2093 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002094 return -EBUSY;
2095 }
2096 if (ret != NO_ERROR) {
2097 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002098 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2099 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002100 return ret;
2101 }
2102 }
2103
2104 evictedClients.clear();
2105
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 // Once clients have been disconnected, relock
2107 mServiceLock.lock();
2108
2109 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2110 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2111 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002112 }
2113
Ruben Brunkcc776712015-02-17 20:18:47 -08002114 *partial = clientDescriptor;
2115 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002116}
2117
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002118Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002119 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002120 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002121 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002122 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002123 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002124 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002125 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002126 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002127 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002128 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002129 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002130
Austin Borger65e64642024-06-11 15:58:23 -07002131 std::string cameraIdStr =
2132 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002133 if (cameraIdStr.empty()) {
2134 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002135 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002136 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2137 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2138 }
malikakashedb38962023-09-06 00:03:35 +00002139
Austin Borger7d2b9232024-07-22 14:17:14 -07002140 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2141 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002142
Austin Borger95a00152024-09-23 17:20:24 -07002143 AttributionSourceState resolvedClientAttribution(clientAttribution);
2144 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraIdStr);
2145 if (!ret.isOk()) {
2146 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002147 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002148 toStdString(ret.toString8()));
2149 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002150 }
2151
Austin Borger95a00152024-09-23 17:20:24 -07002152 const int clientPid = resolvedClientAttribution.pid;
2153 const int clientUid = resolvedClientAttribution.uid;
2154 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2155
2156 logConnectionAttempt(clientPid, clientPackageName, cameraIdStr, API_1);
Austin Borgerb01a8702024-07-22 16:20:34 -07002157
Ruben Brunkcc776712015-02-17 20:18:47 -08002158 sp<Client> client = nullptr;
Austin Borger23694432024-10-07 19:28:01 -07002159 ret = connectHelper<ICameraClient, Client>(
2160 cameraClient, cameraIdStr, api1CameraId, resolvedClientAttribution,
2161 /*systemNativeClient*/ false, API_1,
2162 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, rotationOverride,
2163 forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/ client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002164
Biswarup Pal37a75182024-01-16 15:53:35 +00002165 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002166 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002167 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002168 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002169 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002170 }
2171
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002172 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002173
2174 const sp<IServiceManager> sm(defaultServiceManager());
2175 const auto& mActivityManager = getActivityManager();
2176 if (mActivityManager) {
2177 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002178 getCallingUid(),
2179 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002180 }
2181
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002182 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002183}
2184
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002185bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2186 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002187 // If the client is not a vendor client, don't add listener if
2188 // a) the camera is a publicly hidden secure camera OR
2189 // b) the camera is a system only camera and the client doesn't
2190 // have android.permission.SYSTEM_CAMERA permissions.
2191 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2192 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002193 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002194 return true;
2195 }
2196 return false;
2197}
2198
Austin Borgered99f642023-06-01 16:51:35 -07002199bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002200 // Rules for rejection:
2201 // 1) If cameraserver tries to access this camera device, accept the
2202 // connection.
2203 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002204 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002205 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2206 // and the serving thread is a non hwbinder thread, the client must have
2207 // android.permission.SYSTEM_CAMERA permissions to connect.
2208
Austin Borger22c5c852024-03-08 13:31:36 -08002209 int cPid = getCallingPid();
2210 int cUid = getCallingUid();
2211 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002212 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2213 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002214 // This isn't a known camera ID, so it's not a system camera
2215 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2216 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002217 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002218
2219 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002220 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002221 return false;
2222 }
2223 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002224 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002225 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2226 return true;
2227 }
2228 // (3) Here we only check for permissions if it is a system only camera device. This is since
2229 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2230 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2231 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002232 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002233 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002234 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2235 cameraId.c_str());
2236 return true;
2237 }
2238
2239 return false;
2240}
2241
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002242Status CameraService::connectDevice(
2243 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002244 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002245 int oomScoreOffset, int targetSdkVersion,
2246 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002247 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002248 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002249 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002250 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002251 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002252 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002253 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002254 int callingPid = getCallingPid();
2255 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002256 bool systemNativeClient = false;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002257 AttributionSourceState resolvedClientAttribution(clientAttribution);
Austin Borger7d2b9232024-07-22 14:17:14 -07002258 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002259 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002260 clientPackageNameMaybe = systemClient;
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002261 // Pass in packageName since AttributionAndPermissionUtils can't resolve vndk clients.
2262 resolvedClientAttribution.packageName = clientPackageNameMaybe;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002263 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002264 }
Austin Borger249e6592024-03-10 22:28:11 -07002265
Austin Borger65e64642024-06-11 15:58:23 -07002266 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2267 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002268 if (!cameraIdOptional.has_value()) {
2269 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002270 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002271 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2272 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2273 }
2274 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002275
Austin Borger7d2b9232024-07-22 14:17:14 -07002276 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002277
Austin Borger2a3f9a72024-11-07 12:24:49 -08002278 if (!flags::data_delivery_permission_checks()) {
Austin Borger95a00152024-09-23 17:20:24 -07002279 resolvedClientAttribution.pid = USE_CALLING_PID;
2280 }
Jayant Chowdhary0267d472024-11-01 20:42:15 +00002281
Austin Borger95a00152024-09-23 17:20:24 -07002282 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraId);
2283 if (!ret.isOk()) {
2284 logRejected(cameraId, getCallingPid(), clientAttribution.packageName.value_or(""),
2285 toStdString(ret.toString8()));
2286 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002287 }
2288
Austin Borger95a00152024-09-23 17:20:24 -07002289 const int clientPid = resolvedClientAttribution.pid;
2290 const int clientUid = resolvedClientAttribution.uid;
2291 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2292 userid_t clientUserId = multiuser_get_user_id(resolvedClientAttribution.uid);
Austin Borgerb01a8702024-07-22 16:20:34 -07002293
Austin Borger95a00152024-09-23 17:20:24 -07002294 logConnectionAttempt(clientPid, clientPackageName, cameraId, API_2);
Austin Borgerb01a8702024-07-22 16:20:34 -07002295
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002296 if (oomScoreOffset < 0) {
Austin Borger95a00152024-09-23 17:20:24 -07002297 std::string msg = fmt::sprintf(
2298 "Cannot increase the priority of a client %s pid %d for "
2299 "camera id %s",
2300 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002301 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2302 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002303 }
2304
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002305 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2306 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002307 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2308 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002309 std::string msg = "Camera disabled by device policy";
2310 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2311 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002312 }
2313
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002314 // enforce system camera permissions
Austin Borger95a00152024-09-23 17:20:24 -07002315 if (oomScoreOffset > 0 && !hasPermissionsForSystemCamera(cameraId, clientPid, callingUid) &&
2316 !isTrustedCallingUid(callingUid)) {
2317 std::string msg = fmt::sprintf(
2318 "Cannot change the priority of a client %s pid %d for "
2319 "camera id %s without SYSTEM_CAMERA permissions",
2320 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002321 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2322 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002323 }
2324
Austin Borger95a00152024-09-23 17:20:24 -07002325 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks, CameraDeviceClient>(
Austin Borger23694432024-10-07 19:28:01 -07002326 cameraCb, cameraId, /*api1CameraId*/ -1, resolvedClientAttribution, systemNativeClient,
2327 API_2, /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger95a00152024-09-23 17:20:24 -07002328 /*forceSlowJpegMode*/ false, unresolvedCameraId, isNonSystemNdk, /*out*/ client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002329
Biswarup Pal37a75182024-01-16 15:53:35 +00002330 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002331 logRejected(cameraId, clientPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002332 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002333 }
2334
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002335 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002336 Mutex::Autolock lock(mServiceLock);
2337
2338 // Clear the previous cached logs and reposition the
2339 // file offset to beginning of the file to log new data.
2340 // If either truncate or lseek fails, close the previous file and create a new one.
2341 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2342 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2343 // Close the previous memfd.
2344 close(mMemFd);
2345 // If failure to wipe the data, then create a new file and
2346 // assign the new value to mMemFd.
2347 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2348 if (mMemFd == -1) {
2349 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2350 }
2351 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002352 const sp<IServiceManager> sm(defaultServiceManager());
2353 const auto& mActivityManager = getActivityManager();
2354 if (mActivityManager) {
2355 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002356 callingUid,
2357 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002358 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002359 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002360}
2361
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002362bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2363 int callingPid, int callingUid) {
2364 if (!isAutomotiveDevice()) {
2365 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2366 }
2367
2368 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2369 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2370 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2371 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2372 "using camera %s", callingUid, cam_id.c_str());
2373 return false;
2374 }
2375
2376 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2377 return true;
2378 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2379 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002380 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2381 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002382 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2383 return false;
2384 } else {
2385 return true;
2386 }
2387 }
2388 return false;
2389}
2390
Austin Borger7d2b9232024-07-22 14:17:14 -07002391void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
Austin Borger95a00152024-09-23 17:20:24 -07002392 const std::string& cameraId,
2393 apiLevel effectiveApiLevel) const {
Austin Borger7d2b9232024-07-22 14:17:14 -07002394 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borger95a00152024-09-23 17:20:24 -07002395 "Camera API version %d",
2396 clientPid, clientPackageName.c_str(), cameraId.c_str(),
2397 static_cast<int>(effectiveApiLevel));
Austin Borger7d2b9232024-07-22 14:17:14 -07002398}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002399
Austin Borger23694432024-10-07 19:28:01 -07002400template <class CALLBACK, class CLIENT>
Austin Borger7d2b9232024-07-22 14:17:14 -07002401Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
Austin Borger23694432024-10-07 19:28:01 -07002402 int api1CameraId,
2403 const AttributionSourceState& clientAttribution,
2404 bool systemNativeClient, apiLevel effectiveApiLevel,
2405 bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2406 int rotationOverride, bool forceSlowJpegMode,
2407 const std::string& originalCameraId, bool isNonSystemNdk,
2408 /*out*/ sp<CLIENT>& device) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002409 binder::Status ret = binder::Status::ok();
2410
Shuzhen Wang316781a2020-08-18 18:11:01 -07002411 nsecs_t openTimeNs = systemTime();
2412
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002413 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002414 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002415 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002416
Austin Borger23694432024-10-07 19:28:01 -07002417 const std::string clientPackageName =
2418 clientAttribution.packageName.value_or(kUnknownPackageName);
2419
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002420 {
2421 // Acquire mServiceLock and prevent other clients from connecting
2422 std::unique_ptr<AutoConditionLock> lock =
2423 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2424
2425 if (lock == nullptr) {
Austin Borger23694432024-10-07 19:28:01 -07002426 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting).",
2427 clientAttribution.pid);
2428 return STATUS_ERROR_FMT(
2429 ERROR_MAX_CAMERAS_IN_USE,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002430 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borger23694432024-10-07 19:28:01 -07002431 cameraId.c_str(), clientPackageName.c_str(), clientAttribution.pid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002432 }
2433
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002434 // Enforce client permissions and do basic validity checks
Austin Borger23694432024-10-07 19:28:01 -07002435 if (!(ret = validateConnectLocked(cameraId, clientAttribution)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002436 return ret;
2437 }
2438
2439 // Check the shim parameters after acquiring lock, if they have already been updated and
2440 // we were doing a shim update, return immediately
2441 if (shimUpdateOnly) {
2442 auto cameraState = getCameraState(cameraId);
2443 if (cameraState != nullptr) {
2444 if (!cameraState->getShimParams().isEmpty()) return ret;
2445 }
2446 }
2447
2448 status_t err;
2449
2450 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002451 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger23694432024-10-07 19:28:01 -07002452 if ((err = handleEvictionsLocked(
2453 cameraId, clientAttribution.pid, effectiveApiLevel,
2454 IInterface::asBinder(cameraCb),
2455 clientAttribution.packageName.value_or(kUnknownPackageName), oomScoreOffset,
2456 systemNativeClient, /*out*/ &clientTmp,
2457 /*out*/ &partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002458 switch (err) {
2459 case -ENODEV:
2460 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2461 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002462 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002463 case -EBUSY:
2464 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2465 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002466 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002467 case -EUSERS:
2468 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2469 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002470 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002471 default:
2472 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2473 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002474 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002475 }
2476 }
2477
2478 if (clientTmp.get() != nullptr) {
2479 // Handle special case for API1 MediaRecorder where the existing client is returned
2480 device = static_cast<CLIENT*>(clientTmp.get());
2481 return ret;
2482 }
2483
2484 // give flashlight a chance to close devices if necessary.
2485 mFlashlight->prepareDeviceOpen(cameraId);
2486
Austin Borger18b30a72022-10-27 12:20:29 -07002487 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002488 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002489 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002490 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002491 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002492 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002493 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002494 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002495 }
2496
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002497 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002498 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002499 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002500
Austin Borger6e831c42024-07-22 13:07:56 -07002501 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2502 // that's connected to camera service directly.
Austin Borger2e772b82024-10-11 16:09:57 -07002503 if (!(ret = makeClient(this, cameraCb, clientAttribution, getCallingPid(),
2504 systemNativeClient, cameraId, api1CameraId, facing, orientation,
2505 getpid(), deviceVersionAndTransport, effectiveApiLevel,
2506 overrideForPerfClass, rotationOverride, forceSlowJpegMode,
2507 originalCameraId,
Austin Borger23694432024-10-07 19:28:01 -07002508 /*out*/ &tmp))
2509 .isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002510 return ret;
2511 }
2512 client = static_cast<CLIENT*>(tmp.get());
2513
2514 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2515 __FUNCTION__);
2516
Austin Borgered99f642023-06-01 16:51:35 -07002517 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002518 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002519 if (err != OK) {
2520 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002521 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002522 mServiceLock.unlock();
2523 client->disconnect();
2524 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002525 switch(err) {
2526 case BAD_VALUE:
2527 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002528 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002529 case -EBUSY:
2530 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002531 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002532 case -EUSERS:
2533 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2534 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002535 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002536 case PERMISSION_DENIED:
2537 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002538 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002539 case -EACCES:
2540 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002541 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002542 case -ENODEV:
2543 default:
2544 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002545 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002546 strerror(-err), err);
2547 }
2548 }
2549
2550 // Update shim paremeters for legacy clients
2551 if (effectiveApiLevel == API_1) {
2552 // Assume we have always received a Client subclass for API1
2553 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2554 String8 rawParams = shimClient->getParameters();
2555 CameraParameters params(rawParams);
2556
2557 auto cameraState = getCameraState(cameraId);
2558 if (cameraState != nullptr) {
2559 cameraState->setShimParams(params);
2560 } else {
2561 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002562 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002563 }
2564 }
2565
Ravneetaeb20dc2022-03-30 05:33:03 +00002566 // Enable/disable camera service watchdog
2567 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2568
Emilian Peev6d45db82024-01-18 20:11:54 +00002569 CameraMetadata chars;
2570 bool rotateAndCropSupported = true;
2571 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002572 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002573 if (err == OK) {
2574 auto availableRotateCropEntry = chars.find(
2575 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2576 if (availableRotateCropEntry.count <= 1) {
2577 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002578 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002579 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002580 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2581 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002582 }
2583
Emilian Peev6d45db82024-01-18 20:11:54 +00002584 if (rotateAndCropSupported) {
2585 // Set rotate-and-crop override behavior
2586 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2587 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002588 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2589 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002590 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2591 switch (portraitRotation) {
2592 case 90:
2593 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2594 break;
2595 case 180:
2596 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2597 break;
2598 case 270:
2599 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2600 break;
2601 default:
2602 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2603 break;
2604 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002605 // Here we're communicating to the client the chosen rotate
2606 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002607 client->setRotateAndCropOverride(rotateAndCropMode);
2608 } else {
2609 client->setRotateAndCropOverride(
Austin Borger23694432024-10-07 19:28:01 -07002610 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2611 clientPackageName, facing,
2612 multiuser_get_user_id(clientAttribution.uid)));
Emilian Peev6d45db82024-01-18 20:11:54 +00002613 }
2614 }
2615
2616 bool autoframingSupported = true;
2617 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2618 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2619 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2620 autoframingSupported = false;
2621 }
2622
2623 if (autoframingSupported) {
2624 // Set autoframing override behaviour
2625 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2626 client->setAutoframingOverride(mOverrideAutoframingMode);
2627 } else {
2628 client->setAutoframingOverride(
2629 mCameraServiceProxyWrapper->getAutoframingOverride(
2630 clientPackageName));
2631 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002632 }
2633
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002634 bool isCameraPrivacyEnabled;
2635 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002636 // Set camera muting behavior.
Austin Borger23694432024-10-07 19:28:01 -07002637 isCameraPrivacyEnabled =
2638 this->isCameraPrivacyEnabled(toString16(client->getPackageName()), cameraId,
2639 clientAttribution.pid, clientAttribution.uid);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002640 } else {
2641 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002642 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002643 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002644
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002645 if (client->supportsCameraMute()) {
2646 client->setCameraMute(
2647 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2648 } else if (isCameraPrivacyEnabled) {
2649 // no camera mute supported, but privacy is on! => disconnect
2650 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2651 client->getPackageName().c_str(), cameraId.c_str());
2652 // Do not hold mServiceLock while disconnecting clients, but
2653 // retain the condition blocking other clients from connecting
2654 // in mServiceLockWrapper if held.
2655 mServiceLock.unlock();
2656 // Clear caller identity temporarily so client disconnect PID
2657 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002658 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002659 // Note AppOp to trigger the "Unblock" dialog
2660 client->noteAppOp();
2661 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002662 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002663 // Reacquire mServiceLock
2664 mServiceLock.lock();
2665
2666 return STATUS_ERROR_FMT(ERROR_DISABLED,
2667 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002668 }
2669
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002670 if (shimUpdateOnly) {
2671 // If only updating legacy shim parameters, immediately disconnect client
2672 mServiceLock.unlock();
2673 client->disconnect();
2674 mServiceLock.lock();
2675 } else {
2676 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002677 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002678 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002679
2680 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002681 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002682 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002683 } // lock is destroyed, allow further connect calls
2684
2685 // Important: release the mutex here so the client can call back into the service from its
2686 // destructor (can be at the end of the call)
2687 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002688
2689 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002690 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002691 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002692
Cliff Wud3a05312021-04-26 23:07:31 +08002693 {
2694 Mutex::Autolock lock(mInjectionParametersLock);
2695 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2696 mInjectionInitPending = false;
2697 status_t res = NO_ERROR;
2698 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2699 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002700 sp<BasicClient> clientSp = clientDescriptor->getValue();
2701 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2702 if(res != OK) {
2703 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2704 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002705 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002706 }
2707 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002708 if (res != OK) {
2709 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2710 }
2711 } else {
2712 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002713 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002714 res = NO_INIT;
2715 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2716 }
2717 }
2718 }
2719
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002720 return ret;
2721}
2722
Austin Borgered99f642023-06-01 16:51:35 -07002723status_t CameraService::addOfflineClient(const std::string &cameraId,
2724 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002725 if (offlineClient.get() == nullptr) {
2726 return BAD_VALUE;
2727 }
2728
2729 {
2730 // Acquire mServiceLock and prevent other clients from connecting
2731 std::unique_ptr<AutoConditionLock> lock =
2732 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2733
2734 if (lock == nullptr) {
2735 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
Austin Borger2e772b82024-10-11 16:09:57 -07002736 , __FUNCTION__, offlineClient->getClientCallingPid());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002737 return TIMED_OUT;
2738 }
2739
2740 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2741 if (onlineClientDesc.get() == nullptr) {
2742 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2743 cameraId.c_str());
2744 return BAD_VALUE;
2745 }
2746
2747 // Offline clients do not evict or conflict with other online devices. Resource sharing
2748 // conflicts are handled by the camera provider which will either succeed or fail before
2749 // reaching this method.
2750 const auto& onlinePriority = onlineClientDesc->getPriority();
2751 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2752 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002753 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002754 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002755 // native clients don't have offline processing support.
2756 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002757 if (offlineClientDesc == nullptr) {
2758 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2759 return BAD_VALUE;
2760 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002761
2762 // Allow only one offline device per camera
2763 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2764 if (!incompatibleClients.empty()) {
2765 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2766 return BAD_VALUE;
2767 }
2768
Austin Borgered99f642023-06-01 16:51:35 -07002769 std::string monitorTags = isClientWatched(offlineClient.get())
2770 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002771 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002772 if (err != OK) {
2773 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2774 return err;
2775 }
2776
2777 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2778 if (evicted.size() > 0) {
2779 for (auto& i : evicted) {
2780 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002781 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002782 }
2783
2784 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2785 "properly", __FUNCTION__);
2786
2787 return BAD_VALUE;
2788 }
2789
2790 logConnectedOffline(offlineClientDesc->getKey(),
2791 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002792 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002793
2794 sp<IBinder> remoteCallback = offlineClient->getRemote();
2795 if (remoteCallback != nullptr) {
2796 remoteCallback->linkToDeath(this);
2797 }
2798 } // lock is destroyed, allow further connect calls
2799
2800 return OK;
2801}
2802
Austin Borgered99f642023-06-01 16:51:35 -07002803Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002804 int32_t torchStrength, const sp<IBinder>& clientBinder,
2805 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002806 Mutex::Autolock lock(mServiceLock);
2807
2808 ATRACE_CALL();
2809 if (clientBinder == nullptr) {
2810 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2811 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2812 "Torch client binder in null.");
2813 }
2814
Austin Borger22c5c852024-03-08 13:31:36 -08002815 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002816 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2817 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002818 if (!cameraIdOptional.has_value()) {
2819 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002820 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002821 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2822 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2823 }
2824 std::string cameraId = cameraIdOptional.value();
2825
Austin Borgered99f642023-06-01 16:51:35 -07002826 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002827 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002828 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002829 }
2830
2831 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002832 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002833 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002834 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002835 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002836 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002837 }
2838
2839 StatusInternal cameraStatus = state->getStatus();
2840 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2841 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002842 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002843 (int)cameraStatus);
2844 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002845 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002846 }
2847
2848 {
2849 Mutex::Autolock al(mTorchStatusMutex);
2850 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002851 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002852 if (err != OK) {
2853 if (err == NAME_NOT_FOUND) {
2854 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002855 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002856 }
2857 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002858 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002859 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2860 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002861 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002862 }
2863
2864 if (status == TorchModeStatus::NOT_AVAILABLE) {
2865 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2866 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002867 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002868 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2869 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002870 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002871 } else {
2872 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002873 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002874 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2875 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002876 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 }
2878 }
2879 }
2880
2881 {
2882 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002883 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002884 }
2885 // Check if the current torch strength level is same as the new one.
2886 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002887 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002888
Austin Borgered99f642023-06-01 16:51:35 -07002889 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002890
2891 if (err != OK) {
2892 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002893 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002894 switch (err) {
2895 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002896 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2897 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002898 errorCode = ERROR_ILLEGAL_ARGUMENT;
2899 break;
2900 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002901 msg = fmt::sprintf("Camera \"%s\" is in use",
2902 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002903 errorCode = ERROR_CAMERA_IN_USE;
2904 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002905 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002906 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002907 "valid range.", torchStrength);
2908 errorCode = ERROR_ILLEGAL_ARGUMENT;
2909 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002910 default:
Austin Borgered99f642023-06-01 16:51:35 -07002911 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002912 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002913 }
Austin Borgered99f642023-06-01 16:51:35 -07002914 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2915 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002916 }
2917
2918 {
2919 // update the link to client's death
2920 // Store the last client that turns on each camera's torch mode.
2921 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002922 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002923 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002924 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002925 } else {
2926 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2927 mTorchClientMap.replaceValueAt(index, clientBinder);
2928 }
2929 clientBinder->linkToDeath(this);
2930 }
2931
Austin Borger22c5c852024-03-08 13:31:36 -08002932 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002933 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002934 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002935 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002936 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002937 }
2938 return Status::ok();
2939}
2940
malikakash73125c62023-07-21 22:44:34 +00002941Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002942 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2943 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002944 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002945
2946 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002947 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002948 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002949 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2950 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002951 }
2952
Austin Borger22c5c852024-03-08 13:31:36 -08002953 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002954 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2955 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002956 if (!cameraIdOptional.has_value()) {
2957 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002958 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002959 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2960 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2961 }
2962 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002963
Austin Borgered99f642023-06-01 16:51:35 -07002964 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002965 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002966 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002967 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002968 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002969 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002970 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002971 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002973 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002974 }
2975
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002976 StatusInternal cameraStatus = state->getStatus();
2977 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002978 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002979 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2980 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002981 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002982 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002983 }
2984
2985 {
2986 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002987 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002988 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002989 if (err != OK) {
2990 if (err == NAME_NOT_FOUND) {
2991 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002992 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002993 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002994 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002995 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002996 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002997 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002998 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002999 }
3000
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003001 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003002 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003003 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003004 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003005 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3006 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003007 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003008 } else {
3009 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003010 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003011 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3012 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003013 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003014 }
3015 }
3016 }
3017
Ruben Brunk99e69712015-05-26 17:25:07 -07003018 {
3019 // Update UID map - this is used in the torch status changed callbacks, so must be done
3020 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003021 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003022 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003023 }
3024
Austin Borgered99f642023-06-01 16:51:35 -07003025 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003026
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003027 if (err != OK) {
3028 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003029 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003030 switch (err) {
3031 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003032 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3033 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 errorCode = ERROR_ILLEGAL_ARGUMENT;
3035 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003036 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003037 msg = fmt::sprintf("Camera \"%s\" is in use",
3038 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003039 errorCode = ERROR_CAMERA_IN_USE;
3040 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003041 default:
Austin Borgered99f642023-06-01 16:51:35 -07003042 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003043 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003044 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003045 errorCode = ERROR_INVALID_OPERATION;
3046 }
Austin Borgered99f642023-06-01 16:51:35 -07003047 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3048 logServiceError(msg, errorCode);
3049 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003050 }
3051
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003052 {
3053 // update the link to client's death
3054 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003055 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003056 if (enabled) {
3057 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003058 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003059 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003060 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003061 mTorchClientMap.replaceValueAt(index, clientBinder);
3062 }
3063 clientBinder->linkToDeath(this);
3064 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003065 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003066 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003067 }
3068
Austin Borger22c5c852024-03-08 13:31:36 -08003069 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003070 std::string torchState = enabled ? "on" : "off";
3071 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3072 torchState.c_str(), clientPid);
3073 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003074 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003075}
3076
Austin Borgered99f642023-06-01 16:51:35 -07003077void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3078 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3079 mTorchUidMap[cameraId].first = uid;
3080 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003081 } else {
3082 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003083 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003084 }
3085}
3086
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003087Status CameraService::notifySystemEvent(int32_t eventId,
3088 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003089 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003090 const int selfPid = getpid();
3091
3092 // Permission checks
3093 if (pid != selfPid) {
3094 // Ensure we're being called by system_server, or similar process with
3095 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003096 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003097 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003098 ALOGE("Permission Denial: cannot send updates to camera service about system"
3099 " events from pid=%d, uid=%d", pid, uid);
3100 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003101 "No permission to send updates to camera service about system events"
3102 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003103 }
3104 }
3105
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003106 ATRACE_CALL();
3107
Ruben Brunk36597b22015-03-20 22:15:57 -07003108 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003109 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003110 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003111 // from a system server crash
3112 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003113 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003114 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003115 break;
3116 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003117 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3118 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003119 if (args.size() != 1) {
3120 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3121 "USB Device Event requires 1 argument");
3122 }
3123
Valentin Iftime29e2e152021-08-13 15:17:33 +02003124 // Notify CameraProviderManager for lazy HALs
3125 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3126 std::to_string(args[0]));
3127 break;
3128 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003129 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003130 default: {
3131 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3132 eventId);
3133 break;
3134 }
3135 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003136 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003137}
3138
Emilian Peev53722fa2019-02-22 17:47:20 -08003139void CameraService::notifyMonitoredUids() {
3140 Mutex::Autolock lock(mStatusListenerLock);
3141
3142 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003143 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003144 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3145 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003146 }
3147}
3148
Austin Borgerdddb7552023-03-30 17:53:01 -07003149void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3150 Mutex::Autolock lock(mStatusListenerLock);
3151
3152 for (const auto& it : mListenerList) {
3153 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3154 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3155 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3156 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3157 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3158 }
3159 }
3160}
3161
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003162Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003163 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003164 const int selfPid = getpid();
3165
3166 // Permission checks
3167 if (pid != selfPid) {
3168 // Ensure we're being called by system_server, or similar process with
3169 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003170 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003171 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003172 ALOGE("Permission Denial: cannot send updates to camera service about device"
3173 " state changes from pid=%d, uid=%d", pid, uid);
3174 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3175 "No permission to send updates to camera service about device state"
3176 " changes from pid=%d, uid=%d", pid, uid);
3177 }
3178 }
3179
3180 ATRACE_CALL();
3181
Austin Borger18b30a72022-10-27 12:20:29 -07003182 {
3183 Mutex::Autolock lock(mServiceLock);
3184 mDeviceState = newState;
3185 }
3186
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003187 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003188
3189 return Status::ok();
3190}
3191
Emilian Peev8b64f282021-03-25 16:49:57 -07003192Status CameraService::notifyDisplayConfigurationChange() {
3193 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003194 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003195 const int selfPid = getpid();
3196
3197 // Permission checks
3198 if (callingPid != selfPid) {
3199 // Ensure we're being called by system_server, or similar process with
3200 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003201 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003202 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003203 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3204 " changes from pid=%d, uid=%d", callingPid, uid);
3205 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3206 "No permission to send updates to camera service about orientation"
3207 " changes from pid=%d, uid=%d", callingPid, uid);
3208 }
3209 }
3210
3211 Mutex::Autolock lock(mServiceLock);
3212
3213 // Don't do anything if rotate-and-crop override via cmd is active
3214 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3215
3216 const auto clients = mActiveClientManager.getAll();
3217 for (auto& current : clients) {
3218 if (current != nullptr) {
3219 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003220 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3221 basicClient->setRotateAndCropOverride(
3222 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3223 basicClient->getPackageName(),
3224 basicClient->getCameraFacing(),
3225 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003226 }
3227 }
3228 }
3229
3230 return Status::ok();
3231}
3232
3233Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003234 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3235 ATRACE_CALL();
3236 if (!concurrentCameraIds) {
3237 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3238 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3239 }
3240
3241 if (!mInitialized) {
3242 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003243 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003244 return STATUS_ERROR(ERROR_DISCONNECTED,
3245 "Camera subsystem is not available");
3246 }
3247 // First call into the provider and get the set of concurrent camera
3248 // combinations
3249 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003250 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003251 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003252 std::vector<std::pair<std::string, int32_t>> validCombination;
3253 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003254 for (auto &cameraId : combination) {
3255 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003256 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003257 if (state == nullptr) {
3258 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3259 continue;
3260 }
3261 StatusInternal status = state->getStatus();
3262 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3263 continue;
3264 }
Austin Borgered99f642023-06-01 16:51:35 -07003265 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003266 continue;
3267 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003268 auto [cameraOwnerDeviceId, mappedCameraId] =
3269 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3270 if (firstDeviceId == kInvalidDeviceId) {
3271 firstDeviceId = cameraOwnerDeviceId;
3272 } else if (firstDeviceId != cameraOwnerDeviceId) {
3273 // Found an invalid combination which contains cameras with different device id's,
3274 // hence discard it.
3275 validCombination.clear();
3276 break;
3277 }
3278 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003279 }
3280 if (validCombination.size() != 0) {
3281 concurrentCameraIds->push_back(std::move(validCombination));
3282 }
3283 }
3284 return Status::ok();
3285}
3286
3287Status CameraService::isConcurrentSessionConfigurationSupported(
3288 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003289 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003290 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003291 if (!isSupported) {
3292 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3293 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3294 }
3295
3296 if (!mInitialized) {
3297 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3298 return STATUS_ERROR(ERROR_DISCONNECTED,
3299 "Camera subsystem is not available");
3300 }
3301
Biswarup Pal7d072862024-04-17 15:24:47 +00003302 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3303 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003304 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3305 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003306 if (!cameraIdOptional.has_value()) {
3307 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003308 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003309 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3310 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3311 }
3312 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3313 }
3314
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003315 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003316 int callingPid = getCallingPid();
3317 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003318 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003319 hasPermissionsForCamera(callingPid, callingUid,
3320 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003321 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003322 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003323 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3324 "android.permission.CAMERA needed to call"
3325 "isConcurrentSessionConfigurationSupported");
3326 }
3327
3328 status_t res =
3329 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003330 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3331 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003332 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003333 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003334 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003335 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3336 "support %s (%d)", strerror(-res), res);
3337 }
3338 return Status::ok();
3339}
3340
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003341Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3342 /*out*/
3343 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003344 return addListenerHelper(listener, cameraStatuses);
3345}
3346
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003347binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3348 std::vector<hardware::CameraStatus>* cameraStatuses) {
3349 return addListenerHelper(listener, cameraStatuses, false, true);
3350}
3351
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003352Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3353 /*out*/
3354 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003355 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003356 ATRACE_CALL();
3357
Igor Murashkinbfc99152013-02-27 12:55:20 -08003358 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003359
Ruben Brunk3450ba72015-06-16 11:00:37 -07003360 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003361 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003362 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003363 }
3364
Austin Borger22c5c852024-03-08 13:31:36 -08003365 auto clientPid = getCallingPid();
3366 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003367 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003368
Igor Murashkinbfc99152013-02-27 12:55:20 -08003369 Mutex::Autolock lock(mServiceLock);
3370
Ruben Brunkcc776712015-02-17 20:18:47 -08003371 {
3372 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003373 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003374 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003375 ALOGW("%s: Tried to add listener %p which was already subscribed",
3376 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003377 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003378 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003379 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003380
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003381 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003382 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3383 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003384 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003385 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003386 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003387 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003388 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3389 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3390 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003391 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003392 // The listener still needs to be added to the list of listeners, regardless of what
3393 // permissions the listener process has / whether it is a vendor listener. Since it might be
3394 // eligible to listen to other camera ids.
3395 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003396 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003397 }
3398
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003399 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003400 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003401 Mutex::Autolock lock(mCameraStatesLock);
3402 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003403 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3404 auto [deviceId, mappedCameraId] =
3405 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3406
3407 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003408 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003409 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3410 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003411 }
3412 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003413 // Remove the camera statuses that should be hidden from the client, we do
3414 // this after collecting the states in order to avoid holding
3415 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3416 // the same time.
3417 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3418 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003419 std::string cameraId = s.cameraId;
3420 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003421 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003422 if (!cameraIdOptional.has_value()) {
3423 std::string msg =
3424 fmt::sprintf(
3425 "Camera %s: Invalid camera id for device id %d",
3426 s.cameraId.c_str(), s.deviceId);
3427 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3428 return true;
3429 }
3430 cameraId = cameraIdOptional.value();
3431 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3432 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3433 ALOGE("%s: Invalid camera id %s, skipping status update",
3434 __FUNCTION__, s.cameraId.c_str());
3435 return true;
3436 }
3437 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3438 clientUid);
3439 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003440
Biswarup Pal37a75182024-01-16 15:53:35 +00003441 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003442 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003443 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003444 // Add only default device cameras here, as virtual cameras currently don't support torch
3445 // anyway. Note that this is a simplification of the implementation here, and we should
3446 // change this when virtual cameras support torch.
3447 if (s.deviceId == kDefaultDeviceId) {
3448 idsChosenForCallback.insert(s.cameraId);
3449 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003450 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003451
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003452 /*
3453 * Immediately signal current torch status to this listener only
3454 * This may be a subset of all the devices, so don't include it in the response directly
3455 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003456 {
3457 Mutex::Autolock al(mTorchStatusMutex);
3458 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003459 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003460 // The camera id is visible to the client. Fine to send torch
3461 // callback.
3462 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003463 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3464 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003465 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003466 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003467 }
3468
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003469 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003470}
Ruben Brunkcc776712015-02-17 20:18:47 -08003471
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003472Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003473 ATRACE_CALL();
3474
Igor Murashkinbfc99152013-02-27 12:55:20 -08003475 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3476
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003477 if (listener == 0) {
3478 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003479 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003480 }
3481
Igor Murashkinbfc99152013-02-27 12:55:20 -08003482 Mutex::Autolock lock(mServiceLock);
3483
Ruben Brunkcc776712015-02-17 20:18:47 -08003484 {
3485 Mutex::Autolock lock(mStatusListenerLock);
3486 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003487 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003488 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003489 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003490 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003491 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003492 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003493 }
3494 }
3495
3496 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3497 __FUNCTION__, listener.get());
3498
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003499 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003500}
3501
Austin Borgered99f642023-06-01 16:51:35 -07003502Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003503
3504 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003505 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3506
3507 if (parameters == NULL) {
3508 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003509 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003510 }
3511
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003512 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003513
3514 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003515 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003516 // Error logged by caller
3517 return ret;
3518 }
3519
3520 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003521
Austin Borgered99f642023-06-01 16:51:35 -07003522 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003523
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003524 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003525}
3526
malikakash98260df2024-05-10 23:33:57 +00003527Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003528 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003529 ATRACE_CALL();
3530
Austin Borgered99f642023-06-01 16:51:35 -07003531 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003532
3533 switch (apiVersion) {
3534 case API_VERSION_1:
3535 case API_VERSION_2:
3536 break;
3537 default:
Austin Borgered99f642023-06-01 16:51:35 -07003538 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3539 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3540 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003541 }
3542
Austin Borger18b30a72022-10-27 12:20:29 -07003543 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003544 auto deviceVersionAndTransport =
3545 getDeviceVersion(cameraId,
3546 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3547 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003548 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003549 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3550 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3551 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003552 }
3553 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3554 int deviceVersion = deviceVersionAndTransport.first;
3555 switch (deviceVersion) {
3556 case CAMERA_DEVICE_API_VERSION_1_0:
3557 case CAMERA_DEVICE_API_VERSION_3_0:
3558 case CAMERA_DEVICE_API_VERSION_3_1:
3559 if (apiVersion == API_VERSION_2) {
3560 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003561 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003562 *isSupported = false;
3563 } else { // if (apiVersion == API_VERSION_1) {
3564 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003565 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003566 *isSupported = true;
3567 }
3568 break;
3569 case CAMERA_DEVICE_API_VERSION_3_2:
3570 case CAMERA_DEVICE_API_VERSION_3_3:
3571 case CAMERA_DEVICE_API_VERSION_3_4:
3572 case CAMERA_DEVICE_API_VERSION_3_5:
3573 case CAMERA_DEVICE_API_VERSION_3_6:
3574 case CAMERA_DEVICE_API_VERSION_3_7:
3575 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003576 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003577 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003578 break;
3579 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003580 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3581 deviceVersion, cameraId.c_str());
3582 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3583 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003584 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003585 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003586 } else {
3587 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003588 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003589 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003590}
3591
malikakash98260df2024-05-10 23:33:57 +00003592Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003593 /*out*/ bool *isSupported) {
3594 ATRACE_CALL();
3595
Austin Borgered99f642023-06-01 16:51:35 -07003596 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3597 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003598
3599 return Status::ok();
3600}
3601
Cliff Wud8cae102021-03-11 01:37:42 +08003602Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003603 const std::string& packageName, const std::string& internalCamId,
3604 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003605 const sp<ICameraInjectionCallback>& callback,
3606 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003607 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003608 ATRACE_CALL();
3609
Austin Borgered99f642023-06-01 16:51:35 -07003610 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003611 const int pid = getCallingPid();
3612 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003613 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3614 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003615 "Permission Denial: no permission to inject camera");
3616 }
3617
3618 // Do not allow any camera injection that injects or replaces a virtual camera.
3619 auto [deviceIdForInternalCamera, _] =
3620 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3621 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3622 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3623 "Cannot replace a virtual camera");
3624 }
3625 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3626 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3627 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3628 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3629 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003630 }
3631
3632 ALOGV(
3633 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3634 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003635 __FUNCTION__, packageName.c_str(),
3636 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003637
Cliff Wud3a05312021-04-26 23:07:31 +08003638 {
3639 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003640 mInjectionInternalCamId = internalCamId;
3641 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003642 mInjectionStatusListener->addListener(callback);
3643 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003644 status_t res = NO_ERROR;
3645 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3646 // If the client already exists, we can directly connect to the camera device through the
3647 // client's injectCamera(), otherwise we need to wait until the client is established
3648 // (execute connectHelper()) before injecting the camera to the camera device.
3649 if (clientDescriptor != nullptr) {
3650 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003651 sp<BasicClient> clientSp = clientDescriptor->getValue();
3652 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3653 if(res != OK) {
3654 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3655 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003656 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003657 }
3658 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003659 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003660 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3661 }
3662 } else {
3663 mInjectionInitPending = true;
3664 }
3665 }
Cliff Wud8cae102021-03-11 01:37:42 +08003666
Cliff Wud3a05312021-04-26 23:07:31 +08003667 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003668}
3669
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003670Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003671 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003672 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3673 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3674 return Status::ok();
3675}
3676
Ruben Brunkcc776712015-02-17 20:18:47 -08003677void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003678 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003679 for (auto& i : mActiveClientManager.getAll()) {
3680 auto clientSp = i->getValue();
3681 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003682 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003683 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003684 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003685 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003686 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003687}
3688
Ruben Brunkcc776712015-02-17 20:18:47 -08003689bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003690 bool ret = false;
3691 {
3692 // Acquire mServiceLock and prevent other clients from connecting
3693 std::unique_ptr<AutoConditionLock> lock =
3694 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003695
Ruben Brunkcc776712015-02-17 20:18:47 -08003696 std::vector<sp<BasicClient>> evicted;
3697 for (auto& i : mActiveClientManager.getAll()) {
3698 auto clientSp = i->getValue();
3699 if (clientSp.get() == nullptr) {
3700 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3701 mActiveClientManager.remove(i);
3702 continue;
3703 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003704 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003705 mActiveClientManager.remove(i);
3706 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003707
Ruben Brunkcc776712015-02-17 20:18:47 -08003708 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003709 clientSp->notifyError(
3710 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003711 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003712 }
3713 }
3714
Ruben Brunkcc776712015-02-17 20:18:47 -08003715 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3716 // other clients from connecting in mServiceLockWrapper if held
3717 mServiceLock.unlock();
3718
Ruben Brunk36597b22015-03-20 22:15:57 -07003719 // Do not clear caller identity, remote caller should be client proccess
3720
Ruben Brunkcc776712015-02-17 20:18:47 -08003721 for (auto& i : evicted) {
3722 if (i.get() != nullptr) {
3723 i->disconnect();
3724 ret = true;
3725 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003726 }
3727
Ruben Brunkcc776712015-02-17 20:18:47 -08003728 // Reacquire mServiceLock
3729 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003730
Ruben Brunkcc776712015-02-17 20:18:47 -08003731 } // lock is destroyed, allow further connect calls
3732
3733 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003734}
3735
Ruben Brunkcc776712015-02-17 20:18:47 -08003736std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003737 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003738 std::shared_ptr<CameraState> state;
3739 {
3740 Mutex::Autolock lock(mCameraStatesLock);
3741 auto iter = mCameraStates.find(cameraId);
3742 if (iter != mCameraStates.end()) {
3743 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003744 }
3745 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003746 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003747}
3748
Austin Borgered99f642023-06-01 16:51:35 -07003749sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003750 // Remove from active clients list
3751 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3752 if (clientDescriptorPtr == nullptr) {
3753 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003754 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003755 return sp<BasicClient>{nullptr};
3756 }
3757
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003758 sp<BasicClient> client = clientDescriptorPtr->getValue();
3759 if (client.get() != nullptr) {
3760 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3761 }
3762 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003763}
3764
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003765void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003766 // Acquire mServiceLock and prevent other clients from connecting
3767 std::unique_ptr<AutoConditionLock> lock =
3768 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3769
Ruben Brunk6267b532015-04-30 17:44:07 -07003770 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003771 for (size_t i = 0; i < newUserIds.size(); i++) {
3772 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003773 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003774 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003775 return;
3776 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003777 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003778 }
3779
Ruben Brunka8ca9152015-04-07 14:23:40 -07003780
Ruben Brunk6267b532015-04-30 17:44:07 -07003781 if (newAllowedUsers == mAllowedUsers) {
3782 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3783 return;
3784 }
3785
3786 logUserSwitch(mAllowedUsers, newAllowedUsers);
3787
3788 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003789
3790 // Current user has switched, evict all current clients.
3791 std::vector<sp<BasicClient>> evicted;
3792 for (auto& i : mActiveClientManager.getAll()) {
3793 auto clientSp = i->getValue();
3794
3795 if (clientSp.get() == nullptr) {
3796 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3797 continue;
3798 }
3799
Ruben Brunk6267b532015-04-30 17:44:07 -07003800 // Don't evict clients that are still allowed.
3801 uid_t clientUid = clientSp->getClientUid();
3802 userid_t clientUserId = multiuser_get_user_id(clientUid);
3803 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3804 continue;
3805 }
3806
Ruben Brunk36597b22015-03-20 22:15:57 -07003807 evicted.push_back(clientSp);
3808
Ruben Brunk36597b22015-03-20 22:15:57 -07003809 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003810 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003811
Ruben Brunk36597b22015-03-20 22:15:57 -07003812 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003813 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003814 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003815 " to user switch.", i->getKey().c_str(),
3816 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003817 i->getOwnerId(), i->getPriority().getScore(),
3818 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003819
3820 }
3821
3822 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3823 // blocking other clients from connecting in mServiceLockWrapper if held.
3824 mServiceLock.unlock();
3825
3826 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003827 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003828
3829 for (auto& i : evicted) {
3830 i->disconnect();
3831 }
3832
Austin Borger22c5c852024-03-08 13:31:36 -08003833 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003834
3835 // Reacquire mServiceLock
3836 mServiceLock.lock();
3837}
Ruben Brunkcc776712015-02-17 20:18:47 -08003838
Austin Borgered99f642023-06-01 16:51:35 -07003839void CameraService::logEvent(const std::string &event) {
3840 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003841 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003842 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003843 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003844 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003845 mEventLog.add(msg);
3846 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3847 // Error event not added to the dumpsys log before
3848 mEventLog.add(msg);
3849 sServiceErrorEventSet.insert(msg);
3850 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003851}
3852
Austin Borgered99f642023-06-01 16:51:35 -07003853void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3854 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003855 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003856 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3857 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003858}
3859
Austin Borgered99f642023-06-01 16:51:35 -07003860void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3861 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003862 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003863 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3864 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003865}
3866
Austin Borgered99f642023-06-01 16:51:35 -07003867void CameraService::logConnected(const std::string &cameraId, int clientPid,
3868 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003869 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003870 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3871 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003872}
3873
Austin Borgered99f642023-06-01 16:51:35 -07003874void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3875 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003876 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003877 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3878 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003879}
3880
Austin Borgered99f642023-06-01 16:51:35 -07003881void CameraService::logRejected(const std::string &cameraId, int clientPid,
3882 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003883 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003884 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3885 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003886}
3887
Austin Borgered99f642023-06-01 16:51:35 -07003888void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3889 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003890 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003891 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3892 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003893}
3894
Ruben Brunk6267b532015-04-30 17:44:07 -07003895void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3896 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003897 std::string newUsers = toString(newUserIds);
3898 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003899 if (oldUsers.size() == 0) {
3900 oldUsers = "<None>";
3901 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003902 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003903 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3904 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003905}
3906
Austin Borgered99f642023-06-01 16:51:35 -07003907void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003908 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003909 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003910}
3911
Austin Borgered99f642023-06-01 16:51:35 -07003912void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003913 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003914 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003915}
3916
Austin Borgered99f642023-06-01 16:51:35 -07003917void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003918 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003919 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003920}
3921
Austin Borgered99f642023-06-01 16:51:35 -07003922void CameraService::logServiceError(const std::string &msg, int errorCode) {
3923 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3924 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003925}
3926
Ruben Brunk36597b22015-03-20 22:15:57 -07003927status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3928 uint32_t flags) {
3929
Mathias Agopian65ab4712010-07-14 17:59:35 -07003930 // Permission checks
3931 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003932 case SHELL_COMMAND_TRANSACTION: {
3933 int in = data.readFileDescriptor();
3934 int out = data.readFileDescriptor();
3935 int err = data.readFileDescriptor();
3936 int argc = data.readInt32();
3937 Vector<String16> args;
3938 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3939 args.add(data.readString16());
3940 }
3941 sp<IBinder> unusedCallback;
3942 sp<IResultReceiver> resultReceiver;
3943 status_t status;
3944 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3945 return status;
3946 }
3947 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3948 return status;
3949 }
3950 status = shellCommand(in, out, err, args);
3951 if (resultReceiver != nullptr) {
3952 resultReceiver->send(status);
3953 }
3954 return NO_ERROR;
3955 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003956 }
3957
3958 return BnCameraService::onTransact(code, data, reply, flags);
3959}
3960
Mathias Agopian65ab4712010-07-14 17:59:35 -07003961// We share the media players for shutter and recording sound for all clients.
3962// A reference count is kept to determine when we will actually release the
3963// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003964sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3965 sp<MediaPlayer> mp = new MediaPlayer();
3966 status_t error;
3967 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003968 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003969 error = mp->prepare();
3970 }
3971 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003972 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003973 mp->disconnect();
3974 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003975 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976 }
3977 return mp;
3978}
3979
username5755fea2018-12-27 09:48:08 +08003980void CameraService::increaseSoundRef() {
3981 Mutex::Autolock lock(mSoundLock);
3982 mSoundRef++;
3983}
3984
3985void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003986 ATRACE_CALL();
3987
username5755fea2018-12-27 09:48:08 +08003988 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3989 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3990 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3991 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3992 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3993 }
3994 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3995 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3996 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3997 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003998 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003999 }
4000 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4001 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4002 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4003 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4004 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004005 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004006}
4007
username5755fea2018-12-27 09:48:08 +08004008void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004009 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004010 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004011 if (--mSoundRef) return;
4012
4013 for (int i = 0; i < NUM_SOUNDS; i++) {
4014 if (mSoundPlayer[i] != 0) {
4015 mSoundPlayer[i]->disconnect();
4016 mSoundPlayer[i].clear();
4017 }
4018 }
4019}
4020
4021void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004022 ATRACE_CALL();
4023
Mathias Agopian65ab4712010-07-14 17:59:35 -07004024 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004025 if (kind < 0 || kind >= NUM_SOUNDS) {
4026 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4027 return;
4028 }
4029
Mathias Agopian65ab4712010-07-14 17:59:35 -07004030 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004031 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 sp<MediaPlayer> player = mSoundPlayer[kind];
4033 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004034 player->seekTo(0);
4035 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004036 }
4037}
4038
4039// ----------------------------------------------------------------------------
4040
Austin Borger2e772b82024-10-11 16:09:57 -07004041CameraService::Client::Client(
4042 const sp<CameraService>& cameraService, const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004043 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004044 const AttributionSourceState& clientAttribution, int callingPid, bool systemNativeClient,
4045 const std::string& cameraIdStr, int api1CameraId, int cameraFacing, int sensorOrientation,
4046 int servicePid, int rotationOverride)
4047 : CameraService::BasicClient(cameraService, IInterface::asBinder(cameraClient),
4048 attributionAndPermissionUtils, clientAttribution, callingPid,
4049 systemNativeClient, cameraIdStr, cameraFacing, sensorOrientation,
4050 servicePid, rotationOverride),
4051 mCameraId(api1CameraId) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004052 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004054 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055
username5755fea2018-12-27 09:48:08 +08004056 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004057
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004058 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059}
4060
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061// tear down the client
4062CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004063 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004064 mDestructionStarted = true;
4065
username5755fea2018-12-27 09:48:08 +08004066 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004067 // unconditionally disconnect. function is idempotent
4068 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004069}
4070
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004071sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4072
Austin Borger2e772b82024-10-11 16:09:57 -07004073CameraService::BasicClient::BasicClient(
4074 const sp<CameraService>& cameraService, const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004075 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borger2e772b82024-10-11 16:09:57 -07004076 const AttributionSourceState& clientAttribution, int callingPid, bool nativeClient,
4077 const std::string& cameraIdStr, int cameraFacing, int sensorOrientation, int servicePid,
4078 int rotationOverride)
4079 : AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
4080 mDestructionStarted(false),
4081 mCameraIdStr(cameraIdStr),
4082 mCameraFacing(cameraFacing),
4083 mOrientation(sensorOrientation),
4084 mClientAttribution(clientAttribution),
4085 mCallingPid(callingPid),
4086 mSystemNativeClient(nativeClient),
4087 mServicePid(servicePid),
4088 mDisconnected(false),
4089 mUidIsTrusted(false),
4090 mRotationOverride(rotationOverride),
4091 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
4092 mRemoteBinder(remoteCallback),
Austin Borgera0c61f12024-10-11 13:38:35 -07004093 mCameraOpen(false),
4094 mCameraStreaming(false) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004095 if (sCameraService == nullptr) {
4096 sCameraService = cameraService;
4097 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004098
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004099 // There are 2 scenarios in which a client won't have AppOps operations
4100 // (both scenarios : native clients)
4101 // 1) It's an system native client*, the package name will be empty
4102 // and it will return from this function in the previous if condition
4103 // (This is the same as the previously existing behavior).
4104 // 2) It is a system native client, but its package name has been
4105 // modified for debugging, however it still must not use AppOps since
4106 // the package name is not a real one.
4107 //
4108 // * system native client - native client with UID < AID_APP_START. It
4109 // doesn't exclude clients not on the system partition.
4110 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004111 mAppOpsManager = std::make_unique<AppOpsManager>();
4112 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004113
Austin Borger32163932024-10-25 13:56:52 -07004114 mUidIsTrusted = isTrustedCallingUid(mClientAttribution.uid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004115}
4116
4117CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004118 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004119 mDestructionStarted = true;
4120}
4121
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004122binder::Status CameraService::BasicClient::disconnect() {
4123 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004124 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004125 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004126 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004127 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004128
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004129 sCameraService->removeByClient(this);
Austin Borger2e772b82024-10-11 16:09:57 -07004130 sCameraService->logDisconnected(mCameraIdStr, mCallingPid, getPackageName());
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004131 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004132 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004133
4134 sp<IBinder> remote = getRemote();
4135 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004136 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004137 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004138
Austin Borgera0c61f12024-10-11 13:38:35 -07004139 notifyCameraClosing();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004140 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004141 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004142 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004143 mCallingPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004144
Igor Murashkincba2c162013-03-20 15:56:31 -07004145 // client shouldn't be able to call into us anymore
Austin Borger2e772b82024-10-11 16:09:57 -07004146 mCallingPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004147
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004148 const auto& mActivityManager = getActivityManager();
4149 if (mActivityManager) {
4150 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004151 getCallingUid(),
4152 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004153 }
4154
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004155 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004156}
4157
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004158status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4159 // No dumping of clients directly over Binder,
4160 // must go through CameraService::dump
4161 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004162 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004163 return OK;
4164}
4165
Austin Borgered99f642023-06-01 16:51:35 -07004166status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004167 // Can't watch tags directly, must go through CameraService::startWatchingTags
4168 return OK;
4169}
4170
4171status_t CameraService::BasicClient::stopWatchingTags(int) {
4172 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4173 return OK;
4174}
4175
4176status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4177 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4178 return OK;
4179}
4180
Austin Borgered99f642023-06-01 16:51:35 -07004181std::string CameraService::BasicClient::getPackageName() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004182 return mClientAttribution.packageName.value_or(kUnknownPackageName);
Ruben Brunkcc776712015-02-17 20:18:47 -08004183}
4184
Emilian Peev8b64f282021-03-25 16:49:57 -07004185int CameraService::BasicClient::getCameraFacing() const {
4186 return mCameraFacing;
4187}
4188
4189int CameraService::BasicClient::getCameraOrientation() const {
4190 return mOrientation;
4191}
Ruben Brunkcc776712015-02-17 20:18:47 -08004192
Austin Borger2e772b82024-10-11 16:09:57 -07004193int CameraService::BasicClient::getClientCallingPid() const {
4194 return mCallingPid;
Ruben Brunkcc776712015-02-17 20:18:47 -08004195}
4196
Ruben Brunk6267b532015-04-30 17:44:07 -07004197uid_t CameraService::BasicClient::getClientUid() const {
Austin Borger2e772b82024-10-11 16:09:57 -07004198 return mClientAttribution.uid;
4199}
4200
4201const std::optional<std::string>& CameraService::BasicClient::getClientAttributionTag() const {
4202 return mClientAttribution.attributionTag;
Ruben Brunk6267b532015-04-30 17:44:07 -07004203}
4204
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004205bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4206 // Defaults to API2.
4207 return level == API_2;
4208}
4209
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004210status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004211 {
4212 Mutex::Autolock l(mAudioRestrictionLock);
4213 mAudioRestriction = mode;
4214 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004215 sCameraService->updateAudioRestriction();
4216 return OK;
4217}
4218
4219int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004220 return sCameraService->updateAudioRestriction();
4221}
4222
4223int32_t CameraService::BasicClient::getAudioRestriction() const {
4224 Mutex::Autolock l(mAudioRestrictionLock);
4225 return mAudioRestriction;
4226}
4227
4228bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4229 switch (mode) {
4230 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4231 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4232 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4233 return true;
4234 default:
4235 return false;
4236 }
4237}
4238
Austin Borgera0c61f12024-10-11 13:38:35 -07004239status_t CameraService::BasicClient::handlePermissionResult(
4240 PermissionChecker::PermissionResult result) {
4241 if (result == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004242 ALOGI("Camera %s: Access for \"%s\" has been revoked", mCameraIdStr.c_str(),
4243 getPackageName().c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004244 return PERMISSION_DENIED;
Austin Borgera0c61f12024-10-11 13:38:35 -07004245 } else if (!mUidIsTrusted && result == PermissionChecker::PERMISSION_SOFT_DENIED) {
4246 // If the calling Uid is trusted (a native service), the AppOpsManager/PermissionChecker
4247 // could return MODE_IGNORED/PERMISSION_SOFT_DENIED. Do not treat such case as error.
Austin Borger2e772b82024-10-11 16:09:57 -07004248 bool isUidActive =
4249 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004250
4251 bool isCameraPrivacyEnabled;
4252 if (flags::camera_privacy_allowlist()) {
4253 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004254 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004255 } else {
4256 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004257 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004258 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004259 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4260 // We prefer to successfully open the camera and perform camera muting
4261 // or blocking in connectHelper as handleAppOpMode can be called before the
4262 // connection has been fully established and at that time camera muting
4263 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004264 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004265 ALOGI("Camera %s: Access for \"%s\" has been restricted."
Austin Borger2e772b82024-10-11 16:09:57 -07004266 "uid active: %s, privacy enabled: %s",
4267 mCameraIdStr.c_str(), getPackageName().c_str(), isUidActive ? "true" : "false",
4268 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004269 // Return the same error as for device policy manager rejection
4270 return -EACCES;
4271 }
4272 }
4273 return OK;
4274}
4275
Austin Borgera0c61f12024-10-11 13:38:35 -07004276status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4277 return handlePermissionResult(appOpModeToPermissionResult(mode));
4278}
4279
4280status_t CameraService::BasicClient::notifyCameraOpening() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004281 ATRACE_CALL();
4282
Austin Borgera0c61f12024-10-11 13:38:35 -07004283 // Don't start watching until we're streaming when using permissionChecker for data delivery
Austin Borger2a3f9a72024-11-07 12:24:49 -08004284 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004285 ALOGD("%s: Start camera ops, package name = %s, client UID = %d", __FUNCTION__,
Austin Borger2e772b82024-10-11 16:09:57 -07004286 getPackageName().c_str(), getClientUid());
Austin Borgerca1e0062023-06-28 11:32:55 -07004287
Austin Borgera0c61f12024-10-11 13:38:35 -07004288 if (mAppOpsManager != nullptr) {
4289 // Notify app ops that the camera is not available
4290 mOpsCallback = new OpsCallback(this);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004291
Austin Borgera0c61f12024-10-11 13:38:35 -07004292 mAppOpsManager->startWatchingMode(
4293 AppOpsManager::OP_CAMERA, toString16(getPackageName()),
4294 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4295
4296 // Just check for camera access here on open - delay startOp until
4297 // camera frames start streaming in startCameraStreamingOps
4298 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4299 toString16(getPackageName()));
4300 status_t res = handleAppOpMode(mode);
4301 if (res != OK) {
4302 return res;
4303 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004304 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004305 } else {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004306 // TODO: Remove when removing the data_delivery_permission_checks flag
Austin Borgera0c61f12024-10-11 13:38:35 -07004307 ALOGD("%s: Bypassing checkOp for uid %d", __FUNCTION__, getClientUid());
Svetoslav28e8ef72015-05-11 19:21:31 -07004308 }
4309
Austin Borgera0c61f12024-10-11 13:38:35 -07004310 mCameraOpen = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004311
4312 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004313 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004314
Austin Borger2e772b82024-10-11 16:09:57 -07004315 sCameraService->mUidPolicy->registerMonitorUid(getClientUid(), /*openCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004316
Shuzhen Wang695044d2020-03-06 09:02:23 -08004317 // Notify listeners of camera open/close status
Austin Borger2e772b82024-10-11 16:09:57 -07004318 sCameraService->updateOpenCloseStatus(mCameraIdStr, true /*open*/, getPackageName());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004319
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004320 return OK;
4321}
4322
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004323status_t CameraService::BasicClient::startCameraStreamingOps() {
4324 ATRACE_CALL();
4325
Austin Borgera0c61f12024-10-11 13:38:35 -07004326 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004327 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4328 return INVALID_OPERATION;
4329 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004330
4331 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004332 ALOGV("%s: Streaming already active!", __FUNCTION__);
4333 return OK;
4334 }
4335
Austin Borger2e772b82024-10-11 16:09:57 -07004336 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d", __FUNCTION__,
4337 getPackageName().c_str(), getClientUid());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004338
4339 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004340 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004341 ALOGD("%s: Start data delivery for uid %d", __FUNCTION__, getClientUid());
4342
4343 const PermissionChecker::PermissionResult result =
4344 checkPermissionsForCameraForStartDataDelivery(mCameraIdStr, mClientAttribution);
4345 status_t res = handlePermissionResult(result);
4346 if (res != OK) {
4347 return res;
4348 }
4349
4350 mOpsCallback = new OpsCallback(this);
4351 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4352 [&](const auto& attr) {
4353 mAppOpsManager->startWatchingMode(
4354 AppOpsManager::OP_CAMERA,
4355 toString16(attr.packageName.value_or("")),
4356 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4357 });
4358 } else {
4359 ALOGD("%s: startOp for uid %d", __FUNCTION__, getClientUid());
4360 int32_t mode = mAppOpsManager->startOpNoThrow(
4361 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4362 /*startIfModeDefault*/ false, toString16(getClientAttributionTag()),
4363 toString16("start camera ") + toString16(mCameraIdStr));
4364 status_t res = handleAppOpMode(mode);
4365 if (res != OK) {
4366 return res;
4367 }
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004368 }
4369 }
4370
Austin Borgera0c61f12024-10-11 13:38:35 -07004371 mCameraStreaming = true;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004372
4373 return OK;
4374}
4375
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004376status_t CameraService::BasicClient::noteAppOp() {
4377 ATRACE_CALL();
4378
Austin Borger2e772b82024-10-11 16:09:57 -07004379 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d", __FUNCTION__,
4380 getPackageName().c_str(), getClientUid());
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004381
4382 // noteAppOp is only used for when camera mute is not supported, in order
4383 // to trigger the sensor privacy "Unblock" dialog
Austin Borger2a3f9a72024-11-07 12:24:49 -08004384 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004385 // Ignore the result, since we're only triggering the dialog
4386 ALOGD("%s: Check data delivery permissions for uid %d", __FUNCTION__, getClientUid());
4387 hasPermissionsForCameraForDataDelivery(std::string(), mClientAttribution);
4388 } else if (mAppOpsManager != nullptr) {
4389 ALOGD("%s: noteOp for uid %d", __FUNCTION__, getClientUid());
Austin Borger2e772b82024-10-11 16:09:57 -07004390 int32_t mode = mAppOpsManager->noteOp(
4391 AppOpsManager::OP_CAMERA, getClientUid(), toString16(getPackageName()),
4392 toString16(getClientAttributionTag()),
Austin Borgered99f642023-06-01 16:51:35 -07004393 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004394 status_t res = handleAppOpMode(mode);
4395 if (res != OK) {
4396 return res;
4397 }
4398 }
4399
4400 return OK;
4401}
4402
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004403status_t CameraService::BasicClient::finishCameraStreamingOps() {
4404 ATRACE_CALL();
4405
Austin Borgera0c61f12024-10-11 13:38:35 -07004406 if (!mCameraOpen) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004407 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4408 return INVALID_OPERATION;
4409 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004410 if (!mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004411 ALOGV("%s: Streaming not active!", __FUNCTION__);
4412 return OK;
4413 }
4414
4415 if (mAppOpsManager != nullptr) {
Austin Borger2a3f9a72024-11-07 12:24:49 -08004416 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004417 ALOGD("%s: finishDataDelivery for uid %d", __FUNCTION__, getClientUid());
4418 finishDataDelivery(mClientAttribution);
4419
4420 // Stop watching app op changes after stop streaming
4421 if (mOpsCallback != nullptr) {
4422 mAppOpsManager->stopWatchingMode(mOpsCallback);
4423 mOpsCallback.clear();
4424 }
4425 } else {
4426 ALOGD("%s: finishOp for uid %d", __FUNCTION__, getClientUid());
4427 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, getClientUid(),
4428 toString16(getPackageName()),
4429 toString16(getClientAttributionTag()));
4430 }
4431 mCameraStreaming = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004432 }
4433
4434 return OK;
4435}
4436
Austin Borgera0c61f12024-10-11 13:38:35 -07004437status_t CameraService::BasicClient::notifyCameraClosing() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004438 ATRACE_CALL();
4439
Austin Borgera0c61f12024-10-11 13:38:35 -07004440 if (mCameraStreaming) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004441 // Make sure we've notified everyone about camera stopping
4442 finishCameraStreamingOps();
4443 }
4444
Austin Borgera0c61f12024-10-11 13:38:35 -07004445 // Check if notifyCameraOpening succeeded, and if so, finish the camera op if necessary
4446 if (mCameraOpen) {
4447 mCameraOpen = false;
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004448
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004449 // This function is called when a client disconnects. This should
4450 // release the camera, but actually only if it was in a proper
4451 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004452 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004453 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004454
Ruben Brunkcc776712015-02-17 20:18:47 -08004455 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004456 sCameraService->updateStatus(StatusInternal::PRESENT,
4457 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004458 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004459
4460 // When using the data delivery permission checks, the open state does not involve AppOps
Austin Borger2a3f9a72024-11-07 12:24:49 -08004461 if (!flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004462 // Always stop watching, even if no camera op is active
4463 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4464 mAppOpsManager->stopWatchingMode(mOpsCallback);
4465 }
4466 mOpsCallback.clear();
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004467 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004468
Austin Borger2e772b82024-10-11 16:09:57 -07004469 sCameraService->mUidPolicy->unregisterMonitorUid(getClientUid(), /*closeCamera*/ true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004470
Shuzhen Wang695044d2020-03-06 09:02:23 -08004471 // Notify listeners of camera open/close status
Austin Borger2e772b82024-10-11 16:09:57 -07004472 sCameraService->updateOpenCloseStatus(mCameraIdStr, false /*open*/, getPackageName());
Shuzhen Wang695044d2020-03-06 09:02:23 -08004473
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004474 return OK;
4475}
4476
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004477void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004478 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004479 if (mAppOpsManager == nullptr) {
4480 return;
4481 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004482 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004483 if (op != AppOpsManager::OP_CAMERA) {
4484 ALOGW("Unexpected app ops notification received: %d", op);
4485 return;
4486 }
4487
Austin Borgera0c61f12024-10-11 13:38:35 -07004488 PermissionChecker::PermissionResult res;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004489 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004490 int32_t appOpMode = AppOpsManager::MODE_ALLOWED;
4491 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4492 [&](const auto& attr) {
4493 appOpMode = std::max(appOpMode, mAppOpsManager->checkOp(
4494 AppOpsManager::OP_CAMERA, attr.uid,
4495 toString16(attr.packageName.value_or(""))));
4496 });
4497 ALOGV("checkOp returns: %d, %s ", res,
4498 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4499 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4500 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4501 : "UNKNOWN");
4502 res = appOpModeToPermissionResult(appOpMode);
4503 } else {
4504 int32_t appOpMode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, getClientUid(),
4505 toString16(getPackageName()));
4506 ALOGV("checkOp returns: %d, %s ", res,
4507 appOpMode == AppOpsManager::MODE_ALLOWED ? "ALLOWED"
4508 : appOpMode == AppOpsManager::MODE_IGNORED ? "IGNORED"
4509 : appOpMode == AppOpsManager::MODE_ERRORED ? "ERRORED"
4510 : "UNKNOWN");
4511 res = appOpModeToPermissionResult(appOpMode);
4512 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004513
Austin Borgera0c61f12024-10-11 13:38:35 -07004514 if (res == PermissionChecker::PERMISSION_HARD_DENIED) {
Austin Borgered99f642023-06-01 16:51:35 -07004515 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
Austin Borger2e772b82024-10-11 16:09:57 -07004516 getPackageName().c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004517 block();
Austin Borgera0c61f12024-10-11 13:38:35 -07004518 } else if (res == PermissionChecker::PERMISSION_SOFT_DENIED) {
Austin Borger2e772b82024-10-11 16:09:57 -07004519 bool isUidActive =
4520 sCameraService->mUidPolicy->isUidActive(getClientUid(), getPackageName());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004521
Austin Borgerca1e0062023-06-28 11:32:55 -07004522 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4523 // If not visible, but still active, then we want to block instead of muting the camera.
Austin Borgera0c61f12024-10-11 13:38:35 -07004524 int32_t procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borger2a3f9a72024-11-07 12:24:49 -08004525 if (flags::data_delivery_permission_checks()) {
Austin Borgera0c61f12024-10-11 13:38:35 -07004526 // Use the proc state of the last uid in the chain (ultimately receiving the data)
4527 // when determining whether to mute or block
4528 int32_t uid = -1;
4529 std::for_each(AttrSourceItr{mClientAttribution}, AttrSourceItr::end(),
4530 [&](const auto& attr) {
4531 uid = static_cast<uid_t>(attr.uid);
4532 });
4533 const auto& activityManager = getActivityManager();
4534 if (activityManager != nullptr) {
4535 procState = activityManager->getUidProcessState(uid, toString16(kServiceName));
4536 } else {
4537 ALOGD("%s: getActivityManager returned nullptr.", __FUNCTION__);
4538 }
4539 } else {
4540 procState = sCameraService->mUidPolicy->getProcState(getClientUid());
4541 }
Austin Borgerca1e0062023-06-28 11:32:55 -07004542 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4543
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004544 bool isCameraPrivacyEnabled;
4545 if (flags::camera_privacy_allowlist()) {
4546 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
Austin Borger2e772b82024-10-11 16:09:57 -07004547 toString16(getPackageName()), std::string(), mCallingPid, getClientUid());
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004548 } else {
4549 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004550 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004551 }
4552
4553 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgera0c61f12024-10-11 13:38:35 -07004554 " isUidVisible %d, isCameraPrivacyEnabled %d procState %d",
Austin Borger2e772b82024-10-11 16:09:57 -07004555 mCameraIdStr.c_str(), getPackageName().c_str(), mUidIsTrusted, isUidActive,
Austin Borgera0c61f12024-10-11 13:38:35 -07004556 isUidVisible, isCameraPrivacyEnabled, procState);
Austin Borgerca1e0062023-06-28 11:32:55 -07004557 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4558 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4559 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004560 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004561 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4562 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004563 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004564 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004565 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004566 }
Austin Borgera0c61f12024-10-11 13:38:35 -07004567 } else if (res == PermissionChecker::PERMISSION_GRANTED) {
Evan Severson09ab4002021-02-10 14:15:19 -08004568 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004569 }
4570}
4571
Svet Ganova453d0d2018-01-11 15:37:58 -08004572void CameraService::BasicClient::block() {
4573 ATRACE_CALL();
4574
4575 // Reset the client PID to allow server-initiated disconnect,
4576 // and to prevent further calls by client.
Austin Borger2e772b82024-10-11 16:09:57 -07004577 mCallingPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004578 CaptureResultExtras resultExtras; // a dummy result (invalid)
4579 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4580 disconnect();
4581}
4582
Mathias Agopian65ab4712010-07-14 17:59:35 -07004583// ----------------------------------------------------------------------------
4584
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004585void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004586 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004587 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004588 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4589 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4590 api1ErrorCode = CAMERA_ERROR_DISABLED;
4591 }
4592 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004593 } else {
4594 ALOGE("mRemoteCallback is NULL!!");
4595 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004596}
4597
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004598// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004599binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004600 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004601 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004602}
4603
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004604bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4605 return level == API_1;
4606}
4607
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004608CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4609 mClient(client) {
4610}
4611
4612void CameraService::Client::OpsCallback::opChanged(int32_t op,
4613 const String16& packageName) {
4614 sp<BasicClient> client = mClient.promote();
4615 if (client != NULL) {
4616 client->opChanged(op, packageName);
4617 }
4618}
4619
Mathias Agopian65ab4712010-07-14 17:59:35 -07004620// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004621// UidPolicy
4622// ----------------------------------------------------------------------------
4623
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004624void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004625 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004626 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004627
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004628 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004629 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004630 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004631 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004632 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4633 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004634 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004635 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004636 if (res == OK) {
4637 mRegistered = true;
4638 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004639 } else {
4640 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004641 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004642}
4643
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004644void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004645 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004646 return;
4647 }
4648
4649 registerWithActivityManager();
4650}
4651
4652void CameraService::UidPolicy::registerSelf() {
4653 // Use check service to see if the activity service is available
4654 // If not available then register for notifications, instead of blocking
4655 // till the service is ready
4656 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004657 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004658 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004659 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004660 } else {
4661 registerWithActivityManager();
4662 }
4663}
4664
Svet Ganova453d0d2018-01-11 15:37:58 -08004665void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004666 Mutex::Autolock _l(mUidLock);
4667
Steven Moreland2f348142019-07-02 15:59:07 -07004668 mAm.unregisterUidObserver(this);
4669 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004670 mRegistered = false;
4671 mActiveUids.clear();
4672 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004673}
4674
4675void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4676 onUidIdle(uid, disabled);
4677}
4678
4679void CameraService::UidPolicy::onUidActive(uid_t uid) {
4680 Mutex::Autolock _l(mUidLock);
4681 mActiveUids.insert(uid);
4682}
4683
4684void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4685 bool deleted = false;
4686 {
4687 Mutex::Autolock _l(mUidLock);
4688 if (mActiveUids.erase(uid) > 0) {
4689 deleted = true;
4690 }
4691 }
4692 if (deleted) {
4693 sp<CameraService> service = mService.promote();
4694 if (service != nullptr) {
4695 service->blockClientsForUid(uid);
4696 }
4697 }
4698}
4699
Emilian Peev53722fa2019-02-22 17:47:20 -08004700void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004701 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004702 bool procStateChange = false;
4703 {
4704 Mutex::Autolock _l(mUidLock);
4705 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4706 mMonitoredUids[uid].procState != procState) {
4707 mMonitoredUids[uid].procState = procState;
4708 procStateChange = true;
4709 }
4710 }
4711
4712 if (procStateChange) {
4713 sp<CameraService> service = mService.promote();
4714 if (service != nullptr) {
4715 service->notifyMonitoredUids();
4716 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004717 }
4718}
4719
Austin Borgerdddb7552023-03-30 17:53:01 -07004720/**
4721 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4722 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4723 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4724 * monitoredUids. If it is revised above some other monitoredUid, signal
4725 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4726 * foreground apps in split screen - state changes will capture all other cases.
4727 */
4728void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4729 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004730 {
4731 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004732 auto it = mMonitoredUids.find(uid);
4733
4734 if (it != mMonitoredUids.end()) {
4735 if (it->second.hasCamera) {
4736 for (auto &monitoredUid : mMonitoredUids) {
4737 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004738 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004739 notifyUidSet.emplace(monitoredUid.first);
4740 }
4741 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004742 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004743 notifyUidSet.emplace(uid);
4744 } else {
4745 for (auto &monitoredUid : mMonitoredUids) {
4746 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004747 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004748 notifyUidSet.emplace(uid);
4749 }
4750 }
4751 }
4752 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004753 }
4754 }
4755
Austin Borgerdddb7552023-03-30 17:53:01 -07004756 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004757 sp<CameraService> service = mService.promote();
4758 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004759 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004760 }
4761 }
4762}
4763
Austin Borgerdddb7552023-03-30 17:53:01 -07004764/**
4765 * Register a uid for monitoring, and note whether it owns a camera.
4766 */
4767void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004768 Mutex::Autolock _l(mUidLock);
4769 auto it = mMonitoredUids.find(uid);
4770 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004771 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004772 } else {
Austin Borger65577682022-02-17 00:25:43 +00004773 MonitoredUid monitoredUid;
4774 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004775 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004776 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004777 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004778 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004779 if (res != OK) {
4780 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4781 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004782 }
4783
4784 if (openCamera) {
4785 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004786 }
4787}
4788
Austin Borgerdddb7552023-03-30 17:53:01 -07004789/**
4790 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4791 */
4792void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004793 Mutex::Autolock _l(mUidLock);
4794 auto it = mMonitoredUids.find(uid);
4795 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004796 it->second.refCount--;
4797 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004798 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004799 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004800 if (res != OK) {
4801 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4802 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004803 } else if (closeCamera) {
4804 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004805 }
4806 } else {
4807 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4808 }
4809}
4810
Austin Borgered99f642023-06-01 16:51:35 -07004811bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004812 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004813 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004814}
4815
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004816static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4817static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004818
Austin Borgered99f642023-06-01 16:51:35 -07004819bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004820 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004821 // If activity manager is unreachable, assume everything is active
4822 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004823 return true;
4824 }
4825 auto it = mOverrideUids.find(uid);
4826 if (it != mOverrideUids.end()) {
4827 return it->second;
4828 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004829 bool active = mActiveUids.find(uid) != mActiveUids.end();
4830 if (!active) {
4831 // We want active UIDs to always access camera with their first attempt since
4832 // there is no guarantee the app is robustly written and would retry getting
4833 // the camera on failure. The inverse case is not a problem as we would take
4834 // camera away soon once we get the callback that the uid is no longer active.
4835 ActivityManager am;
4836 // Okay to access with a lock held as UID changes are dispatched without
4837 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004838 int64_t startTimeMillis = 0;
4839 do {
4840 // TODO: Fix this b/109950150!
4841 // Okay this is a hack. There is a race between the UID turning active and
4842 // activity being resumed. The proper fix is very risky, so we temporary add
4843 // some polling which should happen pretty rarely anyway as the race is hard
4844 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004845 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004846 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004847 if (active) {
4848 break;
4849 }
4850 if (startTimeMillis <= 0) {
4851 startTimeMillis = uptimeMillis();
4852 }
4853 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004854 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004855 if (remainingTimeMillis <= 0) {
4856 break;
4857 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004858 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4859
4860 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004861 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004862 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004863 } while (true);
4864
Svet Ganov7b4ab782018-03-25 12:48:10 -07004865 if (active) {
4866 // Now that we found out the UID is actually active, cache that
4867 mActiveUids.insert(uid);
4868 }
4869 }
4870 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004871}
4872
Varun Shahb42f1eb2019-04-16 14:45:13 -07004873int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4874 Mutex::Autolock _l(mUidLock);
4875 return getProcStateLocked(uid);
4876}
4877
4878int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4879 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4880 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004881 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004882 }
4883 return procState;
4884}
4885
Austin Borgered99f642023-06-01 16:51:35 -07004886void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4887 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004888 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004889}
4890
Austin Borgered99f642023-06-01 16:51:35 -07004891void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004892 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004893}
4894
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004895void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4896 Mutex::Autolock _l(mUidLock);
4897 ALOGV("UidPolicy: ActivityManager has died");
4898 mRegistered = false;
4899 mActiveUids.clear();
4900}
4901
Austin Borgered99f642023-06-01 16:51:35 -07004902void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004903 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004904 bool wasActive = false;
4905 bool isActive = false;
4906 {
4907 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004908 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004909 mOverrideUids.erase(uid);
4910 if (insert) {
4911 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4912 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004913 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004914 }
4915 if (wasActive != isActive && !isActive) {
4916 sp<CameraService> service = mService.promote();
4917 if (service != nullptr) {
4918 service->blockClientsForUid(uid);
4919 }
4920 }
4921}
4922
4923// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004924// SensorPrivacyPolicy
4925// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004926
4927void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4928{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004929 Mutex::Autolock _l(mSensorPrivacyLock);
4930 if (mRegistered) {
4931 return;
4932 }
Evan Severson09ab4002021-02-10 14:15:19 -08004933 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004934 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004935 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004936 mSpm.addToggleSensorPrivacyListener(this);
4937 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004938 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004939 if (flags::camera_privacy_allowlist()) {
4940 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4941 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4942 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4943 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004944 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004945 if (res == OK) {
4946 mRegistered = true;
4947 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4948 }
4949}
4950
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004951void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4952 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004953 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004954 return;
4955 }
4956
4957 registerWithSensorPrivacyManager();
4958}
4959
4960void CameraService::SensorPrivacyPolicy::registerSelf() {
4961 // Use checkservice to see if the sensor_privacy service is available
4962 // If service is not available then register for notification
4963 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004964 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004965 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004966 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004967 } else {
4968 registerWithSensorPrivacyManager();
4969 }
4970}
4971
Michael Grooverd1d435a2018-12-18 17:39:42 -08004972void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4973 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004974 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004975 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004976 mSpm.removeToggleSensorPrivacyListener(this);
4977 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004978 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004979 mRegistered = false;
4980 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4981}
4982
4983bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004984 if (!mRegistered) {
4985 registerWithSensorPrivacyManager();
4986 }
4987
Michael Grooverd1d435a2018-12-18 17:39:42 -08004988 Mutex::Autolock _l(mSensorPrivacyLock);
4989 return mSensorPrivacyEnabled;
4990}
4991
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004992int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4993 if (!mRegistered) {
4994 registerWithSensorPrivacyManager();
4995 }
4996
4997 Mutex::Autolock _l(mSensorPrivacyLock);
4998 return mCameraPrivacyState;
4999}
5000
Evan Seversond0b69922022-01-27 10:47:34 -08005001bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005002 if (!hasCameraPrivacyFeature()) {
5003 return false;
5004 }
Evan Seversond0b69922022-01-27 10:47:34 -08005005 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005006}
5007
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005008bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5009 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07005010 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005011 }
5012 return mSpm.isCameraPrivacyEnabled(packageName);
5013}
5014
Evan Seversond0b69922022-01-27 10:47:34 -08005015binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005016 int toggleType, int sensor, bool enabled) {
5017 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5018 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5019 {
5020 Mutex::Autolock _l(mSensorPrivacyLock);
5021 mSensorPrivacyEnabled = enabled;
5022 }
5023 // if sensor privacy is enabled then block all clients from accessing the camera
5024 if (enabled) {
5025 sp<CameraService> service = mService.promote();
5026 if (service != nullptr) {
5027 service->blockAllClients();
5028 }
5029 }
5030 }
5031 return binder::Status::ok();
5032}
5033
5034binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5035 int, int sensor, int state) {
5036 if (!flags::camera_privacy_allowlist()
5037 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5038 return binder::Status::ok();
5039 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005040 {
5041 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005042 mCameraPrivacyState = state;
5043 }
5044 sp<CameraService> service = mService.promote();
5045 if (!service) {
5046 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005047 }
5048 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005049 if (state == SensorPrivacyManager::ENABLED) {
5050 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005051 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005052 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005053 }
5054 return binder::Status::ok();
5055}
5056
5057void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5058 Mutex::Autolock _l(mSensorPrivacyLock);
5059 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5060 mRegistered = false;
5061}
5062
Evan Severson09ab4002021-02-10 14:15:19 -08005063bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005064 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5065 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5066 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5067 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5068 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005069}
5070
Michael Grooverd1d435a2018-12-18 17:39:42 -08005071// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005072// CameraState
5073// ----------------------------------------------------------------------------
5074
Austin Borgered99f642023-06-01 16:51:35 -07005075CameraService::CameraState::CameraState(const std::string& id, int cost,
5076 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005077 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005078 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005079 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005080
5081CameraService::CameraState::~CameraState() {}
5082
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005083CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005084 Mutex::Autolock lock(mStatusLock);
5085 return mStatus;
5086}
5087
Austin Borgered99f642023-06-01 16:51:35 -07005088std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005089 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005090 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005091 return res;
5092}
5093
Ruben Brunkcc776712015-02-17 20:18:47 -08005094CameraParameters CameraService::CameraState::getShimParams() const {
5095 return mShimParams;
5096}
5097
5098void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5099 mShimParams = params;
5100}
5101
5102int CameraService::CameraState::getCost() const {
5103 return mCost;
5104}
5105
Austin Borgered99f642023-06-01 16:51:35 -07005106std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005107 return mConflicting;
5108}
5109
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005110SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5111 return mSystemCameraKind;
5112}
5113
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005114bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5115 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5116 != mPhysicalCameras.end();
5117}
5118
Austin Borgered99f642023-06-01 16:51:35 -07005119bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005120 Mutex::Autolock lock(mStatusLock);
5121 auto result = mUnavailablePhysicalIds.insert(physicalId);
5122 return result.second;
5123}
5124
Austin Borgered99f642023-06-01 16:51:35 -07005125bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005126 Mutex::Autolock lock(mStatusLock);
5127 auto count = mUnavailablePhysicalIds.erase(physicalId);
5128 return count > 0;
5129}
5130
Austin Borgered99f642023-06-01 16:51:35 -07005131void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005132 Mutex::Autolock lock(mStatusLock);
5133 mClientPackage = clientPackage;
5134}
5135
Austin Borgered99f642023-06-01 16:51:35 -07005136std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005137 Mutex::Autolock lock(mStatusLock);
5138 return mClientPackage;
5139}
5140
Ruben Brunkcc776712015-02-17 20:18:47 -08005141// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005142// ClientEventListener
5143// ----------------------------------------------------------------------------
5144
5145void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005146 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005147 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005148 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005149 if (basicClient.get() != nullptr) {
5150 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005151 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005152 static_cast<int>(basicClient->getClientUid()));
5153 }
5154}
5155
5156void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005157 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005158 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005159 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005160 if (basicClient.get() != nullptr) {
5161 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005162 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005163 static_cast<int>(basicClient->getClientUid()));
5164 }
5165}
5166
Ruben Brunk99e69712015-05-26 17:25:07 -07005167// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005168// CameraClientManager
5169// ----------------------------------------------------------------------------
5170
Ruben Brunk99e69712015-05-26 17:25:07 -07005171CameraService::CameraClientManager::CameraClientManager() {
5172 setListener(std::make_shared<ClientEventListener>());
5173}
5174
Ruben Brunkcc776712015-02-17 20:18:47 -08005175CameraService::CameraClientManager::~CameraClientManager() {}
5176
5177sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005178 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005179 auto descriptor = get(id);
5180 if (descriptor == nullptr) {
5181 return sp<BasicClient>{nullptr};
5182 }
5183 return descriptor->getValue();
5184}
5185
Austin Borgered99f642023-06-01 16:51:35 -07005186std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005187 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005188 std::ostringstream ret;
5189 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005190 bool hasAny = false;
5191 for (auto& i : all) {
5192 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005193 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005194 int32_t cost = i->getCost();
5195 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005196 int32_t score = i->getPriority().getScore();
5197 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005198 auto conflicting = i->getConflicting();
5199 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005200 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005201 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005202 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005203 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005204 uid_t clientUid = clientSp->getClientUid();
5205 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005206 }
Austin Borgered99f642023-06-01 16:51:35 -07005207 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5208 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005209
Ruben Brunk6267b532015-04-30 17:44:07 -07005210 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005211 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005212 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005213 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005214 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005215 }
5216
Austin Borgered99f642023-06-01 16:51:35 -07005217 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005218 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005219 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005220 }
Austin Borgered99f642023-06-01 16:51:35 -07005221 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005222 }
Austin Borgered99f642023-06-01 16:51:35 -07005223 if (hasAny) ret << "\n";
5224 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005225 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005226}
5227
5228CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005229 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5230 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005231 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005232
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005233 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005234 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005235
Austin Borgered99f642023-06-01 16:51:35 -07005236 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005237 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5238 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005239}
5240
5241CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005242 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005243 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005244 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005245 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005246 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5247 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005248}
5249
5250// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005251// InjectionStatusListener
5252// ----------------------------------------------------------------------------
5253
5254void CameraService::InjectionStatusListener::addListener(
5255 const sp<ICameraInjectionCallback>& callback) {
5256 Mutex::Autolock lock(mListenerLock);
5257 if (mCameraInjectionCallback) return;
5258 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5259 if (res == OK) {
5260 mCameraInjectionCallback = callback;
5261 }
5262}
5263
5264void CameraService::InjectionStatusListener::removeListener() {
5265 Mutex::Autolock lock(mListenerLock);
5266 if (mCameraInjectionCallback == nullptr) {
5267 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5268 return;
5269 }
5270 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5271 mCameraInjectionCallback = nullptr;
5272}
5273
5274void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005275 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005276 if (mCameraInjectionCallback == nullptr) {
5277 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5278 return;
5279 }
Cliff Wud3a05312021-04-26 23:07:31 +08005280
5281 switch (err) {
5282 case -ENODEV:
5283 mCameraInjectionCallback->onInjectionError(
5284 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5285 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005286 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005287 break;
5288 case -EBUSY:
5289 mCameraInjectionCallback->onInjectionError(
5290 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5291 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005292 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005293 break;
5294 case DEAD_OBJECT:
5295 mCameraInjectionCallback->onInjectionError(
5296 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5297 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005298 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005299 break;
5300 case INVALID_OPERATION:
5301 mCameraInjectionCallback->onInjectionError(
5302 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5303 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005304 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005305 break;
5306 case UNKNOWN_TRANSACTION:
5307 mCameraInjectionCallback->onInjectionError(
5308 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5309 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005310 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005311 break;
5312 default:
5313 mCameraInjectionCallback->onInjectionError(
5314 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5315 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005316 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005317 }
Cliff Wud8cae102021-03-11 01:37:42 +08005318}
5319
5320void CameraService::InjectionStatusListener::binderDied(
5321 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005322 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5323 auto parent = mParent.promote();
5324 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005325 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5326 if (clientDescriptor != nullptr) {
5327 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5328 baseClientPtr->stopInjection();
5329 }
Cliff Wu3b268182021-07-06 15:44:43 +08005330 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005331 }
5332}
5333
5334// ----------------------------------------------------------------------------
5335// CameraInjectionSession
5336// ----------------------------------------------------------------------------
5337
5338binder::Status CameraService::CameraInjectionSession::stopInjection() {
5339 Mutex::Autolock lock(mInjectionSessionLock);
5340 auto parent = mParent.promote();
5341 if (parent == nullptr) {
5342 ALOGE("CameraInjectionSession: Parent is gone");
5343 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5344 "Camera service encountered error");
5345 }
Cliff Wud3a05312021-04-26 23:07:31 +08005346
5347 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005348 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5349 if (clientDescriptor != nullptr) {
5350 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5351 res = baseClientPtr->stopInjection();
5352 if (res != OK) {
5353 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5354 " ret != NO_ERROR: %d", res);
5355 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5356 "Camera session encountered error");
5357 }
5358 }
Cliff Wu3b268182021-07-06 15:44:43 +08005359 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005360 return binder::Status::ok();
5361}
5362
5363// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005364
5365static const int kDumpLockRetries = 50;
5366static const int kDumpLockSleep = 60000;
5367
5368static bool tryLock(Mutex& mutex)
5369{
5370 bool locked = false;
5371 for (int i = 0; i < kDumpLockRetries; ++i) {
5372 if (mutex.tryLock() == NO_ERROR) {
5373 locked = true;
5374 break;
5375 }
5376 usleep(kDumpLockSleep);
5377 }
5378 return locked;
5379}
5380
Rucha Katakwardf223072021-06-15 10:21:00 -07005381void CameraService::cacheDump() {
5382 if (mMemFd != -1) {
5383 const Vector<String16> args;
5384 ATRACE_CALL();
5385 // Acquiring service lock here will avoid the deadlock since
5386 // cacheDump will not be called during the second disconnect.
5387 Mutex::Autolock lock(mServiceLock);
5388
5389 Mutex::Autolock l(mCameraStatesLock);
5390 // Start collecting the info for open sessions and store it in temp file.
5391 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005392 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005393 auto clientDescriptor = mActiveClientManager.get(cameraId);
5394 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005395 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005396 // Log the current open session info before device is disconnected.
5397 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5398 }
5399 }
5400 }
5401}
5402
Mathias Agopian65ab4712010-07-14 17:59:35 -07005403status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005404 ATRACE_CALL();
5405
Austin Borgered99f642023-06-01 16:51:35 -07005406 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005407 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005408 getCallingPid(),
5409 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005410 return NO_ERROR;
5411 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005412 bool locked = tryLock(mServiceLock);
5413 // failed to lock - CameraService is probably deadlocked
5414 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005415 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005416 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005417
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005418 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005419 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005420
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005421 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005422 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005423
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005424 if (locked) mServiceLock.unlock();
5425 return NO_ERROR;
5426 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005427 dprintf(fd, "\n== Service global info: ==\n\n");
5428 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005429 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005430 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5431 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005432 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5433 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5434 }
Austin Borgered99f642023-06-01 16:51:35 -07005435 std::string activeClientString = mActiveClientManager.toString();
5436 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5437 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005438 if (mStreamUseCaseOverrides.size() > 0) {
5439 dprintf(fd, "Active stream use case overrides:");
5440 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5441 dprintf(fd, " %" PRId64, useCaseOverride);
5442 }
5443 dprintf(fd, "\n");
5444 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005445
5446 dumpEventLog(fd);
5447
5448 bool stateLocked = tryLock(mCameraStatesLock);
5449 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005450 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005451 }
5452
Emilian Peevbd8c5032018-02-14 23:05:40 +00005453 int argSize = args.size();
5454 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005455 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005456 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005457 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005458 }
5459 break;
5460 }
5461 }
5462
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005463 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005464 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005465
Austin Borgered99f642023-06-01 16:51:35 -07005466 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005467
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005468 CameraParameters p = state.second->getShimParams();
5469 if (!p.isEmpty()) {
5470 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5471 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005472 }
5473
5474 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005475 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005476 // log the current open session info
5477 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005478 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005479 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005480 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005481
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005482 }
5483
5484 if (stateLocked) mCameraStatesLock.unlock();
5485
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005486 if (locked) mServiceLock.unlock();
5487
Emilian Peevf53f66e2017-04-11 14:29:43 +01005488 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005489
5490 dprintf(fd, "\n== Vendor tags: ==\n\n");
5491
5492 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5493 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005494 sp<VendorTagDescriptorCache> cache =
5495 VendorTagDescriptorCache::getGlobalVendorTagCache();
5496 if (cache == NULL) {
5497 dprintf(fd, "No vendor tags.\n");
5498 } else {
5499 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5500 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005501 } else {
5502 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5503 }
5504
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005505 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005506 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005507 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005508
5509 // Process dump arguments, if any
5510 int n = args.size();
5511 String16 verboseOption("-v");
5512 String16 unreachableOption("--unreachable");
5513 for (int i = 0; i < n; i++) {
5514 if (args[i] == verboseOption) {
5515 // change logging level
5516 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005517 std::string levelStr = toStdString(args[i+1]);
5518 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005519 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005520 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005521 } else if (args[i] == unreachableOption) {
5522 // Dump memory analysis
5523 // TODO - should limit be an argument parameter?
5524 UnreachableMemoryInfo info;
5525 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5526 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005527 dprintf(fd, "\n== Unable to dump unreachable memory. "
5528 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005529 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005530 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005531 std::string s = info.ToString(/*log_contents*/ true);
5532 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005533 }
5534 }
5535 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005536
5537 bool serviceLocked = tryLock(mServiceLock);
5538
5539 // Dump info from previous open sessions.
5540 // Reposition the offset to beginning of the file before reading
5541
5542 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5543 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5544 ssize_t size_read;
5545 char buf[4096];
5546 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5547 // Read data from file to a small buffer and write it to fd.
5548 write(fd, buf, size_read);
5549 if (size_read == -1) {
5550 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5551 break;
5552 }
5553 }
5554 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5555 } else {
5556 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5557 }
5558
5559 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005560 return NO_ERROR;
5561}
5562
Rucha Katakwardf223072021-06-15 10:21:00 -07005563void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005564 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005565 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005566 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005567 getFormattedCurrentTime().c_str(),
5568 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005569 dprintf(fd, " Client priority score: %d state: %d\n",
5570 clientDescriptor->getPriority().getScore(),
5571 clientDescriptor->getPriority().getState());
5572 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5573
5574 auto client = clientDescriptor->getValue();
5575 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005576 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005577
5578 client->dumpClient(fd, args);
5579}
5580
Austin Borgered99f642023-06-01 16:51:35 -07005581void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005582 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005583 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005584}
5585
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005586void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005587 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005588
5589 Mutex::Autolock l(mLogLock);
5590 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005591 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005592 }
5593
5594 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005595 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005596 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005597 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005598 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005599 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005600}
5601
Austin Borgered99f642023-06-01 16:51:35 -07005602void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005603 Mutex::Autolock lock(mLogLock);
5604 if (!isClientWatchedLocked(client)) { return; }
5605
5606 std::vector<std::string> dumpVector;
5607 client->dumpWatchedEventsToVector(dumpVector);
5608
5609 if (dumpVector.empty()) { return; }
5610
Austin Borgered99f642023-06-01 16:51:35 -07005611 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005612
Austin Borgered99f642023-06-01 16:51:35 -07005613 std::string currentTime = getFormattedCurrentTime();
5614 dumpString << "Cached @ ";
5615 dumpString << currentTime;
5616 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005617
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005618 size_t i = dumpVector.size();
5619
5620 // Store the string in reverse order (latest last)
5621 while (i > 0) {
5622 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005623 dumpString << cameraId;
5624 dumpString << ":";
5625 dumpString << client->getPackageName();
5626 dumpString << " ";
5627 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005628 }
5629
Austin Borgered99f642023-06-01 16:51:35 -07005630 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005631}
5632
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005633void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005634 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005635 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5636 if (mTorchClientMap[i] == who) {
5637 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005638 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005639 status_t res = mFlashlight->setTorchMode(cameraId, false);
5640 if (res) {
5641 ALOGE("%s: torch client died but couldn't turn off torch: "
5642 "%s (%d)", __FUNCTION__, strerror(-res), res);
5643 return;
5644 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005645 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005646 break;
5647 }
5648 }
5649}
5650
Ruben Brunkcc776712015-02-17 20:18:47 -08005651/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005652
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005653 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005654 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5655 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005656 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005657 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005658 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005659
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005660 // check torch client
5661 handleTorchClientBinderDied(who);
5662
5663 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005664 if(!evictClientIdByRemote(who)) {
5665 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005666 return;
5667 }
5668
Ruben Brunkcc776712015-02-17 20:18:47 -08005669 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5670 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005671}
5672
Austin Borgered99f642023-06-01 16:51:35 -07005673void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005674 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005675}
5676
Austin Borgered99f642023-06-01 16:51:35 -07005677void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005678 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005679 // Do not lock mServiceLock here or can get into a deadlock from
5680 // connect() -> disconnect -> updateStatus
5681
5682 auto state = getCameraState(cameraId);
5683
5684 if (state == nullptr) {
5685 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005686 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005687 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005688 }
5689
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005690 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5691 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5692 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005693 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005694 return;
5695 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005696
Biswarup Pal37a75182024-01-16 15:53:35 +00005697 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5698 CameraMetadata cameraInfo;
5699 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005700 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005701 if (res != OK) {
5702 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5703 __FUNCTION__, cameraId.c_str());
5704 } else {
5705 int32_t deviceId = getDeviceId(cameraInfo);
5706 if (deviceId != kDefaultDeviceId) {
5707 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5708 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5709 static_cast<camera_metadata_enum_android_lens_facing_t>(
5710 lensFacingEntry.data.u8[0]);
5711 std::string mappedCameraId;
5712 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5713 mappedCameraId = kVirtualDeviceBackCameraId;
5714 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5715 mappedCameraId = kVirtualDeviceFrontCameraId;
5716 } else {
5717 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5718 __func__);
5719 }
5720 if (!mappedCameraId.empty()) {
5721 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5722 }
5723 }
5724 }
5725 }
5726
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005727 // Collect the logical cameras without holding mStatusLock in updateStatus
5728 // as that can lead to a deadlock(b/162192331).
5729 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005730 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005731 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005732 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005733 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005734 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005735 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5736 auto [deviceId, mappedCameraId] =
5737 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005738
Biswarup Pal37a75182024-01-16 15:53:35 +00005739 if (status != StatusInternal::ENUMERATING) {
5740 // Update torch status if it has a flash unit.
5741 Mutex::Autolock al(mTorchStatusMutex);
5742 TorchModeStatus torchStatus;
5743 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5744 NAME_NOT_FOUND) {
5745 TorchModeStatus newTorchStatus =
5746 status == StatusInternal::PRESENT ?
5747 TorchModeStatus::AVAILABLE_OFF :
5748 TorchModeStatus::NOT_AVAILABLE;
5749 if (torchStatus != newTorchStatus) {
5750 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5751 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005752 }
5753 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005754
Biswarup Pal37a75182024-01-16 15:53:35 +00005755 Mutex::Autolock lock(mStatusListenerLock);
5756 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5757 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005758
Biswarup Pal37a75182024-01-16 15:53:35 +00005759 for (auto& listener : mListenerList) {
5760 bool isVendorListener = listener->isVendorListener();
5761 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5762 listener->getListenerPid(), listener->getListenerUid())) {
5763 ALOGV("Skipping discovery callback for system-only camera device %s",
5764 cameraId.c_str());
5765 continue;
5766 }
5767
5768 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5769 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005770 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005771 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005772 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5773 ret.exceptionCode());
5774 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005775 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005776}
5777
Austin Borgered99f642023-06-01 16:51:35 -07005778void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5779 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005780 auto state = getCameraState(cameraId);
5781 if (state == nullptr) {
5782 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005783 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005784 return;
5785 }
5786 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005787 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005788 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005789 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005790 }
5791
Biswarup Pal37a75182024-01-16 15:53:35 +00005792 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5793 auto [deviceId, mappedCameraId] =
5794 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5795
Shuzhen Wang695044d2020-03-06 09:02:23 -08005796 Mutex::Autolock lock(mStatusListenerLock);
5797
5798 for (const auto& it : mListenerList) {
5799 if (!it->isOpenCloseCallbackAllowed()) {
5800 continue;
5801 }
5802
5803 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005804 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005805 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5806 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005807 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005808 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005809 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005810
5811 it->handleBinderStatus(ret,
5812 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5813 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005814 }
5815}
5816
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005817template<class Func>
5818void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005819 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005820 std::initializer_list<StatusInternal> rejectSourceStates,
5821 Func onStatusUpdatedLocked) {
5822 Mutex::Autolock lock(mStatusLock);
5823 StatusInternal oldStatus = mStatus;
5824 mStatus = status;
5825
5826 if (oldStatus == status) {
5827 return;
5828 }
5829
5830 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005831 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005832
5833 if (oldStatus == StatusInternal::NOT_PRESENT &&
5834 (status != StatusInternal::PRESENT &&
5835 status != StatusInternal::ENUMERATING)) {
5836
5837 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5838 __FUNCTION__);
5839 mStatus = oldStatus;
5840 return;
5841 }
5842
5843 /**
5844 * Sometimes we want to conditionally do a transition.
5845 * For example if a client disconnects, we want to go to PRESENT
5846 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5847 */
5848 for (auto& rejectStatus : rejectSourceStates) {
5849 if (oldStatus == rejectStatus) {
5850 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005851 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005852 mStatus = oldStatus;
5853 return;
5854 }
5855 }
5856
5857 onStatusUpdatedLocked(cameraId, status);
5858}
5859
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005860status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005861 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005862 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005863 if (!status) {
5864 return BAD_VALUE;
5865 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005866 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5867 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005868 // invalid camera ID or the camera doesn't have a flash unit
5869 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005870 }
5871
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005872 *status = mTorchStatusMap.valueAt(index);
5873 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005874}
5875
Austin Borgered99f642023-06-01 16:51:35 -07005876status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005877 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005878 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5879 if (index == NAME_NOT_FOUND) {
5880 return BAD_VALUE;
5881 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005882 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005883
5884 return OK;
5885}
5886
Austin Borgered99f642023-06-01 16:51:35 -07005887std::list<std::string> CameraService::getLogicalCameras(
5888 const std::string& physicalCameraId) {
5889 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005890 Mutex::Autolock lock(mCameraStatesLock);
5891 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005892 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5893 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005894 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005895 }
5896 return retList;
5897}
5898
5899void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005900 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005901 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005902 // mStatusListenerLock is expected to be locked
5903 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005904 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005905 // Note: we check only the deviceKind of the physical camera id
5906 // since, logical camera ids and their physical camera ids are
5907 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005908 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5909 listener->getListenerPid(), listener->getListenerUid())) {
5910 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005911 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005912 continue;
5913 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005914 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005915 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005916 listener->handleBinderStatus(ret,
5917 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5918 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5919 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005920 }
5921 }
5922}
5923
Svet Ganova453d0d2018-01-11 15:37:58 -08005924void CameraService::blockClientsForUid(uid_t uid) {
5925 const auto clients = mActiveClientManager.getAll();
5926 for (auto& current : clients) {
5927 if (current != nullptr) {
5928 const auto basicClient = current->getValue();
5929 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5930 basicClient->block();
5931 }
5932 }
5933 }
5934}
5935
Michael Grooverd1d435a2018-12-18 17:39:42 -08005936void CameraService::blockAllClients() {
5937 const auto clients = mActiveClientManager.getAll();
5938 for (auto& current : clients) {
5939 if (current != nullptr) {
5940 const auto basicClient = current->getValue();
5941 if (basicClient.get() != nullptr) {
5942 basicClient->block();
5943 }
5944 }
5945 }
5946}
5947
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005948void CameraService::blockPrivacyEnabledClients() {
5949 const auto clients = mActiveClientManager.getAll();
5950 for (auto& current : clients) {
5951 if (current != nullptr) {
5952 const auto basicClient = current->getValue();
5953 if (basicClient.get() != nullptr) {
5954 std::string pkgName = basicClient->getPackageName();
5955 bool cameraPrivacyEnabled =
5956 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5957 if (cameraPrivacyEnabled) {
5958 basicClient->block();
5959 }
5960 }
5961 }
5962 }
5963}
5964
Svet Ganova453d0d2018-01-11 15:37:58 -08005965// NOTE: This is a remote API - make sure all args are validated
5966status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005967 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005968 return PERMISSION_DENIED;
5969 }
5970 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5971 return BAD_VALUE;
5972 }
Austin Borgered99f642023-06-01 16:51:35 -07005973 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005974 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005975 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005976 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005977 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005978 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005979 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005980 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005981 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005982 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005983 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005984 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005985 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005986 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005987 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005988 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005989 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005990 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005991 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005992 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005993 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005994 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005995 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005996 handleClearStreamUseCaseOverrides();
5997 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005998 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005999 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006000 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006001 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006002 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006003 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006004 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006005 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006006 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006007 }
6008 printHelp(err);
6009 return BAD_VALUE;
6010}
6011
6012status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006013 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006014
Svet Ganova453d0d2018-01-11 15:37:58 -08006015 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006016 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006017 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006018 } else if ((args[2] != toString16("idle"))) {
6019 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006020 return BAD_VALUE;
6021 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006022
6023 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006024 if (args.size() >= 5 && args[3] == toString16("--user")) {
6025 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006026 }
6027
6028 uid_t uid;
6029 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6030 return BAD_VALUE;
6031 }
6032
6033 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006034 return NO_ERROR;
6035}
6036
6037status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006038 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006039
6040 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006041 if (args.size() >= 4 && args[2] == toString16("--user")) {
6042 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006043 }
6044
6045 uid_t uid;
6046 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006047 return BAD_VALUE;
6048 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006049
6050 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006051 return NO_ERROR;
6052}
6053
6054status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006055 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006056
6057 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006058 if (args.size() >= 4 && args[2] == toString16("--user")) {
6059 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006060 }
6061
6062 uid_t uid;
6063 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006064 return BAD_VALUE;
6065 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006066
6067 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006068 return dprintf(out, "active\n");
6069 } else {
6070 return dprintf(out, "idle\n");
6071 }
6072}
6073
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006074status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006075 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006076 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6077 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6078 Mutex::Autolock lock(mServiceLock);
6079
6080 mOverrideRotateAndCropMode = rotateValue;
6081
6082 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6083
6084 const auto clients = mActiveClientManager.getAll();
6085 for (auto& current : clients) {
6086 if (current != nullptr) {
6087 const auto basicClient = current->getValue();
6088 if (basicClient.get() != nullptr) {
6089 basicClient->setRotateAndCropOverride(rotateValue);
6090 }
6091 }
6092 }
6093
6094 return OK;
6095}
6096
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006097status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6098 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006099 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006100 if ((*end != '\0') ||
6101 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6102 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6103 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6104 return BAD_VALUE;
6105 }
6106
6107 Mutex::Autolock lock(mServiceLock);
6108 mOverrideAutoframingMode = autoframingValue;
6109
6110 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6111
6112 const auto clients = mActiveClientManager.getAll();
6113 for (auto& current : clients) {
6114 if (current != nullptr) {
6115 const auto basicClient = current->getValue();
6116 if (basicClient.get() != nullptr) {
6117 basicClient->setAutoframingOverride(autoframingValue);
6118 }
6119 }
6120 }
6121
6122 return OK;
6123}
6124
Ravneetaeb20dc2022-03-30 05:33:03 +00006125status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006126 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006127
6128 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6129
6130 Mutex::Autolock lock(mServiceLock);
6131
6132 mCameraServiceWatchdogEnabled = enableWatchdog;
6133
6134 const auto clients = mActiveClientManager.getAll();
6135 for (auto& current : clients) {
6136 if (current != nullptr) {
6137 const auto basicClient = current->getValue();
6138 if (basicClient.get() != nullptr) {
6139 basicClient->setCameraServiceWatchdog(enableWatchdog);
6140 }
6141 }
6142 }
6143
6144 return OK;
6145}
6146
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006147status_t CameraService::handleGetRotateAndCrop(int out) {
6148 Mutex::Autolock lock(mServiceLock);
6149
6150 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6151}
6152
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006153status_t CameraService::handleGetAutoframing(int out) {
6154 Mutex::Autolock lock(mServiceLock);
6155
6156 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6157}
6158
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006159status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6160 char *endPtr;
6161 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006162 std::string maskString = toStdString(args[1]);
6163 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006164
6165 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006166 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006167 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6168
6169 Mutex::Autolock lock(mServiceLock);
6170
6171 mImageDumpMask = maskValue;
6172
6173 return OK;
6174}
6175
6176status_t CameraService::handleGetImageDumpMask(int out) {
6177 Mutex::Autolock lock(mServiceLock);
6178
6179 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6180}
6181
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006182status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006183 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006184 if (errno != 0) return BAD_VALUE;
6185
6186 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6187 Mutex::Autolock lock(mServiceLock);
6188
6189 mOverrideCameraMuteMode = (muteValue == 1);
6190
6191 const auto clients = mActiveClientManager.getAll();
6192 for (auto& current : clients) {
6193 if (current != nullptr) {
6194 const auto basicClient = current->getValue();
6195 if (basicClient.get() != nullptr) {
6196 if (basicClient->supportsCameraMute()) {
6197 basicClient->setCameraMute(mOverrideCameraMuteMode);
6198 }
6199 }
6200 }
6201 }
6202
6203 return OK;
6204}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006205
Shuzhen Wang16610a62022-12-15 22:38:07 -08006206status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6207 std::vector<int64_t> useCasesOverride;
6208 for (size_t i = 1; i < args.size(); i++) {
6209 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006210 std::string arg = toStdString(args[i]);
6211 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006212 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006213 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006214 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006215 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006216 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006217 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006218 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006219 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006220 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006221 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006222 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006223 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006224 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6225 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006226 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006227 return BAD_VALUE;
6228 }
6229 useCasesOverride.push_back(useCase);
6230 }
6231
6232 Mutex::Autolock lock(mServiceLock);
6233 mStreamUseCaseOverrides = std::move(useCasesOverride);
6234
6235 return OK;
6236}
6237
6238void CameraService::handleClearStreamUseCaseOverrides() {
6239 Mutex::Autolock lock(mServiceLock);
6240 mStreamUseCaseOverrides.clear();
6241}
6242
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006243status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6244 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006245 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006246 if ((*end != '\0') ||
6247 (zoomOverrideValue != -1 &&
6248 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6249 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6250 return BAD_VALUE;
6251 }
6252
6253 Mutex::Autolock lock(mServiceLock);
6254 mZoomOverrideValue = zoomOverrideValue;
6255
6256 const auto clients = mActiveClientManager.getAll();
6257 for (auto& current : clients) {
6258 if (current != nullptr) {
6259 const auto basicClient = current->getValue();
6260 if (basicClient.get() != nullptr) {
6261 if (basicClient->supportsZoomOverride()) {
6262 basicClient->setZoomOverride(mZoomOverrideValue);
6263 }
6264 }
6265 }
6266 }
6267
6268 return OK;
6269}
6270
Avichal Rakesh84147132021-11-11 17:47:11 -08006271status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006272 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006273 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006274 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006275 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006276 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006277 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006278 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006279 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006280 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006281 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006282 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006283 dprintf(outFd, "Camera service watch commands:\n"
6284 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6285 " starts watching the provided tags for clients with provided package\n"
6286 " recognizes tag shorthands like '3a'\n"
6287 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006288 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006289 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006290 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006291 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006292 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006293 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006294 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006295}
6296
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006297status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6298 Mutex::Autolock lock(mLogLock);
6299 size_t tagsIdx; // index of '-m'
6300 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006301 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006302 if (tagsIdx < args.size() - 1) {
6303 tags = args[tagsIdx + 1];
6304 } else {
6305 dprintf(outFd, "No tags provided.\n");
6306 return BAD_VALUE;
6307 }
6308
6309 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006310 // watch all clients if no clients are provided
6311 String16 clients = toString16(kWatchAllClientsFlag);
6312 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006313 clientsIdx++);
6314 if (clientsIdx < args.size() - 1) {
6315 clients = args[clientsIdx + 1];
6316 }
Austin Borgered99f642023-06-01 16:51:35 -07006317 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006318
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006319 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006320 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006321
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006322 bool serviceLock = tryLock(mServiceLock);
6323 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006324 auto cameraClients = mActiveClientManager.getAll();
6325 for (const auto &clientDescriptor: cameraClients) {
6326 if (clientDescriptor == nullptr) { continue; }
6327 sp<BasicClient> client = clientDescriptor->getValue();
6328 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006329
6330 if (isClientWatchedLocked(client.get())) {
6331 client->startWatchingTags(mMonitorTags, outFd);
6332 numWatchedClients++;
6333 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006334 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006335 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6336
6337 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006338 return OK;
6339}
6340
6341status_t CameraService::stopWatchingTags(int outFd) {
6342 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006343 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006344 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006345
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006346 mWatchedClientPackages.clear();
6347 mWatchedClientsDumpCache.clear();
6348
6349 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006350 auto cameraClients = mActiveClientManager.getAll();
6351 for (const auto &clientDescriptor : cameraClients) {
6352 if (clientDescriptor == nullptr) { continue; }
6353 sp<BasicClient> client = clientDescriptor->getValue();
6354 if (client.get() == nullptr) { continue; }
6355 client->stopWatchingTags(outFd);
6356 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006357 dprintf(outFd, "Stopped watching all clients.\n");
6358 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006359 return OK;
6360}
6361
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006362status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6363 Mutex::Autolock lock(mLogLock);
6364 size_t clearedSize = mWatchedClientsDumpCache.size();
6365 mWatchedClientsDumpCache.clear();
6366 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6367 return OK;
6368}
6369
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006370status_t CameraService::printWatchedTags(int outFd) {
6371 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006372 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006373
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006374 bool printedSomething = false; // tracks if any monitoring information was printed
6375 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006376
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006377 bool serviceLock = tryLock(mServiceLock);
6378 // get all watched clients that are currently connected
6379 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6380 if (clientDescriptor == nullptr) { continue; }
6381
6382 sp<BasicClient> client = clientDescriptor->getValue();
6383 if (client.get() == nullptr) { continue; }
6384 if (!isClientWatchedLocked(client.get())) { continue; }
6385
6386 std::vector<std::string> dumpVector;
6387 client->dumpWatchedEventsToVector(dumpVector);
6388
6389 size_t printIdx = dumpVector.size();
6390 if (printIdx == 0) {
6391 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006392 }
6393
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006394 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006395 const std::string &cameraId = clientDescriptor->getKey();
6396 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006397 while(printIdx > 0) {
6398 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006399 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006400 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006401 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006402 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006403 printedSomething = true;
6404
6405 connectedMonitoredClients.emplace(client->getPackageName());
6406 }
6407 if (serviceLock) { mServiceLock.unlock(); }
6408
6409 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6410 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006411 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006412 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6413 continue;
6414 }
6415
Austin Borgered99f642023-06-01 16:51:35 -07006416 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006417 dprintf(outFd, "%s\n", kv.second.c_str());
6418 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006419 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006420
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006421 if (!printedSomething) {
6422 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006423 }
6424
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006425 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006426}
6427
Avichal Rakesh84147132021-11-11 17:47:11 -08006428// Print all events in vector `events' that came after lastPrintedEvent
6429void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006430 const std::string &cameraId,
6431 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006432 const std::vector<std::string> &events,
6433 const std::string &lastPrintedEvent) {
6434 if (events.empty()) { return; }
6435
6436 // index of lastPrintedEvent in events.
6437 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6438 size_t lastPrintedIdx;
6439 for (lastPrintedIdx = 0;
6440 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6441 lastPrintedIdx++);
6442
6443 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6444
Avichal Rakesh84147132021-11-11 17:47:11 -08006445 // print events in chronological order (latest event last)
6446 size_t idxToPrint = lastPrintedIdx;
6447 do {
6448 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006449 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6450 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006451 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006452}
6453
6454// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6455// command should be interrupted if the user presses the return key, or if user loses any way to
6456// signal interrupt.
6457// If timeoutMs == 0, this function will always return false
6458bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6459 struct timeval startTime;
6460 int startTimeError = gettimeofday(&startTime, nullptr);
6461 if (startTimeError) {
6462 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6463 return true;
6464 }
6465
6466 const nfds_t numFds = 1;
6467 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6468
6469 struct timeval currTime;
6470 char buffer[2];
6471 while(true) {
6472 int currTimeError = gettimeofday(&currTime, nullptr);
6473 if (currTimeError) {
6474 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6475 return true;
6476 }
6477
6478 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6479 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6480 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6481
6482 if (remainingTimeMs <= 0) {
6483 // No user interrupt within timeoutMs, don't interrupt watch command
6484 return false;
6485 }
6486
6487 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6488 if (numFdsUpdated < 0) {
6489 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6490 return true;
6491 }
6492
6493 if (numFdsUpdated == 0) {
6494 // No user input within timeoutMs, don't interrupt watch command
6495 return false;
6496 }
6497
6498 if (!(pollFd.revents & POLLIN)) {
6499 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6500 return true;
6501 }
6502
6503 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6504 if (sizeRead < 0) {
6505 dprintf(outFd, "Error reading user input. Exiting.\n");
6506 return true;
6507 }
6508
6509 if (sizeRead == 0) {
6510 // Reached end of input fd (can happen if input is piped)
6511 // User has no way to signal an interrupt, so interrupt here
6512 return true;
6513 }
6514
6515 if (buffer[0] == '\n') {
6516 // User pressed return, interrupt watch command.
6517 return true;
6518 }
6519 }
6520}
6521
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006522status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6523 int inFd, int outFd) {
6524 // Figure out refresh interval, if present in args
6525 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006526 if (args.size() > 2) {
6527 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006528 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006529 intervalIdx++);
6530
6531 size_t intervalValIdx = intervalIdx + 1;
6532 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006533 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006534 if (errno) { return BAD_VALUE; }
6535 }
6536 }
6537
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006538 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6539 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006540
Avichal Rakesh84147132021-11-11 17:47:11 -08006541 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006542 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006543
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006544 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006545 bool serviceLock = tryLock(mServiceLock);
6546 auto cameraClients = mActiveClientManager.getAll();
6547 if (serviceLock) { mServiceLock.unlock(); }
6548
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006549 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006550 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006551 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006552
6553 sp<BasicClient> client = clientDescriptor->getValue();
6554 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006555 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006556
Austin Borgered99f642023-06-01 16:51:35 -07006557 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006558 // This also initializes the map entries with an empty string
6559 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6560
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006561 std::vector<std::string> latestEvents;
6562 client->dumpWatchedEventsToVector(latestEvents);
6563
6564 if (!latestEvents.empty()) {
6565 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006566 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006567 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006568 latestEvents,
6569 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006570 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006571 }
6572 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006573 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006574 break;
6575 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006576 }
6577 return OK;
6578}
6579
Austin Borgered99f642023-06-01 16:51:35 -07006580void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006581 mWatchedClientPackages.clear();
6582
Austin Borgered99f642023-06-01 16:51:35 -07006583 std::istringstream iss(clients);
6584 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006585
Austin Borgered99f642023-06-01 16:51:35 -07006586 while (std::getline(iss, nextClient, ',')) {
6587 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006588 // Don't need to track any other package if 'all' is present
6589 mWatchedClientPackages.clear();
6590 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6591 break;
6592 }
6593
6594 // track package names
6595 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006596 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006597}
6598
Svet Ganova453d0d2018-01-11 15:37:58 -08006599status_t CameraService::printHelp(int out) {
6600 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006601 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6602 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6603 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006604 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6605 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6606 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006607 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6608 " Valid values 0=false, 1=true, 2=auto\n"
6609 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006610 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6611 " Valid values 0=OFF, 1=ON for JPEG\n"
6612 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006613 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006614 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6615 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6616 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6617 " on. In case the number of usecases is smaller than the number of streams, the\n"
6618 " last use case is assigned to all the remaining streams. In case of multiple\n"
6619 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6620 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6621 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6622 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006623 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6624 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006625 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6626 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006627 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006628 " help print this message\n");
6629}
6630
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006631bool CameraService::isClientWatched(const BasicClient *client) {
6632 Mutex::Autolock lock(mLogLock);
6633 return isClientWatchedLocked(client);
6634}
6635
6636bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6637 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6638 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6639}
6640
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006641int32_t CameraService::updateAudioRestriction() {
6642 Mutex::Autolock lock(mServiceLock);
6643 return updateAudioRestrictionLocked();
6644}
6645
6646int32_t CameraService::updateAudioRestrictionLocked() {
6647 int32_t mode = 0;
6648 // iterate through all active client
6649 for (const auto& i : mActiveClientManager.getAll()) {
6650 const auto clientSp = i->getValue();
6651 mode |= clientSp->getAudioRestriction();
6652 }
6653
6654 bool modeChanged = (mAudioRestriction != mode);
6655 mAudioRestriction = mode;
6656 if (modeChanged) {
6657 mAppOps.setCameraAudioRestriction(mode);
6658 }
6659 return mode;
6660}
6661
Austin Borgered99f642023-06-01 16:51:35 -07006662status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006663 sp<BasicClient> clientSp) {
6664 std::unique_ptr<AutoConditionLock> lock =
6665 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6666 status_t res = NO_ERROR;
6667 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006668 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006669 mInjectionStatusListener->notifyInjectionError(
6670 externalCamId, UNKNOWN_TRANSACTION);
6671 clientSp->notifyError(
6672 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6673 CaptureResultExtras());
6674
6675 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6676 // other clients from connecting in mServiceLockWrapper if held
6677 mServiceLock.unlock();
6678
6679 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006680 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006681 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006682 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006683
6684 // Reacquire mServiceLock
6685 mServiceLock.lock();
6686 }
6687
6688 return res;
6689}
6690
Cliff Wud3a05312021-04-26 23:07:31 +08006691void CameraService::clearInjectionParameters() {
6692 {
6693 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006694 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006695 mInjectionInternalCamId = "";
6696 }
6697 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006698 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006699}
6700
Biswarup Pal37a75182024-01-16 15:53:35 +00006701} // namespace android