blob: 17ec41e41234ddfbab9b53386d5af108e738c217 [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 }
108} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110namespace android {
111
Austin Borgerea931242021-12-13 23:10:41 +0000112using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700113using namespace camera3::SessionConfigurationUtils;
114
115using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000116using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700117using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700118using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800119using hardware::ICamera;
120using hardware::ICameraClient;
121using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800122using hardware::camera2::ICameraInjectionCallback;
123using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800124using hardware::camera2::utils::CameraIdAndSessionConfiguration;
125using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000126
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700127namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000128namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131// Logging support -- this is for debugging only
132// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700133volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Steve Blockb8a80522011-12-20 16:23:08 +0000135#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
136#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137
138static void setLogLevel(int level) {
139 android_atomic_write(level, &gLogLevel);
140}
141
Henri Chataingbcb99452023-11-01 17:40:30 +0000142int32_t format_as(CameraService::StatusInternal s) {
143 return fmt::underlying(s);
144}
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
Austin Borger249e6592024-03-10 22:28:11 -0700148// Permission strings (references to AttributionAndPermissionUtils for brevity)
149static const std::string &sDumpPermission =
150 AttributionAndPermissionUtils::sDumpPermission;
151static const std::string &sManageCameraPermission =
152 AttributionAndPermissionUtils::sManageCameraPermission;
153static const std::string &sCameraSendSystemEventsPermission =
154 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
155static const std::string &sCameraInjectExternalCameraPermission =
156 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
157
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000158// Constant integer for FGS Logging, used to denote the API type for logger
159static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700160const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800161static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
162static constexpr int32_t kSystemNativeClientState =
163 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700164static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700165
Austin Borgered99f642023-06-01 16:51:35 -0700166const std::string CameraService::kOfflineDevice("offline-");
167const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700168
Biswarup Pal7d072862024-04-17 15:24:47 +0000169constexpr int32_t kInvalidDeviceId = -1;
170
Rucha Katakward9ea6452021-05-06 11:57:16 -0700171// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700172static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700173
Austin Borger74fca042022-05-23 12:41:21 -0700174CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700175 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
176 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
177 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
178 std::make_shared<AttributionAndPermissionUtils>()\
179 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700180 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
181 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800182 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700184 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700185 mSoundRef(0), mInitialized(false),
186 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700188 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800189 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700190 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
191 if (mMemFd == -1) {
192 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
193 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700194}
195
Charles Chena7b613c2023-01-24 21:57:33 +0000196// Enable processes with isolated AID to request the binder
197void CameraService::instantiate() {
198 CameraService::publish(true);
199}
200
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800201void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700202 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800203 return;
204 }
205
206 ALOGV("appops service registered. setting camera audio restriction");
207 mAppOps.setCameraAudioRestriction(mAudioRestriction);
208}
209
Iliyan Malchev8951a972011-04-14 16:55:59 -0700210void CameraService::onFirstRef()
211{
Ruben Brunkcc776712015-02-17 20:18:47 -0800212 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800213
Iliyan Malchev8951a972011-04-14 16:55:59 -0700214 BnCameraService::onFirstRef();
215
Ruben Brunk99e69712015-05-26 17:25:07 -0700216 // Update battery life tracking if service is restarting
217 BatteryNotifier& notifier(BatteryNotifier::getInstance());
218 notifier.noteResetCamera();
219 notifier.noteResetFlashlight();
220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800222
Emilian Peevf53f66e2017-04-11 14:29:43 +0100223 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800224 if (res == OK) {
225 mInitialized = true;
226 }
227
Svet Ganova453d0d2018-01-11 15:37:58 -0800228 mUidPolicy = new UidPolicy(this);
229 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700230 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800231 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800232 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800233
234 // appops function setCamerAudioRestriction uses getService which
235 // is blocking till the appops service is ready. To enable early
236 // boot availability for cameraservice, use checkService which is
237 // non blocking and register for notifications
238 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700239 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800240 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700241 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800242 } else {
243 mAppOps.setCameraAudioRestriction(mAudioRestriction);
244 }
245
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700246 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
247 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000248 // Deprecated, so it will fail to register on newer devices
249 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700250 __FUNCTION__);
251 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700252
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700253 if (!AidlCameraService::registerService(this)) {
254 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
255 }
256
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 // This needs to be last call in this function, so that it's as close to
258 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700259 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700260 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261}
262
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800264 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100265
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000267 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 {
269 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271 if (nullptr == mCameraProviderManager.get()) {
272 mCameraProviderManager = new CameraProviderManager();
273 res = mCameraProviderManager->initialize(this);
274 if (res != OK) {
275 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
276 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700277 logServiceError("Unable to initialize camera provider manager",
278 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800279 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100280 }
281 }
282
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800283 // Setup vendor tags before we call get_camera_info the first time
284 // because HAL might need to setup static vendor keys in get_camera_info
285 // TODO: maybe put this into CameraProviderManager::initialize()?
286 mCameraProviderManager->setUpVendorTags();
287
288 if (nullptr == mFlashlight.get()) {
289 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700290 }
291
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292 res = mFlashlight->findFlashUnits();
293 if (res != OK) {
294 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
295 }
296
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800298 }
299
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800300 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700301 if (getCameraState(cameraId) == nullptr) {
302 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800303 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 if (unavailPhysicalIds.count(cameraId) > 0) {
305 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700306 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000307 }
308 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800309 }
310
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Derive primary rear/front cameras, and filter their charactierstics.
312 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700313 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700314 // Assume internal cameras are advertised from the same
315 // provider. If multiple providers are registered at different time,
316 // and each provider contains multiple internal color cameras, the current
317 // logic may filter the characteristics of more than one front/rear color
318 // cameras.
319 Mutex::Autolock l(mServiceLock);
320 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700321 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700322
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800323 return OK;
324}
325
Austin Borgered99f642023-06-01 16:51:35 -0700326void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700327 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000328 // Get the device id and app-visible camera id for the given HAL-visible camera id.
329 auto [deviceId, mappedCameraId] =
330 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
331
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800333 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700334 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
335 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000336 ALOGV("%s: Skipping torch callback for system-only camera device %s",
337 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700338 continue;
339 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000340
Austin Borgere8e2c422022-05-12 13:45:24 -0700341 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000342 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700343 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
344 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800345 }
346}
347
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800349 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800350 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800351 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800352 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700353}
354
Emilian Peevaee727d2017-05-04 16:35:48 +0100355void CameraService::onNewProviderRegistered() {
356 enumerateProviders();
357}
358
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700359void CameraService::filterAPI1SystemCameraLocked(
360 const std::vector<std::string> &normalDeviceIds) {
361 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000362 for (auto &cameraId : normalDeviceIds) {
363 if (vd_flags::camera_device_awareness()) {
364 CameraMetadata cameraInfo;
365 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000366 cameraId, false, &cameraInfo,
367 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000368 int32_t deviceId = kDefaultDeviceId;
369 if (res != OK) {
370 ALOGW("%s: Not able to get camera characteristics for camera id %s",
371 __FUNCTION__, cameraId.c_str());
372 } else {
373 deviceId = getDeviceId(cameraInfo);
374 }
375 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
376 // system cameras, so skip for non-default device id's.
377 if (deviceId != kDefaultDeviceId) {
378 continue;
379 }
380 }
381
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000383 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
384 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700385 continue;
386 }
387 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700388 // All system camera ids will necessarily come after public camera
389 // device ids as per the HAL interface contract.
390 break;
391 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000392 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 }
394 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
395 mNormalDeviceIdsWithoutSystemCamera.size());
396}
397
Austin Borgered99f642023-06-01 16:51:35 -0700398status_t CameraService::getSystemCameraKind(const std::string& cameraId,
399 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 auto state = getCameraState(cameraId);
401 if (state != nullptr) {
402 *kind = state->getSystemCameraKind();
403 return OK;
404 }
405 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700406 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700407}
408
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800409void CameraService::updateCameraNumAndIds() {
410 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700411 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
412 // Excludes hidden secure cameras
413 mNumberOfCameras =
414 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
415 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800416 mNormalDeviceIds =
417 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700418 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800419}
420
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700421void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422 // To claim to be S Performance primary cameras, the cameras must be
423 // backward compatible. So performance class primary camera Ids must be API1
424 // compatible.
425 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
426 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
427 int facing = -1;
428 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800429 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000430 getDeviceVersion(cameraId,
431 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
432 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700433 if (facing == -1) {
434 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
435 return;
436 }
437
438 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
439 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700440 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
441 if (res == OK) {
442 mPerfClassPrimaryCameraIds.insert(cameraId);
443 } else {
444 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
445 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
446 break;
447 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700448
449 if (facing == hardware::CAMERA_FACING_BACK) {
450 firstRearCameraSeen = true;
451 }
452 if (facing == hardware::CAMERA_FACING_FRONT) {
453 firstFrontCameraSeen = true;
454 }
455 }
456
457 if (firstRearCameraSeen && firstFrontCameraSeen) {
458 break;
459 }
460 }
461}
462
Austin Borgered99f642023-06-01 16:51:35 -0700463void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700464 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100465 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
466 if (res != OK) {
467 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
468 return;
469 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000470 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700471 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
472 if (res != OK) {
473 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
474 return;
475 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000476 std::vector<std::string> physicalCameraIds;
477 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700478 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700480 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100481 }
482
483 {
484 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700485 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000486 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100487 }
488
Austin Borgered99f642023-06-01 16:51:35 -0700489 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100490 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700491 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800492
Austin Borgered99f642023-06-01 16:51:35 -0700493 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100494 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800495
496 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700497 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498}
499
Austin Borgered99f642023-06-01 16:51:35 -0700500void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800501 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700502 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100503 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700504 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100505 }
506
507 {
508 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700509 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100510 }
511}
512
Austin Borgered99f642023-06-01 16:51:35 -0700513void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 CameraDeviceStatus newHalStatus) {
515 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700516 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 StatusInternal newStatus = mapToInternal(newHalStatus);
519
Austin Borgered99f642023-06-01 16:51:35 -0700520 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800521
522 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700523 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100524 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700525 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100526
527 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700528 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100529
Austin Borgered99f642023-06-01 16:51:35 -0700530 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700531 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700532 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700533 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700534 return;
535 }
536
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800539 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700540 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
541 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700542 return;
543 }
544
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000546 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
547 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800548 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
549 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700550 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000551 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800552
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800553 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700554 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800555 // Don't do this in updateStatus to avoid deadlock over mServiceLock
556 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700557
Ruben Brunkcc776712015-02-17 20:18:47 -0800558 // Remove cached shim parameters
559 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700560
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800561 // Remove online as well as offline client from the list of active clients,
562 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700563 clientToDisconnectOnline = removeClientLocked(cameraId);
564 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700565 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800566
Austin Borgered99f642023-06-01 16:51:35 -0700567 disconnectClient(cameraId, clientToDisconnectOnline);
568 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700569
Austin Borgered99f642023-06-01 16:51:35 -0700570 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800571 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800572 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000573 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
574 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700575 }
Austin Borgered99f642023-06-01 16:51:35 -0700576 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700577 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800578}
Igor Murashkincba2c162013-03-20 15:56:31 -0700579
Austin Borgered99f642023-06-01 16:51:35 -0700580void CameraService::onDeviceStatusChanged(const std::string& id,
581 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800582 CameraDeviceStatus newHalStatus) {
583 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700584 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800585
586 StatusInternal newStatus = mapToInternal(newHalStatus);
587
588 std::shared_ptr<CameraState> state = getCameraState(id);
589
590 if (state == nullptr) {
591 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700592 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800593 return;
594 }
595
596 StatusInternal logicalCameraStatus = state->getStatus();
597 if (logicalCameraStatus != StatusInternal::PRESENT &&
598 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
599 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700600 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800601 return;
602 }
603
604 bool updated = false;
605 if (newStatus == StatusInternal::PRESENT) {
606 updated = state->removeUnavailablePhysicalId(physicalId);
607 } else {
608 updated = state->addUnavailablePhysicalId(physicalId);
609 }
610
611 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700612 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800613 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000614 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800615 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000616 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800617 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700618 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
619 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
620 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700621 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700622 return;
623 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800624 Mutex::Autolock lock(mStatusListenerLock);
625 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700626 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
627 listener->getListenerPid(), listener->getListenerUid())) {
628 ALOGV("Skipping discovery callback for system-only camera device %s",
629 id.c_str());
630 continue;
631 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700632 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000633 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700634 listener->handleBinderStatus(ret,
635 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
636 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
637 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800638 }
639 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700640}
641
Austin Borgered99f642023-06-01 16:51:35 -0700642void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800643 if (clientToDisconnect.get() != nullptr) {
644 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700645 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800646 // Notify the client of disconnection
647 clientToDisconnect->notifyError(
648 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
649 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800650 clientToDisconnect->disconnect();
651 }
652}
653
Austin Borgered99f642023-06-01 16:51:35 -0700654void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800655 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700656 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
657 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
658 if (res != OK) {
659 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700660 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700661 return;
662 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800663 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700664 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800665}
666
Austin Borgered99f642023-06-01 16:51:35 -0700667void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700668 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
669 Mutex::Autolock al(mTorchStatusMutex);
670 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
671}
672
Austin Borgered99f642023-06-01 16:51:35 -0700673void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800674 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000675 // Get the device id and app-visible camera id for the given HAL-visible camera id.
676 auto [deviceId, mappedCameraId] =
677 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
678
Rucha Katakwar38284522021-11-10 11:25:21 -0800679 Mutex::Autolock lock(mStatusListenerLock);
680 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000681 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
682 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700683 i->handleBinderStatus(ret,
684 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
685 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800686 }
687}
688
Austin Borgered99f642023-06-01 16:51:35 -0700689void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700690 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800691 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700692 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800693
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800694 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800695 status_t res = getTorchStatusLocked(cameraId, &status);
696 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700697 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700698 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800699 return;
700 }
701 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800702 return;
703 }
704
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800705 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800707 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
708 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800709 return;
710 }
711
Ruben Brunkcc776712015-02-17 20:18:47 -0800712 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700713 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700714 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700715 auto iter = mTorchUidMap.find(cameraId);
716 if (iter != mTorchUidMap.end()) {
717 int oldUid = iter->second.second;
718 int newUid = iter->second.first;
719 BatteryNotifier& notifier(BatteryNotifier::getInstance());
720 if (oldUid != newUid) {
721 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800722 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700723 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700724 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800725 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700726 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700727 }
728 iter->second.second = newUid;
729 } else {
730 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800731 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700732 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700733 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700734 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700735 }
736 }
737 }
738 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700739 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800740}
741
Austin Borger249e6592024-03-10 22:28:11 -0700742bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700743 // Returns false if this is not an automotive device type.
744 if (!isAutomotiveDevice())
745 return false;
746
747 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700748 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700749 return false;
750
751 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
752 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
753 // This isn't a known camera ID, so it's not a system camera.
754 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
755 return false;
756 }
757
758 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
759 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
760 return false;
761 }
762
763 CameraMetadata cameraInfo;
764 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000765 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700766 if (res != OK){
767 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
768 cam_id.c_str());
769 return false;
770 }
771
772 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
773 if (auto_location.count != 1)
774 return false;
775
776 uint8_t location = auto_location.data.u8[0];
777 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
778 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
779 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
780 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
781 return false;
782 }
783
784 return true;
785}
786
Austin Borger65e64642024-06-11 15:58:23 -0700787Status CameraService::getNumberOfCameras(int32_t type,
788 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000789 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700790 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700791 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000792 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700793 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000794 return Status::ok();
795 }
796
Emilian Peevaee727d2017-05-04 16:35:48 +0100797 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700798 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800799 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
800 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700801 switch (type) {
802 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700803 if (hasSystemCameraPermissions) {
804 *numCameras = static_cast<int>(mNormalDeviceIds.size());
805 } else {
806 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
807 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800808 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700809 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700810 if (hasSystemCameraPermissions) {
811 *numCameras = mNumberOfCameras;
812 } else {
813 *numCameras = mNumberOfCamerasWithoutSystemCamera;
814 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800815 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700816 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800817 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700818 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
820 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700821 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823}
824
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700825Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700826 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700827 /* out */
828 hardware::camera2::impl::CameraMetadataNative* request) {
829 ATRACE_CALL();
830
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700831 if (!mInitialized) {
832 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
833 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
834 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
835 }
836
Austin Borger65e64642024-06-11 15:58:23 -0700837 std::optional<std::string> cameraIdOptional =
838 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000839 if (!cameraIdOptional.has_value()) {
840 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700841 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000842 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
843 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
844 }
845 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700846
847 binder::Status res;
848 if (request == nullptr) {
849 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
850 "Camera %s: Error creating default request", cameraId.c_str());
851 return res;
852 }
853 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
854 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
855 cameraId, templateId, &tempId);
856 if (!res.isOk()) {
857 ALOGE("%s: Camera %s: failed to map request Template %d",
858 __FUNCTION__, cameraId.c_str(), templateId);
859 return res;
860 }
861
862 if (shouldRejectSystemCameraConnection(cameraId)) {
863 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
864 "request for system only device %s: ", cameraId.c_str());
865 }
866
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700867 CameraMetadata metadata;
868 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
869 if (err == OK) {
870 request->swap(metadata);
871 } else if (err == BAD_VALUE) {
872 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
873 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
874 cameraId.c_str(), templateId, strerror(-err), err);
875 } else {
876 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
877 "Camera %s: Error creating default request for template %d: %s (%d)",
878 cameraId.c_str(), templateId, strerror(-err), err);
879 }
880 return res;
881}
882
883Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700884 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700885 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700886 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700887 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700888 ATRACE_CALL();
889
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700890 if (!mInitialized) {
891 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
892 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
893 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
894 }
895
Austin Borger65e64642024-06-11 15:58:23 -0700896 std::optional<std::string> cameraIdOptional =
897 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000898 if (!cameraIdOptional.has_value()) {
899 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700900 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000901 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
902 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
903 }
904 std::string cameraId = cameraIdOptional.value();
905
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700906 if (supported == nullptr) {
907 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
908 unresolvedCameraId.c_str());
909 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
910 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
911 }
912
913 if (shouldRejectSystemCameraConnection(cameraId)) {
914 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
915 "session configuration with parameters support for system only device %s: ",
916 cameraId.c_str());
917 }
918
Avichal Rakeshe005df52024-09-25 17:13:27 -0700919 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700920 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
921
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700922 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
923 sessionConfiguration, overrideForPerfClass, supported);
924 if (flags::analytics_24q3()) {
925 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
926 getCallingUid(), sessionConfiguration, ret);
927 }
928 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700929}
930
931Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
932 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
933 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700934 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700935 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
936 cameraId, sessionConfiguration, overrideForPerfClass,
937 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700938 binder::Status res;
939 switch (ret) {
940 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700941 // Expected. Do Nothing.
942 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700943 case INVALID_OPERATION: {
944 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700945 "Camera %s: Session configuration with parameters supported query not "
946 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700947 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700948 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
949 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
950 *supported = false;
951 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700952 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700953 break;
954 case NAME_NOT_FOUND: {
955 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
956 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
957 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
958 *supported = false;
959 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
960 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700961 break;
962 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700963 std::string msg = fmt::sprintf(
964 "Unable to retrieve session configuration support for camera "
965 "device %s: Error: %s (%d)",
966 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700967 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700968 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
969 *supported = false;
970 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700971 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700972 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974}
975
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800976Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000977 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700978 const SessionConfiguration& sessionConfiguration,
979 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000980 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800981 ATRACE_CALL();
982
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800983 if (outMetadata == nullptr) {
984 std::string msg =
985 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
986 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
987 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
988 }
989
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700990 if (!mInitialized) {
991 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
992 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
993 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
994 }
995
Austin Borger65e64642024-06-11 15:58:23 -0700996 std::optional<std::string> cameraIdOptional =
997 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000998 if (!cameraIdOptional.has_value()) {
999 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001000 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001001 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1002 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1003 }
1004 std::string cameraId = cameraIdOptional.value();
1005
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001006 if (shouldRejectSystemCameraConnection(cameraId)) {
1007 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1008 "Unable to retrieve camera"
1009 "characteristics for system only device %s: ",
1010 cameraId.c_str());
1011 }
1012
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001013 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1014 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesheb961c72024-09-25 17:26:26 -07001015
1016 bool sessionConfigSupported;
1017 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1018 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1019 if (!res.isOk()) {
1020 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1021 // report the correct Status to send to the client. Simply forward the error to
1022 // the client.
1023 outMetadata->clear();
1024 return res;
1025 }
1026
1027 if (!sessionConfigSupported) {
1028 std::string msg = fmt::sprintf("Session configuration not supported for camera device %s.",
1029 cameraId.c_str());
1030 outMetadata->clear();
1031 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001032 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001033
1034 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001035 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001036
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001037 switch (ret) {
1038 case OK:
1039 // Expected, no handling needed.
1040 break;
1041 case INVALID_OPERATION: {
1042 std::string msg = fmt::sprintf(
1043 "Camera %s: Session characteristics query not supported!",
1044 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001045 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001046 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1047 outMetadata->clear();
1048 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1049 }
1050 break;
1051 case NAME_NOT_FOUND: {
1052 std::string msg = fmt::sprintf(
1053 "Camera %s: Unknown camera ID.",
1054 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001055 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001056 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1057 outMetadata->clear();
1058 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001059 }
1060 break;
1061 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001062 std::string msg = fmt::sprintf(
1063 "Unable to retrieve session characteristics for camera device %s: "
1064 "Error: %s (%d)",
1065 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001066 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001067 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1068 outMetadata->clear();
1069 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001070 }
1071 }
1072
Avichal Rakesheb961c72024-09-25 17:26:26 -07001073 res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001074 if (flags::analytics_24q3()) {
1075 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1076 getCallingUid(), sessionConfiguration, res);
1077 }
1078 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001079}
1080
1081Status CameraService::filterSensitiveMetadataIfNeeded(
1082 const std::string& cameraId, CameraMetadata* metadata) {
1083 int callingPid = getCallingPid();
1084 int callingUid = getCallingUid();
1085
1086 if (callingPid == getpid()) {
1087 // Caller is cameraserver; no need to remove keys
1088 return Status::ok();
1089 }
1090
1091 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1092 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1093 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1094 metadata->clear();
1095 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1096 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1097 }
1098 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1099 // Attempting to query system only camera without system camera permission would have
1100 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1101 // for a system only camera, then the caller has the required permission.
1102 // No need to remove keys
1103 return Status::ok();
1104 }
1105
1106 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001107 // Get the device id that owns this camera.
1108 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1109 cameraId);
1110 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1111 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001112 if (hasCameraPermission) {
1113 // Caller has camera permission; no need to remove keys
1114 return Status::ok();
1115 }
1116
1117 status_t ret = metadata->removePermissionEntries(
1118 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1119 if (ret != OK) {
1120 metadata->clear();
1121 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1122 "Failed to remove camera characteristics needing camera permission "
1123 "for device %s:%s (%d)",
1124 cameraId.c_str(), strerror(-ret), ret);
1125 }
1126
1127 if (!tagsRemoved.empty()) {
1128 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1129 tagsRemoved.data(), tagsRemoved.size());
1130 if (ret != OK) {
1131 metadata->clear();
1132 return STATUS_ERROR_FMT(
1133 ERROR_INVALID_OPERATION,
1134 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1135 cameraId.c_str(), strerror(-ret), ret);
1136 }
1137 }
1138 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001139}
1140
malikakash22af94c2023-12-04 18:13:14 +00001141Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001142 const std::string& cameraId,
1143 const CameraMetadata& sessionParams) {
1144 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001145 const int pid = getCallingPid();
1146 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001147 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1148 __FUNCTION__, pid, uid);
1149 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1150 "Permission Denial: no permission to inject session params");
1151 }
1152
Biswarup Pal37a75182024-01-16 15:53:35 +00001153 // Do not allow session params injection for a virtual camera.
1154 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1155 if (deviceId != kDefaultDeviceId) {
1156 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1157 "Cannot inject session params for a virtual camera");
1158 }
1159
malikakash22af94c2023-12-04 18:13:14 +00001160 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1161 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1162
1163 auto clientDescriptor = mActiveClientManager.get(cameraId);
1164 if (clientDescriptor == nullptr) {
1165 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1166 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1167 "No active client for camera id %s", cameraId.c_str());
1168 }
1169
1170 sp<BasicClient> clientSp = clientDescriptor->getValue();
1171 status_t res = clientSp->injectSessionParams(sessionParams);
1172
1173 if (res != OK) {
1174 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1175 "Error injecting session params into camera \"%s\": %s (%d)",
1176 cameraId.c_str(), strerror(-res), res);
1177 }
1178 return Status::ok();
1179}
1180
Biswarup Pal37a75182024-01-16 15:53:35 +00001181std::optional<std::string> CameraService::resolveCameraId(
1182 const std::string& inputCameraId,
1183 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001184 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001185 if ((deviceId == kDefaultDeviceId)
1186 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1187 auto [storedDeviceId, _] =
1188 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1189 if (storedDeviceId != kDefaultDeviceId) {
1190 // Trying to access a virtual camera from default-policy device context, we should fail.
1191 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1192 inputCameraId.c_str(), deviceId);
1193 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1194 return std::nullopt;
1195 }
malikakash98260df2024-05-10 23:33:57 +00001196 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001197 }
1198
1199 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1200}
1201
Austin Borger65e64642024-06-11 15:58:23 -07001202Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1203 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1204 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001205 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001206 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001207 std::string cameraIdStr =
1208 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001209 if (cameraIdStr.empty()) {
1210 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001211 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001212 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1213 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1214 }
malikakashedb38962023-09-06 00:03:35 +00001215
Austin Borgered99f642023-06-01 16:51:35 -07001216 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001217 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1218 "characteristics for system only device %s: ", cameraIdStr.c_str());
1219 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001221 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001222 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001223 return STATUS_ERROR(ERROR_DISCONNECTED,
1224 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001225 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001226 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001227 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001228 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1229 if (hasSystemCameraPermissions) {
1230 cameraIdBound = mNumberOfCameras;
1231 }
1232 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001233 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1234 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001235 }
1236
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001237 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001238 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001239 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001240 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001241 if (err != OK) {
1242 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1243 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1244 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001245 logServiceError(std::string("Error retrieving camera info from device ")
1246 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001247 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001248
Ruben Brunkcc776712015-02-17 20:18:47 -08001249 return ret;
1250}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001251
Biswarup Pal37a75182024-01-16 15:53:35 +00001252std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1253 int32_t deviceId, int32_t devicePolicy) {
1254 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1255 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1256 std::optional<std::string> cameraIdOptional =
1257 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1258 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1259 }
1260
1261 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001262 auto callingPid = getCallingPid();
1263 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001264 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1265 callingPid, callingUid, /* checkCameraPermissions= */ false);
1266 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001267 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001268 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001269 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1270 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1271 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001272 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001273 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001274
malikakash98260df2024-05-10 23:33:57 +00001275 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001276}
1277
Biswarup Pal37a75182024-01-16 15:53:35 +00001278std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1279 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001280 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001281 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001282}
1283
Austin Borgered99f642023-06-01 16:51:35 -07001284Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001285 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1286 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001287 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001288
Zhijun He2b59be82013-09-25 10:14:30 -07001289 if (!cameraInfo) {
1290 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001291 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001292 }
1293
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001294 if (!mInitialized) {
1295 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001296 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001297 return STATUS_ERROR(ERROR_DISCONNECTED,
1298 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001299 }
1300
Austin Borger65e64642024-06-11 15:58:23 -07001301 std::optional<std::string> cameraIdOptional =
1302 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001303 if (!cameraIdOptional.has_value()) {
1304 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001305 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001306 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1307 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1308 }
1309 std::string cameraId = cameraIdOptional.value();
1310
Austin Borgered99f642023-06-01 16:51:35 -07001311 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001312 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001313 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001314 }
1315
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001316 bool overrideForPerfClass =
1317 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001318 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001319 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001320 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001321 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001322 if (res == NAME_NOT_FOUND) {
1323 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001324 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001325 strerror(-res), res);
1326 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001327 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1328 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001329 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001330 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001331 strerror(-res), res);
1332 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001333 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001334
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001335 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001336}
1337
Austin Borger65e64642024-06-11 15:58:23 -07001338Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1339 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001340 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001341 ATRACE_CALL();
1342 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001343
Austin Borger65e64642024-06-11 15:58:23 -07001344 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1345 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001346 if (!cameraIdOptional.has_value()) {
1347 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001348 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1350 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1351 }
1352 std::string cameraId = cameraIdOptional.value();
1353
Rucha Katakwar38284522021-11-10 11:25:21 -08001354 if (!mInitialized) {
1355 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1356 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1357 }
1358
Biswarup Pal37a75182024-01-16 15:53:35 +00001359 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001360 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1361 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1362 }
1363
Austin Borgered99f642023-06-01 16:51:35 -07001364 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001365 if (res != OK) {
1366 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001367 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001368 strerror(-res), res);
1369 }
1370 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1371 return Status::ok();
1372}
1373
Austin Borgered99f642023-06-01 16:51:35 -07001374std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001375 time_t now = time(nullptr);
1376 char formattedTime[64];
1377 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001378 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001379}
1380
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001381Status CameraService::getCameraVendorTagDescriptor(
1382 /*out*/
1383 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001384 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001385 if (!mInitialized) {
1386 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001387 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001388 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001389 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1390 if (globalDescriptor != nullptr) {
1391 *desc = *(globalDescriptor.get());
1392 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001393 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001394}
1395
Emilian Peev71c73a22017-03-21 16:35:51 +00001396Status CameraService::getCameraVendorTagCache(
1397 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1398 ATRACE_CALL();
1399 if (!mInitialized) {
1400 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1401 return STATUS_ERROR(ERROR_DISCONNECTED,
1402 "Camera subsystem not available");
1403 }
1404 sp<VendorTagDescriptorCache> globalCache =
1405 VendorTagDescriptorCache::getGlobalVendorTagCache();
1406 if (globalCache != nullptr) {
1407 *cache = *(globalCache.get());
1408 }
1409 return Status::ok();
1410}
1411
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001412void CameraService::clearCachedVariables() {
1413 BasicClient::BasicClient::sCameraService = nullptr;
1414}
1415
Austin Borgered99f642023-06-01 16:51:35 -07001416std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001417 int rotationOverride, int* portraitRotation, int* facing,
1418 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001419 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001420
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001421 int deviceVersion = 0;
1422
Emilian Peevf53f66e2017-04-11 14:29:43 +01001423 status_t res;
1424 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001425 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001426 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001427 if (res != OK || transport == IPCTransport::INVALID) {
1428 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001429 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001430 return std::make_pair(-1, IPCTransport::INVALID) ;
1431 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001432 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001433
Emilian Peevf53f66e2017-04-11 14:29:43 +01001434 hardware::CameraInfo info;
1435 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001436 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001437 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001438 if (res != OK) {
1439 return std::make_pair(-1, IPCTransport::INVALID);
1440 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001441 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001442 if (orientation) {
1443 *orientation = info.orientation;
1444 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001445 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001446
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001447 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001448}
1449
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001450Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001451 switch(err) {
1452 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001453 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001454 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001455 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1456 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001457 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458 return STATUS_ERROR(ERROR_DISCONNECTED,
1459 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001460 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1462 "Camera HAL encountered error %d: %s",
1463 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001464 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001465}
1466
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001468 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1469 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001470 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001471 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001472 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001473 bool forceSlowJpegMode, const std::string& originalCameraId,
1474 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001475 // For HIDL devices
1476 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1477 // Create CameraClient based on device version reported by the HAL.
1478 int deviceVersion = deviceVersionAndTransport.first;
1479 switch(deviceVersion) {
1480 case CAMERA_DEVICE_API_VERSION_1_0:
1481 ALOGE("Camera using old HAL version: %d", deviceVersion);
1482 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1483 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001484 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001485 break;
1486 case CAMERA_DEVICE_API_VERSION_3_0:
1487 case CAMERA_DEVICE_API_VERSION_3_1:
1488 case CAMERA_DEVICE_API_VERSION_3_2:
1489 case CAMERA_DEVICE_API_VERSION_3_3:
1490 case CAMERA_DEVICE_API_VERSION_3_4:
1491 case CAMERA_DEVICE_API_VERSION_3_5:
1492 case CAMERA_DEVICE_API_VERSION_3_6:
1493 case CAMERA_DEVICE_API_VERSION_3_7:
1494 break;
1495 default:
1496 // Should not be reachable
1497 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1498 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1499 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001500 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001501 }
1502 }
1503 if (effectiveApiLevel == API_1) { // Camera1 API route
1504 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001505 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001506 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001507 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001508 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001509 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001510 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1511 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001512 } else { // Camera2 API route
1513 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1514 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001515 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001516 cameraService->mCameraServiceProxyWrapper,
1517 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001518 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001519 overrideForPerfClass, rotationOverride, originalCameraId);
1520 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001521 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001522 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001523}
1524
Austin Borgered99f642023-06-01 16:51:35 -07001525std::string CameraService::toString(std::set<userid_t> intSet) {
1526 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001527 bool first = true;
1528 for (userid_t i : intSet) {
1529 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001530 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001531 first = false;
1532 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001533 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001534 }
1535 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001536 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001537}
1538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001539int32_t CameraService::mapToInterface(TorchModeStatus status) {
1540 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1541 switch (status) {
1542 case TorchModeStatus::NOT_AVAILABLE:
1543 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1544 break;
1545 case TorchModeStatus::AVAILABLE_OFF:
1546 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1547 break;
1548 case TorchModeStatus::AVAILABLE_ON:
1549 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1550 break;
1551 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001552 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001553 }
1554 return serviceStatus;
1555}
1556
1557CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1558 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1559 switch (status) {
1560 case CameraDeviceStatus::NOT_PRESENT:
1561 serviceStatus = StatusInternal::NOT_PRESENT;
1562 break;
1563 case CameraDeviceStatus::PRESENT:
1564 serviceStatus = StatusInternal::PRESENT;
1565 break;
1566 case CameraDeviceStatus::ENUMERATING:
1567 serviceStatus = StatusInternal::ENUMERATING;
1568 break;
1569 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001570 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001571 }
1572 return serviceStatus;
1573}
1574
1575int32_t CameraService::mapToInterface(StatusInternal status) {
1576 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1577 switch (status) {
1578 case StatusInternal::NOT_PRESENT:
1579 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1580 break;
1581 case StatusInternal::PRESENT:
1582 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1583 break;
1584 case StatusInternal::ENUMERATING:
1585 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1586 break;
1587 case StatusInternal::NOT_AVAILABLE:
1588 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1589 break;
1590 case StatusInternal::UNKNOWN:
1591 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1592 break;
1593 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001594 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001595 }
1596 return serviceStatus;
1597}
1598
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001599Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001600 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001601
Austin Borgered99f642023-06-01 16:51:35 -07001602 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001603 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001604 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001605
Austin Borgerb01a8702024-07-22 16:20:34 -07001606 int callingPid = getCallingPid();
1607 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001608
Austin Borger23694432024-10-07 19:28:01 -07001609 AttributionSourceState clientAttribution =
1610 buildAttributionSource(callingPid, uid, kServiceName, kDefaultDeviceId);
1611
1612 if (!(ret = connectHelper<ICameraClient, Client>(
1613 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId, clientAttribution,
1614 /*systemNativeClient*/ false, API_1, /*shimUpdateOnly*/ true,
1615 /*oomScoreOffset*/ 0,
1616 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1617 /*rotationOverride*/
1618 hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
1619 /*forceSlowJpegMode*/ false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp))
1620 .isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001621 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001622 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001623 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001624}
1625
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001627 /*out*/
1628 CameraParameters* parameters) {
1629
1630 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1631
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001633
1634 if (parameters == NULL) {
1635 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001636 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001637 }
1638
malikakash98260df2024-05-10 23:33:57 +00001639 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001640
1641 // Check if we already have parameters
1642 {
1643 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001644 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001645 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001646 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001647 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001648 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001649 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001650 }
1651 CameraParameters p = cameraState->getShimParams();
1652 if (!p.isEmpty()) {
1653 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001655 }
1656 }
1657
Austin Borger22c5c852024-03-08 13:31:36 -08001658 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001659 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001660 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001661 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001662 // Error already logged by callee
1663 return ret;
1664 }
1665
1666 // Check for parameters again
1667 {
1668 // Scope for service lock
1669 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001670 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001672 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001673 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001674 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001675 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001676 CameraParameters p = cameraState->getShimParams();
1677 if (!p.isEmpty()) {
1678 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001679 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001680 }
1681 }
1682
Ruben Brunkcc776712015-02-17 20:18:47 -08001683 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1684 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001685 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001686}
1687
Austin Borgered99f642023-06-01 16:51:35 -07001688Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borger23694432024-10-07 19:28:01 -07001689 const AttributionSourceState& clientAttribution) const {
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001690#ifdef __BRILLO__
Austin Borger23694432024-10-07 19:28:01 -07001691 UNUSED(clientAttribution);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001692#else
Austin Borger23694432024-10-07 19:28:01 -07001693 Status allowed = validateClientPermissionsLocked(cameraId, clientAttribution);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001694 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001695 return allowed;
1696 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001697#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001698
Austin Borger22c5c852024-03-08 13:31:36 -08001699 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001700
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001701 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001702 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1703 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001704 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001705 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001706 }
1707
Ruben Brunkcc776712015-02-17 20:18:47 -08001708 if (getCameraState(cameraId) == nullptr) {
1709 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001710 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001711 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001712 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001713 }
1714
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001715 status_t err = checkIfDeviceIsUsable(cameraId);
1716 if (err != NO_ERROR) {
1717 switch(err) {
1718 case -ENODEV:
1719 case -EBUSY:
1720 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001721 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001722 default:
1723 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001724 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001725 }
1726 }
1727 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001728}
1729
Austin Borger23694432024-10-07 19:28:01 -07001730Status CameraService::validateClientPermissionsLocked(
1731 const std::string& cameraId, const AttributionSourceState& clientAttribution) const {
Austin Borgerb01a8702024-07-22 16:20:34 -07001732 int callingPid = getCallingPid();
1733 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001734
Austin Borger23694432024-10-07 19:28:01 -07001735 int clientPid = clientAttribution.pid;
1736 int clientUid = clientAttribution.uid;
1737 const std::string clientName = clientAttribution.packageName.value_or(kUnknownPackageName);
1738
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001739 if (shouldRejectSystemCameraConnection(cameraId)) {
1740 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1741 cameraId.c_str());
1742 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001743 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001744 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001745 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1746 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001747 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001748 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001749 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001750 }
1751
Biswarup Pale506e732024-03-27 13:46:20 +00001752 // Get the device id that owns this camera.
1753 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Austin Borger23694432024-10-07 19:28:01 -07001754 AttributionSourceState clientAttributionWithDeviceId = clientAttribution;
1755 clientAttributionWithDeviceId.deviceId = deviceId;
Biswarup Pale506e732024-03-27 13:46:20 +00001756
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001757 // If it's not calling from cameraserver, check the permission if the
1758 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1759 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001760 bool checkPermissionForCamera =
Austin Borger23694432024-10-07 19:28:01 -07001761 hasPermissionsForCamera(cameraId, clientAttributionWithDeviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001762 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001763 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001764 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001765 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1766 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001767 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001768 }
1769
Svet Ganova453d0d2018-01-11 15:37:58 -08001770 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001771 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001772 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001773 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1774 clientPid, clientUid);
1775 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001776 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1777 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001778 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001779 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001780 }
1781
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001782 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1783 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1784 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1785 if ((!isAutomotivePrivilegedClient(callingUid) ||
1786 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1787 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001788 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1789 return STATUS_ERROR_FMT(ERROR_DISABLED,
1790 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001791 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001792 }
1793
Austin Borger6e831c42024-07-22 13:07:56 -07001794 userid_t clientUserId = multiuser_get_user_id(clientUid);
1795
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001796 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1797 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001798
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001799 // For non-system clients : Only allow clients who are being used by the current foreground
1800 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001801 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001802 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001803 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1804 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001805 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001806 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1807 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001808 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001809 }
1810
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001811 if (flags::camera_hsum_permission()) {
1812 // If the System User tries to access the camera when the device is running in
1813 // headless system user mode, ensure that client has the required permission
1814 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001815 if (isHeadlessSystemUserMode()
1816 && (clientUserId == USER_SYSTEM)
1817 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001818 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001819 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1820 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1821 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001822 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001823 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001824 }
1825
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001826 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001827}
1828
Austin Borgered99f642023-06-01 16:51:35 -07001829status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001830 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001831 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001832 if (cameraState == nullptr) {
1833 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001834 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001835 return -ENODEV;
1836 }
1837
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001838 StatusInternal currentStatus = cameraState->getStatus();
1839 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001840 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001841 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001842 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001843 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001844 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001845 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001846 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001847 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001848
Ruben Brunkcc776712015-02-17 20:18:47 -08001849 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001850}
1851
Ruben Brunkcc776712015-02-17 20:18:47 -08001852void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001853 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001854
Ruben Brunkcc776712015-02-17 20:18:47 -08001855 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001856 auto clientDescriptor =
1857 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001858 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001859 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1860
1861 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001862 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001863
1864 if (evicted.size() > 0) {
1865 // This should never happen - clients should already have been removed in disconnect
1866 for (auto& i : evicted) {
1867 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001868 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001869 }
1870
1871 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1872 __FUNCTION__);
1873 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001874
1875 // And register a death notification for the client callback. Do
1876 // this last to avoid Binder policy where a nested Binder
1877 // transaction might be pre-empted to service the client death
1878 // notification if the client process dies before linkToDeath is
1879 // invoked.
1880 sp<IBinder> remoteCallback = client->getRemote();
1881 if (remoteCallback != nullptr) {
1882 remoteCallback->linkToDeath(this);
1883 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001884}
1885
Austin Borgered99f642023-06-01 16:51:35 -07001886status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1887 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1888 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001889 /*out*/
1890 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001891 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001892 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001894 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001895 DescriptorPtr clientDescriptor;
1896 {
1897 if (effectiveApiLevel == API_1) {
1898 // If we are using API1, any existing client for this camera ID with the same remote
1899 // should be returned rather than evicted to allow MediaRecorder to work properly.
1900
1901 auto current = mActiveClientManager.get(cameraId);
1902 if (current != nullptr) {
1903 auto clientSp = current->getValue();
1904 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001905 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001906 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001907 " API level, evicting prior client...");
1908 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001909 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001910 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001911 *client = clientSp;
1912 return NO_ERROR;
1913 }
1914 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001915 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001916 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001917
Ruben Brunkcc776712015-02-17 20:18:47 -08001918 // Get state for the given cameraId
1919 auto state = getCameraState(cameraId);
1920 if (state == nullptr) {
1921 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001922 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001923 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001924 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001925 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001926
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001927 sp<IServiceManager> sm = defaultServiceManager();
1928 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001929 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001930 // If processinfo service is not available and the client is automotive privileged
1931 // client used for safety critical uses cases such as rear-view and surround-view which
1932 // needs to be available before android boot completes, then use the hardcoded values
1933 // for the process state and priority score. As this scenario is before android system
1934 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1935 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1936 // visible on the top.
1937 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1938 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1939 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1940 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1941 } else {
1942 // Get current active client PIDs
1943 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1944 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001945
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001946 std::vector<int> priorityScores(ownerPids.size());
1947 std::vector<int> states(ownerPids.size());
1948
1949 // Get priority scores of all active PIDs
1950 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1951 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1952 if (err != OK) {
1953 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1954 return err;
1955 }
1956
1957 // Update all active clients' priorities
1958 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1959 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1960 pidToPriorityMap.emplace(ownerPids[i],
1961 resource_policy::ClientPriority(priorityScores[i], states[i],
1962 /* isVendorClient won't get copied over*/ false,
1963 /* oomScoreOffset won't get copied over*/ 0));
1964 }
1965 mActiveClientManager.updatePriorities(pidToPriorityMap);
1966
1967 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1968 int32_t actualState = states[states.size() - 1];
1969
1970 // Make descriptor for incoming client. We store the oomScoreOffset
1971 // since we might need it later on new handleEvictionsLocked and
1972 // ProcessInfoService would not take that into account.
1973 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1974 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1975 state->getConflicting(), actualScore, clientPid, actualState,
1976 oomScoreOffset, systemNativeClient);
1977 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001978
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001979 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1980
Ruben Brunkcc776712015-02-17 20:18:47 -08001981 // Find clients that would be evicted
1982 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1983
1984 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1985 // background, so we cannot do evictions
1986 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1987 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1988 " priority).", clientPid);
1989
1990 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001991 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001992 auto incompatibleClients =
1993 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1994
Austin Borgered99f642023-06-01 16:51:35 -07001995 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1996 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1997 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001998 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001999
2000 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002001 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002002 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002003 i->getKey().c_str(),
2004 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002005 i->getOwnerId(), i->getPriority().getScore(),
2006 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002007 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002008 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2009 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002010 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002011 }
2012
2013 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002014 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002015 mEventLog.add(msg);
2016
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002017 auto current = mActiveClientManager.get(cameraId);
2018 if (current != nullptr) {
2019 return -EBUSY; // CAMERA_IN_USE
2020 } else {
2021 return -EUSERS; // MAX_CAMERAS_IN_USE
2022 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002023 }
2024
2025 for (auto& i : evicted) {
2026 sp<BasicClient> clientSp = i->getValue();
2027 if (clientSp.get() == nullptr) {
2028 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2029
2030 // TODO: Remove this
2031 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2032 __FUNCTION__);
2033 mActiveClientManager.remove(i);
2034 continue;
2035 }
2036
2037 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002038 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002039 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002040
Ruben Brunkcc776712015-02-17 20:18:47 -08002041 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002042 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002043 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2044 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002045 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002046 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002047 i->getPriority().getState(), cameraId.c_str(),
2048 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002049 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002050
2051 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002052 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002053 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002054 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002055 }
2056
Ruben Brunkcc776712015-02-17 20:18:47 -08002057 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2058 // other clients from connecting in mServiceLockWrapper if held
2059 mServiceLock.unlock();
2060
2061 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002062 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002063
2064 // Destroy evicted clients
2065 for (auto& i : evictedClients) {
2066 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002067 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002068 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002069
Austin Borger22c5c852024-03-08 13:31:36 -08002070 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002071
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002072 for (const auto& i : evictedClients) {
2073 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002074 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002075 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2076 if (ret == TIMED_OUT) {
2077 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002078 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2079 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002080 return -EBUSY;
2081 }
2082 if (ret != NO_ERROR) {
2083 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002084 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2085 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002086 return ret;
2087 }
2088 }
2089
2090 evictedClients.clear();
2091
Ruben Brunkcc776712015-02-17 20:18:47 -08002092 // Once clients have been disconnected, relock
2093 mServiceLock.lock();
2094
2095 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2096 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2097 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002098 }
2099
Ruben Brunkcc776712015-02-17 20:18:47 -08002100 *partial = clientDescriptor;
2101 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002102}
2103
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002104Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002105 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002106 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002107 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002108 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002109 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002110 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002111 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002112 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002113 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002114 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002115 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002116
Austin Borger65e64642024-06-11 15:58:23 -07002117 std::string cameraIdStr =
2118 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002119 if (cameraIdStr.empty()) {
2120 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002121 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002122 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2123 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2124 }
malikakashedb38962023-09-06 00:03:35 +00002125
Austin Borger7d2b9232024-07-22 14:17:14 -07002126 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2127 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002128
Austin Borger95a00152024-09-23 17:20:24 -07002129 AttributionSourceState resolvedClientAttribution(clientAttribution);
2130 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraIdStr);
2131 if (!ret.isOk()) {
2132 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002133 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002134 toStdString(ret.toString8()));
2135 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002136 }
2137
Austin Borger95a00152024-09-23 17:20:24 -07002138 const int clientPid = resolvedClientAttribution.pid;
2139 const int clientUid = resolvedClientAttribution.uid;
2140 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2141
2142 logConnectionAttempt(clientPid, clientPackageName, cameraIdStr, API_1);
Austin Borgerb01a8702024-07-22 16:20:34 -07002143
Ruben Brunkcc776712015-02-17 20:18:47 -08002144 sp<Client> client = nullptr;
Austin Borger23694432024-10-07 19:28:01 -07002145 ret = connectHelper<ICameraClient, Client>(
2146 cameraClient, cameraIdStr, api1CameraId, resolvedClientAttribution,
2147 /*systemNativeClient*/ false, API_1,
2148 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion, rotationOverride,
2149 forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/ client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002150
Biswarup Pal37a75182024-01-16 15:53:35 +00002151 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002152 logRejected(cameraIdStr, getCallingPid(),
Austin Borger23694432024-10-07 19:28:01 -07002153 clientAttribution.packageName.value_or(kUnknownPackageName),
Austin Borger95a00152024-09-23 17:20:24 -07002154 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002155 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002156 }
2157
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002158 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002159
2160 const sp<IServiceManager> sm(defaultServiceManager());
2161 const auto& mActivityManager = getActivityManager();
2162 if (mActivityManager) {
2163 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002164 getCallingUid(),
2165 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002166 }
2167
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002168 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002169}
2170
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002171bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2172 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002173 // If the client is not a vendor client, don't add listener if
2174 // a) the camera is a publicly hidden secure camera OR
2175 // b) the camera is a system only camera and the client doesn't
2176 // have android.permission.SYSTEM_CAMERA permissions.
2177 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2178 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002179 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002180 return true;
2181 }
2182 return false;
2183}
2184
Austin Borgered99f642023-06-01 16:51:35 -07002185bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002186 // Rules for rejection:
2187 // 1) If cameraserver tries to access this camera device, accept the
2188 // connection.
2189 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002190 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002191 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2192 // and the serving thread is a non hwbinder thread, the client must have
2193 // android.permission.SYSTEM_CAMERA permissions to connect.
2194
Austin Borger22c5c852024-03-08 13:31:36 -08002195 int cPid = getCallingPid();
2196 int cUid = getCallingUid();
2197 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002198 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2199 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002200 // This isn't a known camera ID, so it's not a system camera
2201 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2202 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002203 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002204
2205 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002206 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002207 return false;
2208 }
2209 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002210 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002211 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2212 return true;
2213 }
2214 // (3) Here we only check for permissions if it is a system only camera device. This is since
2215 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2216 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2217 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002218 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002219 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002220 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2221 cameraId.c_str());
2222 return true;
2223 }
2224
2225 return false;
2226}
2227
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002228Status CameraService::connectDevice(
2229 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002230 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002231 int oomScoreOffset, int targetSdkVersion,
2232 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002233 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002234 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002235 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002236 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002237 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002238 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002239 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002240 int callingPid = getCallingPid();
2241 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002242 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002243 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002244 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002245 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002246 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002247 }
Austin Borger249e6592024-03-10 22:28:11 -07002248
Austin Borger65e64642024-06-11 15:58:23 -07002249 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2250 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002251 if (!cameraIdOptional.has_value()) {
2252 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002253 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002254 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2255 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2256 }
2257 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002258
Austin Borger7d2b9232024-07-22 14:17:14 -07002259 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002260
Austin Borger95a00152024-09-23 17:20:24 -07002261 AttributionSourceState resolvedClientAttribution(clientAttribution);
2262 if (!flags::use_context_attribution_source()) {
2263 resolvedClientAttribution.pid = USE_CALLING_PID;
2264 }
2265 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraId);
2266 if (!ret.isOk()) {
2267 logRejected(cameraId, getCallingPid(), clientAttribution.packageName.value_or(""),
2268 toStdString(ret.toString8()));
2269 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002270 }
2271
Austin Borger95a00152024-09-23 17:20:24 -07002272 const int clientPid = resolvedClientAttribution.pid;
2273 const int clientUid = resolvedClientAttribution.uid;
2274 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2275 userid_t clientUserId = multiuser_get_user_id(resolvedClientAttribution.uid);
Austin Borgerb01a8702024-07-22 16:20:34 -07002276
Austin Borger95a00152024-09-23 17:20:24 -07002277 logConnectionAttempt(clientPid, clientPackageName, cameraId, API_2);
Austin Borgerb01a8702024-07-22 16:20:34 -07002278
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002279 if (oomScoreOffset < 0) {
Austin Borger95a00152024-09-23 17:20:24 -07002280 std::string msg = fmt::sprintf(
2281 "Cannot increase the priority of a client %s pid %d for "
2282 "camera id %s",
2283 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002284 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2285 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002286 }
2287
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002288 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2289 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002290 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2291 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002292 std::string msg = "Camera disabled by device policy";
2293 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2294 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002295 }
2296
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002297 // enforce system camera permissions
Austin Borger95a00152024-09-23 17:20:24 -07002298 if (oomScoreOffset > 0 && !hasPermissionsForSystemCamera(cameraId, clientPid, callingUid) &&
2299 !isTrustedCallingUid(callingUid)) {
2300 std::string msg = fmt::sprintf(
2301 "Cannot change the priority of a client %s pid %d for "
2302 "camera id %s without SYSTEM_CAMERA permissions",
2303 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002304 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2305 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002306 }
2307
Austin Borger95a00152024-09-23 17:20:24 -07002308 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks, CameraDeviceClient>(
Austin Borger23694432024-10-07 19:28:01 -07002309 cameraCb, cameraId, /*api1CameraId*/ -1, resolvedClientAttribution, systemNativeClient,
2310 API_2, /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger95a00152024-09-23 17:20:24 -07002311 /*forceSlowJpegMode*/ false, unresolvedCameraId, isNonSystemNdk, /*out*/ client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002312
Biswarup Pal37a75182024-01-16 15:53:35 +00002313 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002314 logRejected(cameraId, clientPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002315 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002316 }
2317
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002318 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002319 Mutex::Autolock lock(mServiceLock);
2320
2321 // Clear the previous cached logs and reposition the
2322 // file offset to beginning of the file to log new data.
2323 // If either truncate or lseek fails, close the previous file and create a new one.
2324 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2325 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2326 // Close the previous memfd.
2327 close(mMemFd);
2328 // If failure to wipe the data, then create a new file and
2329 // assign the new value to mMemFd.
2330 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2331 if (mMemFd == -1) {
2332 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2333 }
2334 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002335 const sp<IServiceManager> sm(defaultServiceManager());
2336 const auto& mActivityManager = getActivityManager();
2337 if (mActivityManager) {
2338 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002339 callingUid,
2340 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002341 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002342 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002343}
2344
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002345bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2346 int callingPid, int callingUid) {
2347 if (!isAutomotiveDevice()) {
2348 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2349 }
2350
2351 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2352 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2353 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2354 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2355 "using camera %s", callingUid, cam_id.c_str());
2356 return false;
2357 }
2358
2359 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2360 return true;
2361 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2362 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002363 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2364 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002365 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2366 return false;
2367 } else {
2368 return true;
2369 }
2370 }
2371 return false;
2372}
2373
Austin Borger7d2b9232024-07-22 14:17:14 -07002374void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
Austin Borger95a00152024-09-23 17:20:24 -07002375 const std::string& cameraId,
2376 apiLevel effectiveApiLevel) const {
Austin Borger7d2b9232024-07-22 14:17:14 -07002377 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borger95a00152024-09-23 17:20:24 -07002378 "Camera API version %d",
2379 clientPid, clientPackageName.c_str(), cameraId.c_str(),
2380 static_cast<int>(effectiveApiLevel));
Austin Borger7d2b9232024-07-22 14:17:14 -07002381}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002382
Austin Borger23694432024-10-07 19:28:01 -07002383template <class CALLBACK, class CLIENT>
Austin Borger7d2b9232024-07-22 14:17:14 -07002384Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
Austin Borger23694432024-10-07 19:28:01 -07002385 int api1CameraId,
2386 const AttributionSourceState& clientAttribution,
2387 bool systemNativeClient, apiLevel effectiveApiLevel,
2388 bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2389 int rotationOverride, bool forceSlowJpegMode,
2390 const std::string& originalCameraId, bool isNonSystemNdk,
2391 /*out*/ sp<CLIENT>& device) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002392 binder::Status ret = binder::Status::ok();
2393
Shuzhen Wang316781a2020-08-18 18:11:01 -07002394 nsecs_t openTimeNs = systemTime();
2395
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002396 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002397 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002398 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002399
Austin Borger23694432024-10-07 19:28:01 -07002400 const std::string clientPackageName =
2401 clientAttribution.packageName.value_or(kUnknownPackageName);
2402
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002403 {
2404 // Acquire mServiceLock and prevent other clients from connecting
2405 std::unique_ptr<AutoConditionLock> lock =
2406 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2407
2408 if (lock == nullptr) {
Austin Borger23694432024-10-07 19:28:01 -07002409 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting).",
2410 clientAttribution.pid);
2411 return STATUS_ERROR_FMT(
2412 ERROR_MAX_CAMERAS_IN_USE,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002413 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borger23694432024-10-07 19:28:01 -07002414 cameraId.c_str(), clientPackageName.c_str(), clientAttribution.pid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002415 }
2416
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002417 // Enforce client permissions and do basic validity checks
Austin Borger23694432024-10-07 19:28:01 -07002418 if (!(ret = validateConnectLocked(cameraId, clientAttribution)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002419 return ret;
2420 }
2421
2422 // Check the shim parameters after acquiring lock, if they have already been updated and
2423 // we were doing a shim update, return immediately
2424 if (shimUpdateOnly) {
2425 auto cameraState = getCameraState(cameraId);
2426 if (cameraState != nullptr) {
2427 if (!cameraState->getShimParams().isEmpty()) return ret;
2428 }
2429 }
2430
2431 status_t err;
2432
2433 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002434 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger23694432024-10-07 19:28:01 -07002435 if ((err = handleEvictionsLocked(
2436 cameraId, clientAttribution.pid, effectiveApiLevel,
2437 IInterface::asBinder(cameraCb),
2438 clientAttribution.packageName.value_or(kUnknownPackageName), oomScoreOffset,
2439 systemNativeClient, /*out*/ &clientTmp,
2440 /*out*/ &partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002441 switch (err) {
2442 case -ENODEV:
2443 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2444 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002445 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002446 case -EBUSY:
2447 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2448 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002449 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002450 case -EUSERS:
2451 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2452 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002453 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002454 default:
2455 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2456 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002457 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002458 }
2459 }
2460
2461 if (clientTmp.get() != nullptr) {
2462 // Handle special case for API1 MediaRecorder where the existing client is returned
2463 device = static_cast<CLIENT*>(clientTmp.get());
2464 return ret;
2465 }
2466
2467 // give flashlight a chance to close devices if necessary.
2468 mFlashlight->prepareDeviceOpen(cameraId);
2469
Austin Borger18b30a72022-10-27 12:20:29 -07002470 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002471 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002472 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002473 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002474 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002475 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002476 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002477 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002478 }
2479
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002480 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002481 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002482 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002483
Austin Borger6e831c42024-07-22 13:07:56 -07002484 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2485 // that's connected to camera service directly.
Austin Borger23694432024-10-07 19:28:01 -07002486 if (!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
2487 clientAttribution.attributionTag, cameraId, api1CameraId, facing,
2488 orientation, getCallingPid(), clientAttribution.uid, getpid(),
2489 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
2490 rotationOverride, forceSlowJpegMode, originalCameraId,
2491 /*out*/ &tmp))
2492 .isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002493 return ret;
2494 }
2495 client = static_cast<CLIENT*>(tmp.get());
2496
2497 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2498 __FUNCTION__);
2499
Austin Borgered99f642023-06-01 16:51:35 -07002500 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002501 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002502 if (err != OK) {
2503 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002504 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002505 mServiceLock.unlock();
2506 client->disconnect();
2507 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002508 switch(err) {
2509 case BAD_VALUE:
2510 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002511 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002512 case -EBUSY:
2513 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002514 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002515 case -EUSERS:
2516 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2517 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002518 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002519 case PERMISSION_DENIED:
2520 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002521 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002522 case -EACCES:
2523 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002524 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002525 case -ENODEV:
2526 default:
2527 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002528 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002529 strerror(-err), err);
2530 }
2531 }
2532
2533 // Update shim paremeters for legacy clients
2534 if (effectiveApiLevel == API_1) {
2535 // Assume we have always received a Client subclass for API1
2536 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2537 String8 rawParams = shimClient->getParameters();
2538 CameraParameters params(rawParams);
2539
2540 auto cameraState = getCameraState(cameraId);
2541 if (cameraState != nullptr) {
2542 cameraState->setShimParams(params);
2543 } else {
2544 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002545 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002546 }
2547 }
2548
Ravneetaeb20dc2022-03-30 05:33:03 +00002549 // Enable/disable camera service watchdog
2550 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2551
Emilian Peev6d45db82024-01-18 20:11:54 +00002552 CameraMetadata chars;
2553 bool rotateAndCropSupported = true;
2554 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002555 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002556 if (err == OK) {
2557 auto availableRotateCropEntry = chars.find(
2558 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2559 if (availableRotateCropEntry.count <= 1) {
2560 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002561 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002562 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002563 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2564 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002565 }
2566
Emilian Peev6d45db82024-01-18 20:11:54 +00002567 if (rotateAndCropSupported) {
2568 // Set rotate-and-crop override behavior
2569 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2570 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002571 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2572 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002573 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2574 switch (portraitRotation) {
2575 case 90:
2576 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2577 break;
2578 case 180:
2579 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2580 break;
2581 case 270:
2582 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2583 break;
2584 default:
2585 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2586 break;
2587 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002588 // Here we're communicating to the client the chosen rotate
2589 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002590 client->setRotateAndCropOverride(rotateAndCropMode);
2591 } else {
2592 client->setRotateAndCropOverride(
Austin Borger23694432024-10-07 19:28:01 -07002593 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2594 clientPackageName, facing,
2595 multiuser_get_user_id(clientAttribution.uid)));
Emilian Peev6d45db82024-01-18 20:11:54 +00002596 }
2597 }
2598
2599 bool autoframingSupported = true;
2600 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2601 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2602 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2603 autoframingSupported = false;
2604 }
2605
2606 if (autoframingSupported) {
2607 // Set autoframing override behaviour
2608 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2609 client->setAutoframingOverride(mOverrideAutoframingMode);
2610 } else {
2611 client->setAutoframingOverride(
2612 mCameraServiceProxyWrapper->getAutoframingOverride(
2613 clientPackageName));
2614 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002615 }
2616
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002617 bool isCameraPrivacyEnabled;
2618 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002619 // Set camera muting behavior.
Austin Borger23694432024-10-07 19:28:01 -07002620 isCameraPrivacyEnabled =
2621 this->isCameraPrivacyEnabled(toString16(client->getPackageName()), cameraId,
2622 clientAttribution.pid, clientAttribution.uid);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002623 } else {
2624 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002625 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002626 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002627
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002628 if (client->supportsCameraMute()) {
2629 client->setCameraMute(
2630 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2631 } else if (isCameraPrivacyEnabled) {
2632 // no camera mute supported, but privacy is on! => disconnect
2633 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2634 client->getPackageName().c_str(), cameraId.c_str());
2635 // Do not hold mServiceLock while disconnecting clients, but
2636 // retain the condition blocking other clients from connecting
2637 // in mServiceLockWrapper if held.
2638 mServiceLock.unlock();
2639 // Clear caller identity temporarily so client disconnect PID
2640 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002641 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002642 // Note AppOp to trigger the "Unblock" dialog
2643 client->noteAppOp();
2644 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002645 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002646 // Reacquire mServiceLock
2647 mServiceLock.lock();
2648
2649 return STATUS_ERROR_FMT(ERROR_DISABLED,
2650 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002651 }
2652
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002653 if (shimUpdateOnly) {
2654 // If only updating legacy shim parameters, immediately disconnect client
2655 mServiceLock.unlock();
2656 client->disconnect();
2657 mServiceLock.lock();
2658 } else {
2659 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002660 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002661 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002662
2663 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002664 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002665 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002666 } // lock is destroyed, allow further connect calls
2667
2668 // Important: release the mutex here so the client can call back into the service from its
2669 // destructor (can be at the end of the call)
2670 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002671
2672 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002673 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002674 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002675
Cliff Wud3a05312021-04-26 23:07:31 +08002676 {
2677 Mutex::Autolock lock(mInjectionParametersLock);
2678 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2679 mInjectionInitPending = false;
2680 status_t res = NO_ERROR;
2681 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2682 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002683 sp<BasicClient> clientSp = clientDescriptor->getValue();
2684 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2685 if(res != OK) {
2686 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2687 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002688 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002689 }
2690 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002691 if (res != OK) {
2692 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2693 }
2694 } else {
2695 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002696 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002697 res = NO_INIT;
2698 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2699 }
2700 }
2701 }
2702
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002703 return ret;
2704}
2705
Austin Borgered99f642023-06-01 16:51:35 -07002706status_t CameraService::addOfflineClient(const std::string &cameraId,
2707 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002708 if (offlineClient.get() == nullptr) {
2709 return BAD_VALUE;
2710 }
2711
2712 {
2713 // Acquire mServiceLock and prevent other clients from connecting
2714 std::unique_ptr<AutoConditionLock> lock =
2715 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2716
2717 if (lock == nullptr) {
2718 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2719 , __FUNCTION__, offlineClient->getClientPid());
2720 return TIMED_OUT;
2721 }
2722
2723 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2724 if (onlineClientDesc.get() == nullptr) {
2725 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2726 cameraId.c_str());
2727 return BAD_VALUE;
2728 }
2729
2730 // Offline clients do not evict or conflict with other online devices. Resource sharing
2731 // conflicts are handled by the camera provider which will either succeed or fail before
2732 // reaching this method.
2733 const auto& onlinePriority = onlineClientDesc->getPriority();
2734 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2735 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002736 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002737 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002738 // native clients don't have offline processing support.
2739 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002740 if (offlineClientDesc == nullptr) {
2741 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2742 return BAD_VALUE;
2743 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002744
2745 // Allow only one offline device per camera
2746 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2747 if (!incompatibleClients.empty()) {
2748 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2749 return BAD_VALUE;
2750 }
2751
Austin Borgered99f642023-06-01 16:51:35 -07002752 std::string monitorTags = isClientWatched(offlineClient.get())
2753 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002754 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002755 if (err != OK) {
2756 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2757 return err;
2758 }
2759
2760 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2761 if (evicted.size() > 0) {
2762 for (auto& i : evicted) {
2763 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002764 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002765 }
2766
2767 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2768 "properly", __FUNCTION__);
2769
2770 return BAD_VALUE;
2771 }
2772
2773 logConnectedOffline(offlineClientDesc->getKey(),
2774 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002775 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002776
2777 sp<IBinder> remoteCallback = offlineClient->getRemote();
2778 if (remoteCallback != nullptr) {
2779 remoteCallback->linkToDeath(this);
2780 }
2781 } // lock is destroyed, allow further connect calls
2782
2783 return OK;
2784}
2785
Austin Borgered99f642023-06-01 16:51:35 -07002786Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002787 int32_t torchStrength, const sp<IBinder>& clientBinder,
2788 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002789 Mutex::Autolock lock(mServiceLock);
2790
2791 ATRACE_CALL();
2792 if (clientBinder == nullptr) {
2793 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2794 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2795 "Torch client binder in null.");
2796 }
2797
Austin Borger22c5c852024-03-08 13:31:36 -08002798 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002799 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2800 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002801 if (!cameraIdOptional.has_value()) {
2802 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002803 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002804 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2805 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2806 }
2807 std::string cameraId = cameraIdOptional.value();
2808
Austin Borgered99f642023-06-01 16:51:35 -07002809 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002810 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002811 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002812 }
2813
2814 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002815 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002816 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002817 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002818 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002819 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002820 }
2821
2822 StatusInternal cameraStatus = state->getStatus();
2823 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2824 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002825 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002826 (int)cameraStatus);
2827 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002828 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002829 }
2830
2831 {
2832 Mutex::Autolock al(mTorchStatusMutex);
2833 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002834 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002835 if (err != OK) {
2836 if (err == NAME_NOT_FOUND) {
2837 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002838 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002839 }
2840 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002841 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002842 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2843 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002844 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002845 }
2846
2847 if (status == TorchModeStatus::NOT_AVAILABLE) {
2848 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2849 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002850 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002851 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2852 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002853 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002854 } else {
2855 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002856 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002857 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2858 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002859 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002860 }
2861 }
2862 }
2863
2864 {
2865 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002866 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002867 }
2868 // Check if the current torch strength level is same as the new one.
2869 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002870 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002871
Austin Borgered99f642023-06-01 16:51:35 -07002872 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002873
2874 if (err != OK) {
2875 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002876 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 switch (err) {
2878 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002879 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2880 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002881 errorCode = ERROR_ILLEGAL_ARGUMENT;
2882 break;
2883 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002884 msg = fmt::sprintf("Camera \"%s\" is in use",
2885 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002886 errorCode = ERROR_CAMERA_IN_USE;
2887 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002888 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002889 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002890 "valid range.", torchStrength);
2891 errorCode = ERROR_ILLEGAL_ARGUMENT;
2892 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002893 default:
Austin Borgered99f642023-06-01 16:51:35 -07002894 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002895 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002896 }
Austin Borgered99f642023-06-01 16:51:35 -07002897 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2898 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002899 }
2900
2901 {
2902 // update the link to client's death
2903 // Store the last client that turns on each camera's torch mode.
2904 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002905 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002906 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002907 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002908 } else {
2909 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2910 mTorchClientMap.replaceValueAt(index, clientBinder);
2911 }
2912 clientBinder->linkToDeath(this);
2913 }
2914
Austin Borger22c5c852024-03-08 13:31:36 -08002915 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002916 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002917 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002919 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002920 }
2921 return Status::ok();
2922}
2923
malikakash73125c62023-07-21 22:44:34 +00002924Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002925 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2926 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002927 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002928
2929 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002930 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002931 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002932 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2933 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002934 }
2935
Austin Borger22c5c852024-03-08 13:31:36 -08002936 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002937 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2938 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002939 if (!cameraIdOptional.has_value()) {
2940 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002941 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002942 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2943 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2944 }
2945 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002946
Austin Borgered99f642023-06-01 16:51:35 -07002947 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002948 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002949 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002950 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002951 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002952 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002953 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002954 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002955 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002956 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002957 }
2958
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002959 StatusInternal cameraStatus = state->getStatus();
2960 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002961 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002962 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2963 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002964 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002965 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002966 }
2967
2968 {
2969 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002970 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002971 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972 if (err != OK) {
2973 if (err == NAME_NOT_FOUND) {
2974 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002975 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002976 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002977 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002978 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002979 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002980 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002981 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002982 }
2983
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002984 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002985 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002986 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002987 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002988 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2989 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002990 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002991 } else {
2992 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002993 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002994 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2995 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002996 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002997 }
2998 }
2999 }
3000
Ruben Brunk99e69712015-05-26 17:25:07 -07003001 {
3002 // Update UID map - this is used in the torch status changed callbacks, so must be done
3003 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003004 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003005 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003006 }
3007
Austin Borgered99f642023-06-01 16:51:35 -07003008 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003009
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003010 if (err != OK) {
3011 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003012 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003013 switch (err) {
3014 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003015 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3016 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003017 errorCode = ERROR_ILLEGAL_ARGUMENT;
3018 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003019 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003020 msg = fmt::sprintf("Camera \"%s\" is in use",
3021 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003022 errorCode = ERROR_CAMERA_IN_USE;
3023 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003024 default:
Austin Borgered99f642023-06-01 16:51:35 -07003025 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003026 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003027 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003028 errorCode = ERROR_INVALID_OPERATION;
3029 }
Austin Borgered99f642023-06-01 16:51:35 -07003030 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3031 logServiceError(msg, errorCode);
3032 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003033 }
3034
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003035 {
3036 // update the link to client's death
3037 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003038 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003039 if (enabled) {
3040 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003041 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003042 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003043 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003044 mTorchClientMap.replaceValueAt(index, clientBinder);
3045 }
3046 clientBinder->linkToDeath(this);
3047 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003048 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003049 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003050 }
3051
Austin Borger22c5c852024-03-08 13:31:36 -08003052 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003053 std::string torchState = enabled ? "on" : "off";
3054 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3055 torchState.c_str(), clientPid);
3056 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003057 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003058}
3059
Austin Borgered99f642023-06-01 16:51:35 -07003060void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3061 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3062 mTorchUidMap[cameraId].first = uid;
3063 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003064 } else {
3065 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003066 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003067 }
3068}
3069
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003070Status CameraService::notifySystemEvent(int32_t eventId,
3071 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003072 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003073 const int selfPid = getpid();
3074
3075 // Permission checks
3076 if (pid != selfPid) {
3077 // Ensure we're being called by system_server, or similar process with
3078 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003079 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003080 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003081 ALOGE("Permission Denial: cannot send updates to camera service about system"
3082 " events from pid=%d, uid=%d", pid, uid);
3083 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003084 "No permission to send updates to camera service about system events"
3085 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003086 }
3087 }
3088
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003089 ATRACE_CALL();
3090
Ruben Brunk36597b22015-03-20 22:15:57 -07003091 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003092 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003093 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003094 // from a system server crash
3095 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003096 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003097 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003098 break;
3099 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003100 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3101 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003102 if (args.size() != 1) {
3103 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3104 "USB Device Event requires 1 argument");
3105 }
3106
Valentin Iftime29e2e152021-08-13 15:17:33 +02003107 // Notify CameraProviderManager for lazy HALs
3108 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3109 std::to_string(args[0]));
3110 break;
3111 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003112 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003113 default: {
3114 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3115 eventId);
3116 break;
3117 }
3118 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003119 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003120}
3121
Emilian Peev53722fa2019-02-22 17:47:20 -08003122void CameraService::notifyMonitoredUids() {
3123 Mutex::Autolock lock(mStatusListenerLock);
3124
3125 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003126 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003127 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3128 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003129 }
3130}
3131
Austin Borgerdddb7552023-03-30 17:53:01 -07003132void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3133 Mutex::Autolock lock(mStatusListenerLock);
3134
3135 for (const auto& it : mListenerList) {
3136 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3137 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3138 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3139 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3140 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3141 }
3142 }
3143}
3144
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003145Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003146 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003147 const int selfPid = getpid();
3148
3149 // Permission checks
3150 if (pid != selfPid) {
3151 // Ensure we're being called by system_server, or similar process with
3152 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003153 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003154 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003155 ALOGE("Permission Denial: cannot send updates to camera service about device"
3156 " state changes from pid=%d, uid=%d", pid, uid);
3157 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3158 "No permission to send updates to camera service about device state"
3159 " changes from pid=%d, uid=%d", pid, uid);
3160 }
3161 }
3162
3163 ATRACE_CALL();
3164
Austin Borger18b30a72022-10-27 12:20:29 -07003165 {
3166 Mutex::Autolock lock(mServiceLock);
3167 mDeviceState = newState;
3168 }
3169
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003170 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003171
3172 return Status::ok();
3173}
3174
Emilian Peev8b64f282021-03-25 16:49:57 -07003175Status CameraService::notifyDisplayConfigurationChange() {
3176 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003177 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003178 const int selfPid = getpid();
3179
3180 // Permission checks
3181 if (callingPid != selfPid) {
3182 // Ensure we're being called by system_server, or similar process with
3183 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003184 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003185 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003186 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3187 " changes from pid=%d, uid=%d", callingPid, uid);
3188 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3189 "No permission to send updates to camera service about orientation"
3190 " changes from pid=%d, uid=%d", callingPid, uid);
3191 }
3192 }
3193
3194 Mutex::Autolock lock(mServiceLock);
3195
3196 // Don't do anything if rotate-and-crop override via cmd is active
3197 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3198
3199 const auto clients = mActiveClientManager.getAll();
3200 for (auto& current : clients) {
3201 if (current != nullptr) {
3202 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003203 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3204 basicClient->setRotateAndCropOverride(
3205 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3206 basicClient->getPackageName(),
3207 basicClient->getCameraFacing(),
3208 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003209 }
3210 }
3211 }
3212
3213 return Status::ok();
3214}
3215
3216Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003217 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3218 ATRACE_CALL();
3219 if (!concurrentCameraIds) {
3220 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3221 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3222 }
3223
3224 if (!mInitialized) {
3225 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003226 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003227 return STATUS_ERROR(ERROR_DISCONNECTED,
3228 "Camera subsystem is not available");
3229 }
3230 // First call into the provider and get the set of concurrent camera
3231 // combinations
3232 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003233 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003234 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003235 std::vector<std::pair<std::string, int32_t>> validCombination;
3236 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003237 for (auto &cameraId : combination) {
3238 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003239 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003240 if (state == nullptr) {
3241 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3242 continue;
3243 }
3244 StatusInternal status = state->getStatus();
3245 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3246 continue;
3247 }
Austin Borgered99f642023-06-01 16:51:35 -07003248 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003249 continue;
3250 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003251 auto [cameraOwnerDeviceId, mappedCameraId] =
3252 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3253 if (firstDeviceId == kInvalidDeviceId) {
3254 firstDeviceId = cameraOwnerDeviceId;
3255 } else if (firstDeviceId != cameraOwnerDeviceId) {
3256 // Found an invalid combination which contains cameras with different device id's,
3257 // hence discard it.
3258 validCombination.clear();
3259 break;
3260 }
3261 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003262 }
3263 if (validCombination.size() != 0) {
3264 concurrentCameraIds->push_back(std::move(validCombination));
3265 }
3266 }
3267 return Status::ok();
3268}
3269
3270Status CameraService::isConcurrentSessionConfigurationSupported(
3271 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003272 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003273 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003274 if (!isSupported) {
3275 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3276 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3277 }
3278
3279 if (!mInitialized) {
3280 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3281 return STATUS_ERROR(ERROR_DISCONNECTED,
3282 "Camera subsystem is not available");
3283 }
3284
Biswarup Pal7d072862024-04-17 15:24:47 +00003285 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3286 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003287 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3288 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003289 if (!cameraIdOptional.has_value()) {
3290 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003291 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003292 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3293 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3294 }
3295 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3296 }
3297
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003298 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003299 int callingPid = getCallingPid();
3300 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003301 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003302 hasPermissionsForCamera(callingPid, callingUid,
3303 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003304 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003305 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003306 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3307 "android.permission.CAMERA needed to call"
3308 "isConcurrentSessionConfigurationSupported");
3309 }
3310
3311 status_t res =
3312 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003313 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3314 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003315 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003316 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003317 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003318 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3319 "support %s (%d)", strerror(-res), res);
3320 }
3321 return Status::ok();
3322}
3323
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003324Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3325 /*out*/
3326 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003327 return addListenerHelper(listener, cameraStatuses);
3328}
3329
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003330binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3331 std::vector<hardware::CameraStatus>* cameraStatuses) {
3332 return addListenerHelper(listener, cameraStatuses, false, true);
3333}
3334
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003335Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3336 /*out*/
3337 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003338 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003339 ATRACE_CALL();
3340
Igor Murashkinbfc99152013-02-27 12:55:20 -08003341 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003342
Ruben Brunk3450ba72015-06-16 11:00:37 -07003343 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003344 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003345 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003346 }
3347
Austin Borger22c5c852024-03-08 13:31:36 -08003348 auto clientPid = getCallingPid();
3349 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003350 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003351
Igor Murashkinbfc99152013-02-27 12:55:20 -08003352 Mutex::Autolock lock(mServiceLock);
3353
Ruben Brunkcc776712015-02-17 20:18:47 -08003354 {
3355 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003356 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003357 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003358 ALOGW("%s: Tried to add listener %p which was already subscribed",
3359 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003360 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003361 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003362 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003363
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003364 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003365 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3366 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003367 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003368 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003369 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003370 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003371 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3372 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3373 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003374 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003375 // The listener still needs to be added to the list of listeners, regardless of what
3376 // permissions the listener process has / whether it is a vendor listener. Since it might be
3377 // eligible to listen to other camera ids.
3378 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003379 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003380 }
3381
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003382 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003383 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003384 Mutex::Autolock lock(mCameraStatesLock);
3385 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003386 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3387 auto [deviceId, mappedCameraId] =
3388 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3389
3390 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003391 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003392 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3393 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003394 }
3395 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003396 // Remove the camera statuses that should be hidden from the client, we do
3397 // this after collecting the states in order to avoid holding
3398 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3399 // the same time.
3400 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3401 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003402 std::string cameraId = s.cameraId;
3403 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003404 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003405 if (!cameraIdOptional.has_value()) {
3406 std::string msg =
3407 fmt::sprintf(
3408 "Camera %s: Invalid camera id for device id %d",
3409 s.cameraId.c_str(), s.deviceId);
3410 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3411 return true;
3412 }
3413 cameraId = cameraIdOptional.value();
3414 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3415 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3416 ALOGE("%s: Invalid camera id %s, skipping status update",
3417 __FUNCTION__, s.cameraId.c_str());
3418 return true;
3419 }
3420 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3421 clientUid);
3422 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003423
Biswarup Pal37a75182024-01-16 15:53:35 +00003424 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003425 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003426 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003427 // Add only default device cameras here, as virtual cameras currently don't support torch
3428 // anyway. Note that this is a simplification of the implementation here, and we should
3429 // change this when virtual cameras support torch.
3430 if (s.deviceId == kDefaultDeviceId) {
3431 idsChosenForCallback.insert(s.cameraId);
3432 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003433 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003434
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003435 /*
3436 * Immediately signal current torch status to this listener only
3437 * This may be a subset of all the devices, so don't include it in the response directly
3438 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003439 {
3440 Mutex::Autolock al(mTorchStatusMutex);
3441 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003442 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003443 // The camera id is visible to the client. Fine to send torch
3444 // callback.
3445 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003446 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3447 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003448 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003449 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003450 }
3451
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003452 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003453}
Ruben Brunkcc776712015-02-17 20:18:47 -08003454
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003455Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003456 ATRACE_CALL();
3457
Igor Murashkinbfc99152013-02-27 12:55:20 -08003458 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3459
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003460 if (listener == 0) {
3461 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003462 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003463 }
3464
Igor Murashkinbfc99152013-02-27 12:55:20 -08003465 Mutex::Autolock lock(mServiceLock);
3466
Ruben Brunkcc776712015-02-17 20:18:47 -08003467 {
3468 Mutex::Autolock lock(mStatusListenerLock);
3469 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003470 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003471 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003472 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003473 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003474 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003475 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003476 }
3477 }
3478
3479 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3480 __FUNCTION__, listener.get());
3481
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003482 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003483}
3484
Austin Borgered99f642023-06-01 16:51:35 -07003485Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003486
3487 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003488 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3489
3490 if (parameters == NULL) {
3491 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003492 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003493 }
3494
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003495 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003496
3497 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003498 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003499 // Error logged by caller
3500 return ret;
3501 }
3502
3503 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003504
Austin Borgered99f642023-06-01 16:51:35 -07003505 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003506
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003507 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003508}
3509
malikakash98260df2024-05-10 23:33:57 +00003510Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003511 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003512 ATRACE_CALL();
3513
Austin Borgered99f642023-06-01 16:51:35 -07003514 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003515
3516 switch (apiVersion) {
3517 case API_VERSION_1:
3518 case API_VERSION_2:
3519 break;
3520 default:
Austin Borgered99f642023-06-01 16:51:35 -07003521 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3522 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3523 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003524 }
3525
Austin Borger18b30a72022-10-27 12:20:29 -07003526 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003527 auto deviceVersionAndTransport =
3528 getDeviceVersion(cameraId,
3529 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3530 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003531 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003532 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3533 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3534 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003535 }
3536 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3537 int deviceVersion = deviceVersionAndTransport.first;
3538 switch (deviceVersion) {
3539 case CAMERA_DEVICE_API_VERSION_1_0:
3540 case CAMERA_DEVICE_API_VERSION_3_0:
3541 case CAMERA_DEVICE_API_VERSION_3_1:
3542 if (apiVersion == API_VERSION_2) {
3543 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003544 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003545 *isSupported = false;
3546 } else { // if (apiVersion == API_VERSION_1) {
3547 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003548 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003549 *isSupported = true;
3550 }
3551 break;
3552 case CAMERA_DEVICE_API_VERSION_3_2:
3553 case CAMERA_DEVICE_API_VERSION_3_3:
3554 case CAMERA_DEVICE_API_VERSION_3_4:
3555 case CAMERA_DEVICE_API_VERSION_3_5:
3556 case CAMERA_DEVICE_API_VERSION_3_6:
3557 case CAMERA_DEVICE_API_VERSION_3_7:
3558 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003559 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003560 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003561 break;
3562 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003563 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3564 deviceVersion, cameraId.c_str());
3565 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3566 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003567 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003568 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003569 } else {
3570 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003571 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003572 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003573}
3574
malikakash98260df2024-05-10 23:33:57 +00003575Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003576 /*out*/ bool *isSupported) {
3577 ATRACE_CALL();
3578
Austin Borgered99f642023-06-01 16:51:35 -07003579 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3580 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003581
3582 return Status::ok();
3583}
3584
Cliff Wud8cae102021-03-11 01:37:42 +08003585Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003586 const std::string& packageName, const std::string& internalCamId,
3587 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003588 const sp<ICameraInjectionCallback>& callback,
3589 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003590 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003591 ATRACE_CALL();
3592
Austin Borgered99f642023-06-01 16:51:35 -07003593 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003594 const int pid = getCallingPid();
3595 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003596 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3597 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003598 "Permission Denial: no permission to inject camera");
3599 }
3600
3601 // Do not allow any camera injection that injects or replaces a virtual camera.
3602 auto [deviceIdForInternalCamera, _] =
3603 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3604 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3605 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3606 "Cannot replace a virtual camera");
3607 }
3608 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3609 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3610 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3611 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3612 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003613 }
3614
3615 ALOGV(
3616 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3617 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003618 __FUNCTION__, packageName.c_str(),
3619 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003620
Cliff Wud3a05312021-04-26 23:07:31 +08003621 {
3622 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003623 mInjectionInternalCamId = internalCamId;
3624 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003625 mInjectionStatusListener->addListener(callback);
3626 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003627 status_t res = NO_ERROR;
3628 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3629 // If the client already exists, we can directly connect to the camera device through the
3630 // client's injectCamera(), otherwise we need to wait until the client is established
3631 // (execute connectHelper()) before injecting the camera to the camera device.
3632 if (clientDescriptor != nullptr) {
3633 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003634 sp<BasicClient> clientSp = clientDescriptor->getValue();
3635 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3636 if(res != OK) {
3637 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3638 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003639 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003640 }
3641 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003642 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003643 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3644 }
3645 } else {
3646 mInjectionInitPending = true;
3647 }
3648 }
Cliff Wud8cae102021-03-11 01:37:42 +08003649
Cliff Wud3a05312021-04-26 23:07:31 +08003650 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003651}
3652
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003653Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003654 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003655 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3656 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3657 return Status::ok();
3658}
3659
Ruben Brunkcc776712015-02-17 20:18:47 -08003660void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003661 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003662 for (auto& i : mActiveClientManager.getAll()) {
3663 auto clientSp = i->getValue();
3664 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003665 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003666 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003667 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003668 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003669 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003670}
3671
Ruben Brunkcc776712015-02-17 20:18:47 -08003672bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003673 bool ret = false;
3674 {
3675 // Acquire mServiceLock and prevent other clients from connecting
3676 std::unique_ptr<AutoConditionLock> lock =
3677 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003678
Ruben Brunkcc776712015-02-17 20:18:47 -08003679 std::vector<sp<BasicClient>> evicted;
3680 for (auto& i : mActiveClientManager.getAll()) {
3681 auto clientSp = i->getValue();
3682 if (clientSp.get() == nullptr) {
3683 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3684 mActiveClientManager.remove(i);
3685 continue;
3686 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003687 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003688 mActiveClientManager.remove(i);
3689 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003690
Ruben Brunkcc776712015-02-17 20:18:47 -08003691 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003692 clientSp->notifyError(
3693 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003694 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003695 }
3696 }
3697
Ruben Brunkcc776712015-02-17 20:18:47 -08003698 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3699 // other clients from connecting in mServiceLockWrapper if held
3700 mServiceLock.unlock();
3701
Ruben Brunk36597b22015-03-20 22:15:57 -07003702 // Do not clear caller identity, remote caller should be client proccess
3703
Ruben Brunkcc776712015-02-17 20:18:47 -08003704 for (auto& i : evicted) {
3705 if (i.get() != nullptr) {
3706 i->disconnect();
3707 ret = true;
3708 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003709 }
3710
Ruben Brunkcc776712015-02-17 20:18:47 -08003711 // Reacquire mServiceLock
3712 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003713
Ruben Brunkcc776712015-02-17 20:18:47 -08003714 } // lock is destroyed, allow further connect calls
3715
3716 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003717}
3718
Ruben Brunkcc776712015-02-17 20:18:47 -08003719std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003720 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003721 std::shared_ptr<CameraState> state;
3722 {
3723 Mutex::Autolock lock(mCameraStatesLock);
3724 auto iter = mCameraStates.find(cameraId);
3725 if (iter != mCameraStates.end()) {
3726 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003727 }
3728 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003729 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003730}
3731
Austin Borgered99f642023-06-01 16:51:35 -07003732sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003733 // Remove from active clients list
3734 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3735 if (clientDescriptorPtr == nullptr) {
3736 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003737 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003738 return sp<BasicClient>{nullptr};
3739 }
3740
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003741 sp<BasicClient> client = clientDescriptorPtr->getValue();
3742 if (client.get() != nullptr) {
3743 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3744 }
3745 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003746}
3747
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003748void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003749 // Acquire mServiceLock and prevent other clients from connecting
3750 std::unique_ptr<AutoConditionLock> lock =
3751 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3752
Ruben Brunk6267b532015-04-30 17:44:07 -07003753 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003754 for (size_t i = 0; i < newUserIds.size(); i++) {
3755 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003756 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003757 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003758 return;
3759 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003760 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003761 }
3762
Ruben Brunka8ca9152015-04-07 14:23:40 -07003763
Ruben Brunk6267b532015-04-30 17:44:07 -07003764 if (newAllowedUsers == mAllowedUsers) {
3765 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3766 return;
3767 }
3768
3769 logUserSwitch(mAllowedUsers, newAllowedUsers);
3770
3771 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003772
3773 // Current user has switched, evict all current clients.
3774 std::vector<sp<BasicClient>> evicted;
3775 for (auto& i : mActiveClientManager.getAll()) {
3776 auto clientSp = i->getValue();
3777
3778 if (clientSp.get() == nullptr) {
3779 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3780 continue;
3781 }
3782
Ruben Brunk6267b532015-04-30 17:44:07 -07003783 // Don't evict clients that are still allowed.
3784 uid_t clientUid = clientSp->getClientUid();
3785 userid_t clientUserId = multiuser_get_user_id(clientUid);
3786 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3787 continue;
3788 }
3789
Ruben Brunk36597b22015-03-20 22:15:57 -07003790 evicted.push_back(clientSp);
3791
Ruben Brunk36597b22015-03-20 22:15:57 -07003792 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003793 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003794
Ruben Brunk36597b22015-03-20 22:15:57 -07003795 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003796 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003797 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003798 " to user switch.", i->getKey().c_str(),
3799 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003800 i->getOwnerId(), i->getPriority().getScore(),
3801 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003802
3803 }
3804
3805 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3806 // blocking other clients from connecting in mServiceLockWrapper if held.
3807 mServiceLock.unlock();
3808
3809 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003810 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003811
3812 for (auto& i : evicted) {
3813 i->disconnect();
3814 }
3815
Austin Borger22c5c852024-03-08 13:31:36 -08003816 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003817
3818 // Reacquire mServiceLock
3819 mServiceLock.lock();
3820}
Ruben Brunkcc776712015-02-17 20:18:47 -08003821
Austin Borgered99f642023-06-01 16:51:35 -07003822void CameraService::logEvent(const std::string &event) {
3823 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003824 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003825 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003826 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003827 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003828 mEventLog.add(msg);
3829 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3830 // Error event not added to the dumpsys log before
3831 mEventLog.add(msg);
3832 sServiceErrorEventSet.insert(msg);
3833 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003834}
3835
Austin Borgered99f642023-06-01 16:51:35 -07003836void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3837 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003838 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003839 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3840 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003841}
3842
Austin Borgered99f642023-06-01 16:51:35 -07003843void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3844 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003845 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003846 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3847 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003848}
3849
Austin Borgered99f642023-06-01 16:51:35 -07003850void CameraService::logConnected(const std::string &cameraId, int clientPid,
3851 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003852 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003853 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3854 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003855}
3856
Austin Borgered99f642023-06-01 16:51:35 -07003857void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3858 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003859 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003860 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3861 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003862}
3863
Austin Borgered99f642023-06-01 16:51:35 -07003864void CameraService::logRejected(const std::string &cameraId, int clientPid,
3865 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003866 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003867 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3868 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003869}
3870
Austin Borgered99f642023-06-01 16:51:35 -07003871void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3872 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003873 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003874 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3875 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003876}
3877
Ruben Brunk6267b532015-04-30 17:44:07 -07003878void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3879 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003880 std::string newUsers = toString(newUserIds);
3881 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003882 if (oldUsers.size() == 0) {
3883 oldUsers = "<None>";
3884 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003885 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003886 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3887 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003888}
3889
Austin Borgered99f642023-06-01 16:51:35 -07003890void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003891 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003892 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003893}
3894
Austin Borgered99f642023-06-01 16:51:35 -07003895void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003896 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003897 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003898}
3899
Austin Borgered99f642023-06-01 16:51:35 -07003900void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003901 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003902 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003903}
3904
Austin Borgered99f642023-06-01 16:51:35 -07003905void CameraService::logServiceError(const std::string &msg, int errorCode) {
3906 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3907 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003908}
3909
Ruben Brunk36597b22015-03-20 22:15:57 -07003910status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3911 uint32_t flags) {
3912
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913 // Permission checks
3914 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003915 case SHELL_COMMAND_TRANSACTION: {
3916 int in = data.readFileDescriptor();
3917 int out = data.readFileDescriptor();
3918 int err = data.readFileDescriptor();
3919 int argc = data.readInt32();
3920 Vector<String16> args;
3921 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3922 args.add(data.readString16());
3923 }
3924 sp<IBinder> unusedCallback;
3925 sp<IResultReceiver> resultReceiver;
3926 status_t status;
3927 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3928 return status;
3929 }
3930 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3931 return status;
3932 }
3933 status = shellCommand(in, out, err, args);
3934 if (resultReceiver != nullptr) {
3935 resultReceiver->send(status);
3936 }
3937 return NO_ERROR;
3938 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003939 }
3940
3941 return BnCameraService::onTransact(code, data, reply, flags);
3942}
3943
Mathias Agopian65ab4712010-07-14 17:59:35 -07003944// We share the media players for shutter and recording sound for all clients.
3945// A reference count is kept to determine when we will actually release the
3946// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003947sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3948 sp<MediaPlayer> mp = new MediaPlayer();
3949 status_t error;
3950 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003951 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003952 error = mp->prepare();
3953 }
3954 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003955 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003956 mp->disconnect();
3957 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003958 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003959 }
3960 return mp;
3961}
3962
username5755fea2018-12-27 09:48:08 +08003963void CameraService::increaseSoundRef() {
3964 Mutex::Autolock lock(mSoundLock);
3965 mSoundRef++;
3966}
3967
3968void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003969 ATRACE_CALL();
3970
username5755fea2018-12-27 09:48:08 +08003971 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3972 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3973 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3974 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3975 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3976 }
3977 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3978 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3979 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3980 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003981 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003982 }
3983 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3984 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3985 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3986 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3987 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003988 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989}
3990
username5755fea2018-12-27 09:48:08 +08003991void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003993 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003994 if (--mSoundRef) return;
3995
3996 for (int i = 0; i < NUM_SOUNDS; i++) {
3997 if (mSoundPlayer[i] != 0) {
3998 mSoundPlayer[i]->disconnect();
3999 mSoundPlayer[i].clear();
4000 }
4001 }
4002}
4003
4004void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004005 ATRACE_CALL();
4006
Mathias Agopian65ab4712010-07-14 17:59:35 -07004007 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004008 if (kind < 0 || kind >= NUM_SOUNDS) {
4009 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4010 return;
4011 }
4012
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004014 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004015 sp<MediaPlayer> player = mSoundPlayer[kind];
4016 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004017 player->seekTo(0);
4018 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004019 }
4020}
4021
4022// ----------------------------------------------------------------------------
4023
4024CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004025 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004026 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004027 const std::string& clientPackageName, bool systemNativeClient,
4028 const std::optional<std::string>& clientFeatureId,
4029 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004030 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004031 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004032 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004033 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004034 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004035 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004036 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004037 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004038 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004039 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004040 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004041{
Austin Borger22c5c852024-03-08 13:31:36 -08004042 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004043 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004044
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004045 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004046
username5755fea2018-12-27 09:48:08 +08004047 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004048
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004049 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004050}
4051
Mathias Agopian65ab4712010-07-14 17:59:35 -07004052// tear down the client
4053CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004054 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004055 mDestructionStarted = true;
4056
username5755fea2018-12-27 09:48:08 +08004057 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004058 // unconditionally disconnect. function is idempotent
4059 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004060}
4061
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004062sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4063
Igor Murashkin634a5152013-02-20 17:15:11 -08004064CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004065 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004066 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004067 const std::string& clientPackageName, bool nativeClient,
4068 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004069 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004070 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004071 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004072 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004073 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004074 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4075 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004076 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004077 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004078 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004079 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004080 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004081 mRemoteBinder(remoteCallback),
4082 mOpsActive(false),
4083 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004084{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004085 if (sCameraService == nullptr) {
4086 sCameraService = cameraService;
4087 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004088
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004089 // There are 2 scenarios in which a client won't have AppOps operations
4090 // (both scenarios : native clients)
4091 // 1) It's an system native client*, the package name will be empty
4092 // and it will return from this function in the previous if condition
4093 // (This is the same as the previously existing behavior).
4094 // 2) It is a system native client, but its package name has been
4095 // modified for debugging, however it still must not use AppOps since
4096 // the package name is not a real one.
4097 //
4098 // * system native client - native client with UID < AID_APP_START. It
4099 // doesn't exclude clients not on the system partition.
4100 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004101 mAppOpsManager = std::make_unique<AppOpsManager>();
4102 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004103
Charles Chenf075f082024-03-04 23:32:55 +00004104 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004105}
4106
4107CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004108 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004109 mDestructionStarted = true;
4110}
4111
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004112binder::Status CameraService::BasicClient::disconnect() {
4113 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004114 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004115 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004116 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004117 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004118
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004119 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004120 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004121 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004122 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004123
4124 sp<IBinder> remote = getRemote();
4125 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004126 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004127 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004128
4129 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004130 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004131 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004132 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004133 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004134
Igor Murashkincba2c162013-03-20 15:56:31 -07004135 // client shouldn't be able to call into us anymore
4136 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004137
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004138 const auto& mActivityManager = getActivityManager();
4139 if (mActivityManager) {
4140 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004141 getCallingUid(),
4142 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004143 }
4144
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004145 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004146}
4147
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004148status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4149 // No dumping of clients directly over Binder,
4150 // must go through CameraService::dump
4151 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004152 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004153 return OK;
4154}
4155
Austin Borgered99f642023-06-01 16:51:35 -07004156status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004157 // Can't watch tags directly, must go through CameraService::startWatchingTags
4158 return OK;
4159}
4160
4161status_t CameraService::BasicClient::stopWatchingTags(int) {
4162 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4163 return OK;
4164}
4165
4166status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4167 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4168 return OK;
4169}
4170
Austin Borgered99f642023-06-01 16:51:35 -07004171std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004172 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004173}
4174
Emilian Peev8b64f282021-03-25 16:49:57 -07004175int CameraService::BasicClient::getCameraFacing() const {
4176 return mCameraFacing;
4177}
4178
4179int CameraService::BasicClient::getCameraOrientation() const {
4180 return mOrientation;
4181}
Ruben Brunkcc776712015-02-17 20:18:47 -08004182
4183int CameraService::BasicClient::getClientPid() const {
4184 return mClientPid;
4185}
4186
Ruben Brunk6267b532015-04-30 17:44:07 -07004187uid_t CameraService::BasicClient::getClientUid() const {
4188 return mClientUid;
4189}
4190
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004191bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4192 // Defaults to API2.
4193 return level == API_2;
4194}
4195
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004196status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004197 {
4198 Mutex::Autolock l(mAudioRestrictionLock);
4199 mAudioRestriction = mode;
4200 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004201 sCameraService->updateAudioRestriction();
4202 return OK;
4203}
4204
4205int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004206 return sCameraService->updateAudioRestriction();
4207}
4208
4209int32_t CameraService::BasicClient::getAudioRestriction() const {
4210 Mutex::Autolock l(mAudioRestrictionLock);
4211 return mAudioRestriction;
4212}
4213
4214bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4215 switch (mode) {
4216 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4217 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4218 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4219 return true;
4220 default:
4221 return false;
4222 }
4223}
4224
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004225status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4226 if (mode == AppOpsManager::MODE_ERRORED) {
4227 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004228 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004229 return PERMISSION_DENIED;
4230 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4231 // If the calling Uid is trusted (a native service), the AppOpsManager could
4232 // return MODE_IGNORED. Do not treat such case as error.
4233 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4234 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004235
4236 bool isCameraPrivacyEnabled;
4237 if (flags::camera_privacy_allowlist()) {
4238 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4239 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4240 } else {
4241 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004242 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004243 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004244 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4245 // We prefer to successfully open the camera and perform camera muting
4246 // or blocking in connectHelper as handleAppOpMode can be called before the
4247 // connection has been fully established and at that time camera muting
4248 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004249 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004250 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4251 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4252 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4253 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004254 // Return the same error as for device policy manager rejection
4255 return -EACCES;
4256 }
4257 }
4258 return OK;
4259}
4260
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004261status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004262 ATRACE_CALL();
4263
Igor Murashkine6800ce2013-03-04 17:25:57 -08004264 {
4265 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004266 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004267 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004268 if (mAppOpsManager != nullptr) {
4269 // Notify app ops that the camera is not available
4270 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004271
Austin Borger5755d9b2024-09-09 11:15:44 -07004272 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4273 toString16(mClientPackageName),
4274 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004275
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004276 // Just check for camera acccess here on open - delay startOp until
4277 // camera frames start streaming in startCameraStreamingOps
4278 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004279 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004280 status_t res = handleAppOpMode(mode);
4281 if (res != OK) {
4282 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004283 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004284 }
4285
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004286 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004287
4288 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004289 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004290
Austin Borgerdddb7552023-03-30 17:53:01 -07004291 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004292
Shuzhen Wang695044d2020-03-06 09:02:23 -08004293 // Notify listeners of camera open/close status
4294 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4295
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004296 return OK;
4297}
4298
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004299status_t CameraService::BasicClient::startCameraStreamingOps() {
4300 ATRACE_CALL();
4301
4302 if (!mOpsActive) {
4303 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4304 return INVALID_OPERATION;
4305 }
4306 if (mOpsStreaming) {
4307 ALOGV("%s: Streaming already active!", __FUNCTION__);
4308 return OK;
4309 }
4310
4311 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004312 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004313
4314 if (mAppOpsManager != nullptr) {
4315 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004316 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4317 toString16(mClientFeatureId),
4318 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004319 status_t res = handleAppOpMode(mode);
4320 if (res != OK) {
4321 return res;
4322 }
4323 }
4324
4325 mOpsStreaming = true;
4326
4327 return OK;
4328}
4329
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004330status_t CameraService::BasicClient::noteAppOp() {
4331 ATRACE_CALL();
4332
4333 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004334 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004335
4336 // noteAppOp is only used for when camera mute is not supported, in order
4337 // to trigger the sensor privacy "Unblock" dialog
4338 if (mAppOpsManager != nullptr) {
4339 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004340 toString16(mClientPackageName), toString16(mClientFeatureId),
4341 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004342 status_t res = handleAppOpMode(mode);
4343 if (res != OK) {
4344 return res;
4345 }
4346 }
4347
4348 return OK;
4349}
4350
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004351status_t CameraService::BasicClient::finishCameraStreamingOps() {
4352 ATRACE_CALL();
4353
4354 if (!mOpsActive) {
4355 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4356 return INVALID_OPERATION;
4357 }
4358 if (!mOpsStreaming) {
4359 ALOGV("%s: Streaming not active!", __FUNCTION__);
4360 return OK;
4361 }
4362
4363 if (mAppOpsManager != nullptr) {
4364 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004365 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004366 mOpsStreaming = false;
4367 }
4368
4369 return OK;
4370}
4371
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004372status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004373 ATRACE_CALL();
4374
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004375 if (mOpsStreaming) {
4376 // Make sure we've notified everyone about camera stopping
4377 finishCameraStreamingOps();
4378 }
4379
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004380 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004381 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004382 mOpsActive = false;
4383
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004384 // This function is called when a client disconnects. This should
4385 // release the camera, but actually only if it was in a proper
4386 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004387 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004388 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004389
Ruben Brunkcc776712015-02-17 20:18:47 -08004390 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004391 sCameraService->updateStatus(StatusInternal::PRESENT,
4392 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004393 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004394 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004395 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4396 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004397 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004398 mOpsCallback.clear();
4399
Austin Borgerdddb7552023-03-30 17:53:01 -07004400 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004401
Shuzhen Wang695044d2020-03-06 09:02:23 -08004402 // Notify listeners of camera open/close status
4403 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4404
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004405 return OK;
4406}
4407
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004408void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004409 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004410 if (mAppOpsManager == nullptr) {
4411 return;
4412 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004413 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004414 if (op != AppOpsManager::OP_CAMERA) {
4415 ALOGW("Unexpected app ops notification received: %d", op);
4416 return;
4417 }
4418
4419 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004420 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004421 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004422 ALOGV("checkOp returns: %d, %s ", res,
4423 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4424 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4425 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4426 "UNKNOWN");
4427
Shuzhen Wang64900852021-02-05 09:03:29 -08004428 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004429 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4430 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004431 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004432 } else if (res == AppOpsManager::MODE_IGNORED) {
4433 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004434
Austin Borgerca1e0062023-06-28 11:32:55 -07004435 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4436 // If not visible, but still active, then we want to block instead of muting the camera.
4437 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4438 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4439
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004440 bool isCameraPrivacyEnabled;
4441 if (flags::camera_privacy_allowlist()) {
4442 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4443 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4444 } else {
4445 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004446 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004447 }
4448
4449 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004450 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4451 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4452 isCameraPrivacyEnabled);
4453 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4454 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4455 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004456 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004457 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4458 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004459 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004460 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004461 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004462 }
Evan Severson09ab4002021-02-10 14:15:19 -08004463 } else if (res == AppOpsManager::MODE_ALLOWED) {
4464 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004465 }
4466}
4467
Svet Ganova453d0d2018-01-11 15:37:58 -08004468void CameraService::BasicClient::block() {
4469 ATRACE_CALL();
4470
4471 // Reset the client PID to allow server-initiated disconnect,
4472 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004473 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004474 CaptureResultExtras resultExtras; // a dummy result (invalid)
4475 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4476 disconnect();
4477}
4478
Mathias Agopian65ab4712010-07-14 17:59:35 -07004479// ----------------------------------------------------------------------------
4480
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004481void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004482 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004483 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004484 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4485 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4486 api1ErrorCode = CAMERA_ERROR_DISABLED;
4487 }
4488 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004489 } else {
4490 ALOGE("mRemoteCallback is NULL!!");
4491 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004492}
4493
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004494// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004495binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004496 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004497 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004498}
4499
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004500bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4501 return level == API_1;
4502}
4503
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004504CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4505 mClient(client) {
4506}
4507
4508void CameraService::Client::OpsCallback::opChanged(int32_t op,
4509 const String16& packageName) {
4510 sp<BasicClient> client = mClient.promote();
4511 if (client != NULL) {
4512 client->opChanged(op, packageName);
4513 }
4514}
4515
Mathias Agopian65ab4712010-07-14 17:59:35 -07004516// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004517// UidPolicy
4518// ----------------------------------------------------------------------------
4519
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004520void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004521 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004522 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004523
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004524 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004525 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004526 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004527 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004528 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4529 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004530 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004531 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004532 if (res == OK) {
4533 mRegistered = true;
4534 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004535 } else {
4536 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004537 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004538}
4539
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004540void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004541 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004542 return;
4543 }
4544
4545 registerWithActivityManager();
4546}
4547
4548void CameraService::UidPolicy::registerSelf() {
4549 // Use check service to see if the activity service is available
4550 // If not available then register for notifications, instead of blocking
4551 // till the service is ready
4552 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004553 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004554 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004555 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004556 } else {
4557 registerWithActivityManager();
4558 }
4559}
4560
Svet Ganova453d0d2018-01-11 15:37:58 -08004561void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004562 Mutex::Autolock _l(mUidLock);
4563
Steven Moreland2f348142019-07-02 15:59:07 -07004564 mAm.unregisterUidObserver(this);
4565 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004566 mRegistered = false;
4567 mActiveUids.clear();
4568 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004569}
4570
4571void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4572 onUidIdle(uid, disabled);
4573}
4574
4575void CameraService::UidPolicy::onUidActive(uid_t uid) {
4576 Mutex::Autolock _l(mUidLock);
4577 mActiveUids.insert(uid);
4578}
4579
4580void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4581 bool deleted = false;
4582 {
4583 Mutex::Autolock _l(mUidLock);
4584 if (mActiveUids.erase(uid) > 0) {
4585 deleted = true;
4586 }
4587 }
4588 if (deleted) {
4589 sp<CameraService> service = mService.promote();
4590 if (service != nullptr) {
4591 service->blockClientsForUid(uid);
4592 }
4593 }
4594}
4595
Emilian Peev53722fa2019-02-22 17:47:20 -08004596void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004597 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004598 bool procStateChange = false;
4599 {
4600 Mutex::Autolock _l(mUidLock);
4601 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4602 mMonitoredUids[uid].procState != procState) {
4603 mMonitoredUids[uid].procState = procState;
4604 procStateChange = true;
4605 }
4606 }
4607
4608 if (procStateChange) {
4609 sp<CameraService> service = mService.promote();
4610 if (service != nullptr) {
4611 service->notifyMonitoredUids();
4612 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004613 }
4614}
4615
Austin Borgerdddb7552023-03-30 17:53:01 -07004616/**
4617 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4618 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4619 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4620 * monitoredUids. If it is revised above some other monitoredUid, signal
4621 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4622 * foreground apps in split screen - state changes will capture all other cases.
4623 */
4624void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4625 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004626 {
4627 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004628 auto it = mMonitoredUids.find(uid);
4629
4630 if (it != mMonitoredUids.end()) {
4631 if (it->second.hasCamera) {
4632 for (auto &monitoredUid : mMonitoredUids) {
4633 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004634 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004635 notifyUidSet.emplace(monitoredUid.first);
4636 }
4637 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004638 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004639 notifyUidSet.emplace(uid);
4640 } else {
4641 for (auto &monitoredUid : mMonitoredUids) {
4642 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004643 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004644 notifyUidSet.emplace(uid);
4645 }
4646 }
4647 }
4648 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004649 }
4650 }
4651
Austin Borgerdddb7552023-03-30 17:53:01 -07004652 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004653 sp<CameraService> service = mService.promote();
4654 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004655 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004656 }
4657 }
4658}
4659
Austin Borgerdddb7552023-03-30 17:53:01 -07004660/**
4661 * Register a uid for monitoring, and note whether it owns a camera.
4662 */
4663void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004664 Mutex::Autolock _l(mUidLock);
4665 auto it = mMonitoredUids.find(uid);
4666 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004667 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004668 } else {
Austin Borger65577682022-02-17 00:25:43 +00004669 MonitoredUid monitoredUid;
4670 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004671 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004672 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004673 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004674 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004675 if (res != OK) {
4676 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4677 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004678 }
4679
4680 if (openCamera) {
4681 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004682 }
4683}
4684
Austin Borgerdddb7552023-03-30 17:53:01 -07004685/**
4686 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4687 */
4688void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004689 Mutex::Autolock _l(mUidLock);
4690 auto it = mMonitoredUids.find(uid);
4691 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004692 it->second.refCount--;
4693 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004694 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004695 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004696 if (res != OK) {
4697 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4698 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004699 } else if (closeCamera) {
4700 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004701 }
4702 } else {
4703 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4704 }
4705}
4706
Austin Borgered99f642023-06-01 16:51:35 -07004707bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004708 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004709 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004710}
4711
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004712static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4713static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004714
Austin Borgered99f642023-06-01 16:51:35 -07004715bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004716 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004717 // If activity manager is unreachable, assume everything is active
4718 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004719 return true;
4720 }
4721 auto it = mOverrideUids.find(uid);
4722 if (it != mOverrideUids.end()) {
4723 return it->second;
4724 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004725 bool active = mActiveUids.find(uid) != mActiveUids.end();
4726 if (!active) {
4727 // We want active UIDs to always access camera with their first attempt since
4728 // there is no guarantee the app is robustly written and would retry getting
4729 // the camera on failure. The inverse case is not a problem as we would take
4730 // camera away soon once we get the callback that the uid is no longer active.
4731 ActivityManager am;
4732 // Okay to access with a lock held as UID changes are dispatched without
4733 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004734 int64_t startTimeMillis = 0;
4735 do {
4736 // TODO: Fix this b/109950150!
4737 // Okay this is a hack. There is a race between the UID turning active and
4738 // activity being resumed. The proper fix is very risky, so we temporary add
4739 // some polling which should happen pretty rarely anyway as the race is hard
4740 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004741 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004742 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004743 if (active) {
4744 break;
4745 }
4746 if (startTimeMillis <= 0) {
4747 startTimeMillis = uptimeMillis();
4748 }
4749 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004750 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004751 if (remainingTimeMillis <= 0) {
4752 break;
4753 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004754 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4755
4756 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004757 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004758 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004759 } while (true);
4760
Svet Ganov7b4ab782018-03-25 12:48:10 -07004761 if (active) {
4762 // Now that we found out the UID is actually active, cache that
4763 mActiveUids.insert(uid);
4764 }
4765 }
4766 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004767}
4768
Varun Shahb42f1eb2019-04-16 14:45:13 -07004769int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4770 Mutex::Autolock _l(mUidLock);
4771 return getProcStateLocked(uid);
4772}
4773
4774int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4775 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4776 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004777 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004778 }
4779 return procState;
4780}
4781
Austin Borgered99f642023-06-01 16:51:35 -07004782void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4783 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004784 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004785}
4786
Austin Borgered99f642023-06-01 16:51:35 -07004787void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004788 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004789}
4790
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004791void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4792 Mutex::Autolock _l(mUidLock);
4793 ALOGV("UidPolicy: ActivityManager has died");
4794 mRegistered = false;
4795 mActiveUids.clear();
4796}
4797
Austin Borgered99f642023-06-01 16:51:35 -07004798void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004799 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004800 bool wasActive = false;
4801 bool isActive = false;
4802 {
4803 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004804 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004805 mOverrideUids.erase(uid);
4806 if (insert) {
4807 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4808 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004809 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004810 }
4811 if (wasActive != isActive && !isActive) {
4812 sp<CameraService> service = mService.promote();
4813 if (service != nullptr) {
4814 service->blockClientsForUid(uid);
4815 }
4816 }
4817}
4818
4819// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004820// SensorPrivacyPolicy
4821// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004822
4823void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4824{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004825 Mutex::Autolock _l(mSensorPrivacyLock);
4826 if (mRegistered) {
4827 return;
4828 }
Evan Severson09ab4002021-02-10 14:15:19 -08004829 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004830 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004831 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004832 mSpm.addToggleSensorPrivacyListener(this);
4833 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004834 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004835 if (flags::camera_privacy_allowlist()) {
4836 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4837 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4838 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4839 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004840 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004841 if (res == OK) {
4842 mRegistered = true;
4843 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4844 }
4845}
4846
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004847void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4848 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004849 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004850 return;
4851 }
4852
4853 registerWithSensorPrivacyManager();
4854}
4855
4856void CameraService::SensorPrivacyPolicy::registerSelf() {
4857 // Use checkservice to see if the sensor_privacy service is available
4858 // If service is not available then register for notification
4859 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004860 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004861 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004862 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004863 } else {
4864 registerWithSensorPrivacyManager();
4865 }
4866}
4867
Michael Grooverd1d435a2018-12-18 17:39:42 -08004868void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4869 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004870 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004871 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004872 mSpm.removeToggleSensorPrivacyListener(this);
4873 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004874 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004875 mRegistered = false;
4876 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4877}
4878
4879bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004880 if (!mRegistered) {
4881 registerWithSensorPrivacyManager();
4882 }
4883
Michael Grooverd1d435a2018-12-18 17:39:42 -08004884 Mutex::Autolock _l(mSensorPrivacyLock);
4885 return mSensorPrivacyEnabled;
4886}
4887
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004888int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4889 if (!mRegistered) {
4890 registerWithSensorPrivacyManager();
4891 }
4892
4893 Mutex::Autolock _l(mSensorPrivacyLock);
4894 return mCameraPrivacyState;
4895}
4896
Evan Seversond0b69922022-01-27 10:47:34 -08004897bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004898 if (!hasCameraPrivacyFeature()) {
4899 return false;
4900 }
Evan Seversond0b69922022-01-27 10:47:34 -08004901 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004902}
4903
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004904bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4905 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004906 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004907 }
4908 return mSpm.isCameraPrivacyEnabled(packageName);
4909}
4910
Evan Seversond0b69922022-01-27 10:47:34 -08004911binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004912 int toggleType, int sensor, bool enabled) {
4913 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4914 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4915 {
4916 Mutex::Autolock _l(mSensorPrivacyLock);
4917 mSensorPrivacyEnabled = enabled;
4918 }
4919 // if sensor privacy is enabled then block all clients from accessing the camera
4920 if (enabled) {
4921 sp<CameraService> service = mService.promote();
4922 if (service != nullptr) {
4923 service->blockAllClients();
4924 }
4925 }
4926 }
4927 return binder::Status::ok();
4928}
4929
4930binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4931 int, int sensor, int state) {
4932 if (!flags::camera_privacy_allowlist()
4933 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4934 return binder::Status::ok();
4935 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004936 {
4937 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004938 mCameraPrivacyState = state;
4939 }
4940 sp<CameraService> service = mService.promote();
4941 if (!service) {
4942 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004943 }
4944 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004945 if (state == SensorPrivacyManager::ENABLED) {
4946 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004947 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004948 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004949 }
4950 return binder::Status::ok();
4951}
4952
4953void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4954 Mutex::Autolock _l(mSensorPrivacyLock);
4955 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4956 mRegistered = false;
4957}
4958
Evan Severson09ab4002021-02-10 14:15:19 -08004959bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004960 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4961 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4962 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4963 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4964 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004965}
4966
Michael Grooverd1d435a2018-12-18 17:39:42 -08004967// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004968// CameraState
4969// ----------------------------------------------------------------------------
4970
Austin Borgered99f642023-06-01 16:51:35 -07004971CameraService::CameraState::CameraState(const std::string& id, int cost,
4972 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004973 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004974 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004975 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004976
4977CameraService::CameraState::~CameraState() {}
4978
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004979CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004980 Mutex::Autolock lock(mStatusLock);
4981 return mStatus;
4982}
4983
Austin Borgered99f642023-06-01 16:51:35 -07004984std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004985 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004986 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004987 return res;
4988}
4989
Ruben Brunkcc776712015-02-17 20:18:47 -08004990CameraParameters CameraService::CameraState::getShimParams() const {
4991 return mShimParams;
4992}
4993
4994void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4995 mShimParams = params;
4996}
4997
4998int CameraService::CameraState::getCost() const {
4999 return mCost;
5000}
5001
Austin Borgered99f642023-06-01 16:51:35 -07005002std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005003 return mConflicting;
5004}
5005
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005006SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5007 return mSystemCameraKind;
5008}
5009
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005010bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5011 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5012 != mPhysicalCameras.end();
5013}
5014
Austin Borgered99f642023-06-01 16:51:35 -07005015bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005016 Mutex::Autolock lock(mStatusLock);
5017 auto result = mUnavailablePhysicalIds.insert(physicalId);
5018 return result.second;
5019}
5020
Austin Borgered99f642023-06-01 16:51:35 -07005021bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005022 Mutex::Autolock lock(mStatusLock);
5023 auto count = mUnavailablePhysicalIds.erase(physicalId);
5024 return count > 0;
5025}
5026
Austin Borgered99f642023-06-01 16:51:35 -07005027void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005028 Mutex::Autolock lock(mStatusLock);
5029 mClientPackage = clientPackage;
5030}
5031
Austin Borgered99f642023-06-01 16:51:35 -07005032std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005033 Mutex::Autolock lock(mStatusLock);
5034 return mClientPackage;
5035}
5036
Ruben Brunkcc776712015-02-17 20:18:47 -08005037// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005038// ClientEventListener
5039// ----------------------------------------------------------------------------
5040
5041void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005042 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005043 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005044 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005045 if (basicClient.get() != nullptr) {
5046 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005047 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005048 static_cast<int>(basicClient->getClientUid()));
5049 }
5050}
5051
5052void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005053 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005054 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005055 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005056 if (basicClient.get() != nullptr) {
5057 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005058 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005059 static_cast<int>(basicClient->getClientUid()));
5060 }
5061}
5062
Ruben Brunk99e69712015-05-26 17:25:07 -07005063// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005064// CameraClientManager
5065// ----------------------------------------------------------------------------
5066
Ruben Brunk99e69712015-05-26 17:25:07 -07005067CameraService::CameraClientManager::CameraClientManager() {
5068 setListener(std::make_shared<ClientEventListener>());
5069}
5070
Ruben Brunkcc776712015-02-17 20:18:47 -08005071CameraService::CameraClientManager::~CameraClientManager() {}
5072
5073sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005074 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005075 auto descriptor = get(id);
5076 if (descriptor == nullptr) {
5077 return sp<BasicClient>{nullptr};
5078 }
5079 return descriptor->getValue();
5080}
5081
Austin Borgered99f642023-06-01 16:51:35 -07005082std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005083 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005084 std::ostringstream ret;
5085 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005086 bool hasAny = false;
5087 for (auto& i : all) {
5088 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005089 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005090 int32_t cost = i->getCost();
5091 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005092 int32_t score = i->getPriority().getScore();
5093 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005094 auto conflicting = i->getConflicting();
5095 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005096 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005097 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005098 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005099 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005100 uid_t clientUid = clientSp->getClientUid();
5101 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005102 }
Austin Borgered99f642023-06-01 16:51:35 -07005103 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5104 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005105
Ruben Brunk6267b532015-04-30 17:44:07 -07005106 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005107 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005108 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005109 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005110 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005111 }
5112
Austin Borgered99f642023-06-01 16:51:35 -07005113 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005114 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005115 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005116 }
Austin Borgered99f642023-06-01 16:51:35 -07005117 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005118 }
Austin Borgered99f642023-06-01 16:51:35 -07005119 if (hasAny) ret << "\n";
5120 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005121 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005122}
5123
5124CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005125 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5126 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005127 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005128
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005129 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005130 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005131
Austin Borgered99f642023-06-01 16:51:35 -07005132 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005133 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5134 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005135}
5136
5137CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005138 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005139 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005140 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005141 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005142 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5143 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005144}
5145
5146// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005147// InjectionStatusListener
5148// ----------------------------------------------------------------------------
5149
5150void CameraService::InjectionStatusListener::addListener(
5151 const sp<ICameraInjectionCallback>& callback) {
5152 Mutex::Autolock lock(mListenerLock);
5153 if (mCameraInjectionCallback) return;
5154 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5155 if (res == OK) {
5156 mCameraInjectionCallback = callback;
5157 }
5158}
5159
5160void CameraService::InjectionStatusListener::removeListener() {
5161 Mutex::Autolock lock(mListenerLock);
5162 if (mCameraInjectionCallback == nullptr) {
5163 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5164 return;
5165 }
5166 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5167 mCameraInjectionCallback = nullptr;
5168}
5169
5170void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005171 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005172 if (mCameraInjectionCallback == nullptr) {
5173 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5174 return;
5175 }
Cliff Wud3a05312021-04-26 23:07:31 +08005176
5177 switch (err) {
5178 case -ENODEV:
5179 mCameraInjectionCallback->onInjectionError(
5180 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5181 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005182 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005183 break;
5184 case -EBUSY:
5185 mCameraInjectionCallback->onInjectionError(
5186 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5187 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005188 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005189 break;
5190 case DEAD_OBJECT:
5191 mCameraInjectionCallback->onInjectionError(
5192 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5193 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005194 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005195 break;
5196 case INVALID_OPERATION:
5197 mCameraInjectionCallback->onInjectionError(
5198 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5199 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005200 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005201 break;
5202 case UNKNOWN_TRANSACTION:
5203 mCameraInjectionCallback->onInjectionError(
5204 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5205 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005206 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005207 break;
5208 default:
5209 mCameraInjectionCallback->onInjectionError(
5210 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5211 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005212 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005213 }
Cliff Wud8cae102021-03-11 01:37:42 +08005214}
5215
5216void CameraService::InjectionStatusListener::binderDied(
5217 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005218 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5219 auto parent = mParent.promote();
5220 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005221 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5222 if (clientDescriptor != nullptr) {
5223 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5224 baseClientPtr->stopInjection();
5225 }
Cliff Wu3b268182021-07-06 15:44:43 +08005226 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005227 }
5228}
5229
5230// ----------------------------------------------------------------------------
5231// CameraInjectionSession
5232// ----------------------------------------------------------------------------
5233
5234binder::Status CameraService::CameraInjectionSession::stopInjection() {
5235 Mutex::Autolock lock(mInjectionSessionLock);
5236 auto parent = mParent.promote();
5237 if (parent == nullptr) {
5238 ALOGE("CameraInjectionSession: Parent is gone");
5239 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5240 "Camera service encountered error");
5241 }
Cliff Wud3a05312021-04-26 23:07:31 +08005242
5243 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005244 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5245 if (clientDescriptor != nullptr) {
5246 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5247 res = baseClientPtr->stopInjection();
5248 if (res != OK) {
5249 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5250 " ret != NO_ERROR: %d", res);
5251 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5252 "Camera session encountered error");
5253 }
5254 }
Cliff Wu3b268182021-07-06 15:44:43 +08005255 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005256 return binder::Status::ok();
5257}
5258
5259// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005260
5261static const int kDumpLockRetries = 50;
5262static const int kDumpLockSleep = 60000;
5263
5264static bool tryLock(Mutex& mutex)
5265{
5266 bool locked = false;
5267 for (int i = 0; i < kDumpLockRetries; ++i) {
5268 if (mutex.tryLock() == NO_ERROR) {
5269 locked = true;
5270 break;
5271 }
5272 usleep(kDumpLockSleep);
5273 }
5274 return locked;
5275}
5276
Rucha Katakwardf223072021-06-15 10:21:00 -07005277void CameraService::cacheDump() {
5278 if (mMemFd != -1) {
5279 const Vector<String16> args;
5280 ATRACE_CALL();
5281 // Acquiring service lock here will avoid the deadlock since
5282 // cacheDump will not be called during the second disconnect.
5283 Mutex::Autolock lock(mServiceLock);
5284
5285 Mutex::Autolock l(mCameraStatesLock);
5286 // Start collecting the info for open sessions and store it in temp file.
5287 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005288 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005289 auto clientDescriptor = mActiveClientManager.get(cameraId);
5290 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005291 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005292 // Log the current open session info before device is disconnected.
5293 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5294 }
5295 }
5296 }
5297}
5298
Mathias Agopian65ab4712010-07-14 17:59:35 -07005299status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005300 ATRACE_CALL();
5301
Austin Borgered99f642023-06-01 16:51:35 -07005302 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005303 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005304 getCallingPid(),
5305 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005306 return NO_ERROR;
5307 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005308 bool locked = tryLock(mServiceLock);
5309 // failed to lock - CameraService is probably deadlocked
5310 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005311 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005312 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005313
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005314 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005315 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005316
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005317 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005318 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005319
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005320 if (locked) mServiceLock.unlock();
5321 return NO_ERROR;
5322 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005323 dprintf(fd, "\n== Service global info: ==\n\n");
5324 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005325 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005326 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5327 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005328 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5329 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5330 }
Austin Borgered99f642023-06-01 16:51:35 -07005331 std::string activeClientString = mActiveClientManager.toString();
5332 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5333 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005334 if (mStreamUseCaseOverrides.size() > 0) {
5335 dprintf(fd, "Active stream use case overrides:");
5336 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5337 dprintf(fd, " %" PRId64, useCaseOverride);
5338 }
5339 dprintf(fd, "\n");
5340 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005341
5342 dumpEventLog(fd);
5343
5344 bool stateLocked = tryLock(mCameraStatesLock);
5345 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005346 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005347 }
5348
Emilian Peevbd8c5032018-02-14 23:05:40 +00005349 int argSize = args.size();
5350 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005351 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005352 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005353 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005354 }
5355 break;
5356 }
5357 }
5358
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005359 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005360 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005361
Austin Borgered99f642023-06-01 16:51:35 -07005362 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005363
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005364 CameraParameters p = state.second->getShimParams();
5365 if (!p.isEmpty()) {
5366 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5367 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005368 }
5369
5370 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005371 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005372 // log the current open session info
5373 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005374 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005375 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005376 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005377
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005378 }
5379
5380 if (stateLocked) mCameraStatesLock.unlock();
5381
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005382 if (locked) mServiceLock.unlock();
5383
Emilian Peevf53f66e2017-04-11 14:29:43 +01005384 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005385
5386 dprintf(fd, "\n== Vendor tags: ==\n\n");
5387
5388 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5389 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005390 sp<VendorTagDescriptorCache> cache =
5391 VendorTagDescriptorCache::getGlobalVendorTagCache();
5392 if (cache == NULL) {
5393 dprintf(fd, "No vendor tags.\n");
5394 } else {
5395 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5396 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005397 } else {
5398 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5399 }
5400
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005401 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005402 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005403 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005404
5405 // Process dump arguments, if any
5406 int n = args.size();
5407 String16 verboseOption("-v");
5408 String16 unreachableOption("--unreachable");
5409 for (int i = 0; i < n; i++) {
5410 if (args[i] == verboseOption) {
5411 // change logging level
5412 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005413 std::string levelStr = toStdString(args[i+1]);
5414 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005415 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005416 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005417 } else if (args[i] == unreachableOption) {
5418 // Dump memory analysis
5419 // TODO - should limit be an argument parameter?
5420 UnreachableMemoryInfo info;
5421 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5422 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005423 dprintf(fd, "\n== Unable to dump unreachable memory. "
5424 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005425 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005426 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005427 std::string s = info.ToString(/*log_contents*/ true);
5428 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005429 }
5430 }
5431 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005432
5433 bool serviceLocked = tryLock(mServiceLock);
5434
5435 // Dump info from previous open sessions.
5436 // Reposition the offset to beginning of the file before reading
5437
5438 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5439 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5440 ssize_t size_read;
5441 char buf[4096];
5442 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5443 // Read data from file to a small buffer and write it to fd.
5444 write(fd, buf, size_read);
5445 if (size_read == -1) {
5446 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5447 break;
5448 }
5449 }
5450 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5451 } else {
5452 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5453 }
5454
5455 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005456 return NO_ERROR;
5457}
5458
Rucha Katakwardf223072021-06-15 10:21:00 -07005459void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005460 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005461 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005462 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005463 getFormattedCurrentTime().c_str(),
5464 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005465 dprintf(fd, " Client priority score: %d state: %d\n",
5466 clientDescriptor->getPriority().getScore(),
5467 clientDescriptor->getPriority().getState());
5468 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5469
5470 auto client = clientDescriptor->getValue();
5471 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005472 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005473
5474 client->dumpClient(fd, args);
5475}
5476
Austin Borgered99f642023-06-01 16:51:35 -07005477void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005478 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005479 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005480}
5481
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005482void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005483 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005484
5485 Mutex::Autolock l(mLogLock);
5486 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005487 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005488 }
5489
5490 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005491 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005492 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005493 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005494 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005495 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005496}
5497
Austin Borgered99f642023-06-01 16:51:35 -07005498void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005499 Mutex::Autolock lock(mLogLock);
5500 if (!isClientWatchedLocked(client)) { return; }
5501
5502 std::vector<std::string> dumpVector;
5503 client->dumpWatchedEventsToVector(dumpVector);
5504
5505 if (dumpVector.empty()) { return; }
5506
Austin Borgered99f642023-06-01 16:51:35 -07005507 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005508
Austin Borgered99f642023-06-01 16:51:35 -07005509 std::string currentTime = getFormattedCurrentTime();
5510 dumpString << "Cached @ ";
5511 dumpString << currentTime;
5512 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005513
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005514 size_t i = dumpVector.size();
5515
5516 // Store the string in reverse order (latest last)
5517 while (i > 0) {
5518 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005519 dumpString << cameraId;
5520 dumpString << ":";
5521 dumpString << client->getPackageName();
5522 dumpString << " ";
5523 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005524 }
5525
Austin Borgered99f642023-06-01 16:51:35 -07005526 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005527}
5528
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005529void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005530 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005531 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5532 if (mTorchClientMap[i] == who) {
5533 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005534 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005535 status_t res = mFlashlight->setTorchMode(cameraId, false);
5536 if (res) {
5537 ALOGE("%s: torch client died but couldn't turn off torch: "
5538 "%s (%d)", __FUNCTION__, strerror(-res), res);
5539 return;
5540 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005541 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005542 break;
5543 }
5544 }
5545}
5546
Ruben Brunkcc776712015-02-17 20:18:47 -08005547/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005548
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005549 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005550 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5551 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005552 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005553 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005554 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005555
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005556 // check torch client
5557 handleTorchClientBinderDied(who);
5558
5559 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005560 if(!evictClientIdByRemote(who)) {
5561 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005562 return;
5563 }
5564
Ruben Brunkcc776712015-02-17 20:18:47 -08005565 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5566 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005567}
5568
Austin Borgered99f642023-06-01 16:51:35 -07005569void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005570 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005571}
5572
Austin Borgered99f642023-06-01 16:51:35 -07005573void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005574 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005575 // Do not lock mServiceLock here or can get into a deadlock from
5576 // connect() -> disconnect -> updateStatus
5577
5578 auto state = getCameraState(cameraId);
5579
5580 if (state == nullptr) {
5581 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005582 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005583 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005584 }
5585
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005586 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5587 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5588 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005589 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005590 return;
5591 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005592
Biswarup Pal37a75182024-01-16 15:53:35 +00005593 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5594 CameraMetadata cameraInfo;
5595 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005596 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005597 if (res != OK) {
5598 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5599 __FUNCTION__, cameraId.c_str());
5600 } else {
5601 int32_t deviceId = getDeviceId(cameraInfo);
5602 if (deviceId != kDefaultDeviceId) {
5603 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5604 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5605 static_cast<camera_metadata_enum_android_lens_facing_t>(
5606 lensFacingEntry.data.u8[0]);
5607 std::string mappedCameraId;
5608 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5609 mappedCameraId = kVirtualDeviceBackCameraId;
5610 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5611 mappedCameraId = kVirtualDeviceFrontCameraId;
5612 } else {
5613 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5614 __func__);
5615 }
5616 if (!mappedCameraId.empty()) {
5617 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5618 }
5619 }
5620 }
5621 }
5622
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005623 // Collect the logical cameras without holding mStatusLock in updateStatus
5624 // as that can lead to a deadlock(b/162192331).
5625 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005626 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005627 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005628 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005629 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005630 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005631 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5632 auto [deviceId, mappedCameraId] =
5633 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005634
Biswarup Pal37a75182024-01-16 15:53:35 +00005635 if (status != StatusInternal::ENUMERATING) {
5636 // Update torch status if it has a flash unit.
5637 Mutex::Autolock al(mTorchStatusMutex);
5638 TorchModeStatus torchStatus;
5639 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5640 NAME_NOT_FOUND) {
5641 TorchModeStatus newTorchStatus =
5642 status == StatusInternal::PRESENT ?
5643 TorchModeStatus::AVAILABLE_OFF :
5644 TorchModeStatus::NOT_AVAILABLE;
5645 if (torchStatus != newTorchStatus) {
5646 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5647 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005648 }
5649 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005650
Biswarup Pal37a75182024-01-16 15:53:35 +00005651 Mutex::Autolock lock(mStatusListenerLock);
5652 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5653 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005654
Biswarup Pal37a75182024-01-16 15:53:35 +00005655 for (auto& listener : mListenerList) {
5656 bool isVendorListener = listener->isVendorListener();
5657 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5658 listener->getListenerPid(), listener->getListenerUid())) {
5659 ALOGV("Skipping discovery callback for system-only camera device %s",
5660 cameraId.c_str());
5661 continue;
5662 }
5663
5664 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5665 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005666 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005667 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005668 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5669 ret.exceptionCode());
5670 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005671 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005672}
5673
Austin Borgered99f642023-06-01 16:51:35 -07005674void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5675 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005676 auto state = getCameraState(cameraId);
5677 if (state == nullptr) {
5678 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005679 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005680 return;
5681 }
5682 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005683 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005684 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005685 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005686 }
5687
Biswarup Pal37a75182024-01-16 15:53:35 +00005688 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5689 auto [deviceId, mappedCameraId] =
5690 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5691
Shuzhen Wang695044d2020-03-06 09:02:23 -08005692 Mutex::Autolock lock(mStatusListenerLock);
5693
5694 for (const auto& it : mListenerList) {
5695 if (!it->isOpenCloseCallbackAllowed()) {
5696 continue;
5697 }
5698
5699 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005700 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005701 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5702 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005703 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005704 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005705 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005706
5707 it->handleBinderStatus(ret,
5708 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5709 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005710 }
5711}
5712
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005713template<class Func>
5714void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005715 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005716 std::initializer_list<StatusInternal> rejectSourceStates,
5717 Func onStatusUpdatedLocked) {
5718 Mutex::Autolock lock(mStatusLock);
5719 StatusInternal oldStatus = mStatus;
5720 mStatus = status;
5721
5722 if (oldStatus == status) {
5723 return;
5724 }
5725
5726 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005727 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005728
5729 if (oldStatus == StatusInternal::NOT_PRESENT &&
5730 (status != StatusInternal::PRESENT &&
5731 status != StatusInternal::ENUMERATING)) {
5732
5733 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5734 __FUNCTION__);
5735 mStatus = oldStatus;
5736 return;
5737 }
5738
5739 /**
5740 * Sometimes we want to conditionally do a transition.
5741 * For example if a client disconnects, we want to go to PRESENT
5742 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5743 */
5744 for (auto& rejectStatus : rejectSourceStates) {
5745 if (oldStatus == rejectStatus) {
5746 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005747 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005748 mStatus = oldStatus;
5749 return;
5750 }
5751 }
5752
5753 onStatusUpdatedLocked(cameraId, status);
5754}
5755
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005756status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005757 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005758 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005759 if (!status) {
5760 return BAD_VALUE;
5761 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005762 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5763 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005764 // invalid camera ID or the camera doesn't have a flash unit
5765 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005766 }
5767
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005768 *status = mTorchStatusMap.valueAt(index);
5769 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005770}
5771
Austin Borgered99f642023-06-01 16:51:35 -07005772status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005773 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005774 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5775 if (index == NAME_NOT_FOUND) {
5776 return BAD_VALUE;
5777 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005778 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005779
5780 return OK;
5781}
5782
Austin Borgered99f642023-06-01 16:51:35 -07005783std::list<std::string> CameraService::getLogicalCameras(
5784 const std::string& physicalCameraId) {
5785 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005786 Mutex::Autolock lock(mCameraStatesLock);
5787 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005788 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5789 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005790 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005791 }
5792 return retList;
5793}
5794
5795void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005796 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005797 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005798 // mStatusListenerLock is expected to be locked
5799 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005800 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005801 // Note: we check only the deviceKind of the physical camera id
5802 // since, logical camera ids and their physical camera ids are
5803 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005804 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5805 listener->getListenerPid(), listener->getListenerUid())) {
5806 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005807 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005808 continue;
5809 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005810 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005811 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005812 listener->handleBinderStatus(ret,
5813 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5814 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5815 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005816 }
5817 }
5818}
5819
Svet Ganova453d0d2018-01-11 15:37:58 -08005820void CameraService::blockClientsForUid(uid_t uid) {
5821 const auto clients = mActiveClientManager.getAll();
5822 for (auto& current : clients) {
5823 if (current != nullptr) {
5824 const auto basicClient = current->getValue();
5825 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5826 basicClient->block();
5827 }
5828 }
5829 }
5830}
5831
Michael Grooverd1d435a2018-12-18 17:39:42 -08005832void CameraService::blockAllClients() {
5833 const auto clients = mActiveClientManager.getAll();
5834 for (auto& current : clients) {
5835 if (current != nullptr) {
5836 const auto basicClient = current->getValue();
5837 if (basicClient.get() != nullptr) {
5838 basicClient->block();
5839 }
5840 }
5841 }
5842}
5843
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005844void CameraService::blockPrivacyEnabledClients() {
5845 const auto clients = mActiveClientManager.getAll();
5846 for (auto& current : clients) {
5847 if (current != nullptr) {
5848 const auto basicClient = current->getValue();
5849 if (basicClient.get() != nullptr) {
5850 std::string pkgName = basicClient->getPackageName();
5851 bool cameraPrivacyEnabled =
5852 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5853 if (cameraPrivacyEnabled) {
5854 basicClient->block();
5855 }
5856 }
5857 }
5858 }
5859}
5860
Svet Ganova453d0d2018-01-11 15:37:58 -08005861// NOTE: This is a remote API - make sure all args are validated
5862status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005863 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005864 return PERMISSION_DENIED;
5865 }
5866 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5867 return BAD_VALUE;
5868 }
Austin Borgered99f642023-06-01 16:51:35 -07005869 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005870 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005871 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005872 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005873 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005874 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005875 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005876 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005877 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005878 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005879 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005880 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005881 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005882 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005883 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005884 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005885 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005886 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005887 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005888 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005889 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005890 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005891 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005892 handleClearStreamUseCaseOverrides();
5893 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005894 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005895 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005896 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005897 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005898 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005899 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005900 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005901 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005902 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005903 }
5904 printHelp(err);
5905 return BAD_VALUE;
5906}
5907
5908status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005909 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005910
Svet Ganova453d0d2018-01-11 15:37:58 -08005911 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005912 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005913 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005914 } else if ((args[2] != toString16("idle"))) {
5915 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005916 return BAD_VALUE;
5917 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005918
5919 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005920 if (args.size() >= 5 && args[3] == toString16("--user")) {
5921 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005922 }
5923
5924 uid_t uid;
5925 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5926 return BAD_VALUE;
5927 }
5928
5929 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005930 return NO_ERROR;
5931}
5932
5933status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005934 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005935
5936 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005937 if (args.size() >= 4 && args[2] == toString16("--user")) {
5938 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005939 }
5940
5941 uid_t uid;
5942 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005943 return BAD_VALUE;
5944 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005945
5946 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005947 return NO_ERROR;
5948}
5949
5950status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005951 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005952
5953 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005954 if (args.size() >= 4 && args[2] == toString16("--user")) {
5955 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005956 }
5957
5958 uid_t uid;
5959 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005960 return BAD_VALUE;
5961 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005962
5963 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005964 return dprintf(out, "active\n");
5965 } else {
5966 return dprintf(out, "idle\n");
5967 }
5968}
5969
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005970status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005971 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005972 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5973 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5974 Mutex::Autolock lock(mServiceLock);
5975
5976 mOverrideRotateAndCropMode = rotateValue;
5977
5978 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5979
5980 const auto clients = mActiveClientManager.getAll();
5981 for (auto& current : clients) {
5982 if (current != nullptr) {
5983 const auto basicClient = current->getValue();
5984 if (basicClient.get() != nullptr) {
5985 basicClient->setRotateAndCropOverride(rotateValue);
5986 }
5987 }
5988 }
5989
5990 return OK;
5991}
5992
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005993status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5994 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005995 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005996 if ((*end != '\0') ||
5997 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5998 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5999 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6000 return BAD_VALUE;
6001 }
6002
6003 Mutex::Autolock lock(mServiceLock);
6004 mOverrideAutoframingMode = autoframingValue;
6005
6006 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6007
6008 const auto clients = mActiveClientManager.getAll();
6009 for (auto& current : clients) {
6010 if (current != nullptr) {
6011 const auto basicClient = current->getValue();
6012 if (basicClient.get() != nullptr) {
6013 basicClient->setAutoframingOverride(autoframingValue);
6014 }
6015 }
6016 }
6017
6018 return OK;
6019}
6020
Ravneetaeb20dc2022-03-30 05:33:03 +00006021status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006022 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006023
6024 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6025
6026 Mutex::Autolock lock(mServiceLock);
6027
6028 mCameraServiceWatchdogEnabled = enableWatchdog;
6029
6030 const auto clients = mActiveClientManager.getAll();
6031 for (auto& current : clients) {
6032 if (current != nullptr) {
6033 const auto basicClient = current->getValue();
6034 if (basicClient.get() != nullptr) {
6035 basicClient->setCameraServiceWatchdog(enableWatchdog);
6036 }
6037 }
6038 }
6039
6040 return OK;
6041}
6042
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006043status_t CameraService::handleGetRotateAndCrop(int out) {
6044 Mutex::Autolock lock(mServiceLock);
6045
6046 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6047}
6048
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006049status_t CameraService::handleGetAutoframing(int out) {
6050 Mutex::Autolock lock(mServiceLock);
6051
6052 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6053}
6054
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006055status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6056 char *endPtr;
6057 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006058 std::string maskString = toStdString(args[1]);
6059 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006060
6061 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006062 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006063 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6064
6065 Mutex::Autolock lock(mServiceLock);
6066
6067 mImageDumpMask = maskValue;
6068
6069 return OK;
6070}
6071
6072status_t CameraService::handleGetImageDumpMask(int out) {
6073 Mutex::Autolock lock(mServiceLock);
6074
6075 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6076}
6077
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006078status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006079 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006080 if (errno != 0) return BAD_VALUE;
6081
6082 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6083 Mutex::Autolock lock(mServiceLock);
6084
6085 mOverrideCameraMuteMode = (muteValue == 1);
6086
6087 const auto clients = mActiveClientManager.getAll();
6088 for (auto& current : clients) {
6089 if (current != nullptr) {
6090 const auto basicClient = current->getValue();
6091 if (basicClient.get() != nullptr) {
6092 if (basicClient->supportsCameraMute()) {
6093 basicClient->setCameraMute(mOverrideCameraMuteMode);
6094 }
6095 }
6096 }
6097 }
6098
6099 return OK;
6100}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006101
Shuzhen Wang16610a62022-12-15 22:38:07 -08006102status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6103 std::vector<int64_t> useCasesOverride;
6104 for (size_t i = 1; i < args.size(); i++) {
6105 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006106 std::string arg = toStdString(args[i]);
6107 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006108 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006109 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006110 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006111 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006112 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006113 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006114 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006115 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006116 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006117 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006118 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006119 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006120 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6121 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006122 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006123 return BAD_VALUE;
6124 }
6125 useCasesOverride.push_back(useCase);
6126 }
6127
6128 Mutex::Autolock lock(mServiceLock);
6129 mStreamUseCaseOverrides = std::move(useCasesOverride);
6130
6131 return OK;
6132}
6133
6134void CameraService::handleClearStreamUseCaseOverrides() {
6135 Mutex::Autolock lock(mServiceLock);
6136 mStreamUseCaseOverrides.clear();
6137}
6138
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006139status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6140 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006141 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006142 if ((*end != '\0') ||
6143 (zoomOverrideValue != -1 &&
6144 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6145 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6146 return BAD_VALUE;
6147 }
6148
6149 Mutex::Autolock lock(mServiceLock);
6150 mZoomOverrideValue = zoomOverrideValue;
6151
6152 const auto clients = mActiveClientManager.getAll();
6153 for (auto& current : clients) {
6154 if (current != nullptr) {
6155 const auto basicClient = current->getValue();
6156 if (basicClient.get() != nullptr) {
6157 if (basicClient->supportsZoomOverride()) {
6158 basicClient->setZoomOverride(mZoomOverrideValue);
6159 }
6160 }
6161 }
6162 }
6163
6164 return OK;
6165}
6166
Avichal Rakesh84147132021-11-11 17:47:11 -08006167status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006168 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006169 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006170 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006171 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006172 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006173 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006174 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006175 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006176 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006177 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006178 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006179 dprintf(outFd, "Camera service watch commands:\n"
6180 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6181 " starts watching the provided tags for clients with provided package\n"
6182 " recognizes tag shorthands like '3a'\n"
6183 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006184 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006185 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006186 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006187 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006188 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006189 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006190 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006191}
6192
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006193status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6194 Mutex::Autolock lock(mLogLock);
6195 size_t tagsIdx; // index of '-m'
6196 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006197 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006198 if (tagsIdx < args.size() - 1) {
6199 tags = args[tagsIdx + 1];
6200 } else {
6201 dprintf(outFd, "No tags provided.\n");
6202 return BAD_VALUE;
6203 }
6204
6205 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006206 // watch all clients if no clients are provided
6207 String16 clients = toString16(kWatchAllClientsFlag);
6208 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006209 clientsIdx++);
6210 if (clientsIdx < args.size() - 1) {
6211 clients = args[clientsIdx + 1];
6212 }
Austin Borgered99f642023-06-01 16:51:35 -07006213 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006214
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006215 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006216 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006217
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006218 bool serviceLock = tryLock(mServiceLock);
6219 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006220 auto cameraClients = mActiveClientManager.getAll();
6221 for (const auto &clientDescriptor: cameraClients) {
6222 if (clientDescriptor == nullptr) { continue; }
6223 sp<BasicClient> client = clientDescriptor->getValue();
6224 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006225
6226 if (isClientWatchedLocked(client.get())) {
6227 client->startWatchingTags(mMonitorTags, outFd);
6228 numWatchedClients++;
6229 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006230 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006231 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6232
6233 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006234 return OK;
6235}
6236
6237status_t CameraService::stopWatchingTags(int outFd) {
6238 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006239 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006240 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006241
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006242 mWatchedClientPackages.clear();
6243 mWatchedClientsDumpCache.clear();
6244
6245 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006246 auto cameraClients = mActiveClientManager.getAll();
6247 for (const auto &clientDescriptor : cameraClients) {
6248 if (clientDescriptor == nullptr) { continue; }
6249 sp<BasicClient> client = clientDescriptor->getValue();
6250 if (client.get() == nullptr) { continue; }
6251 client->stopWatchingTags(outFd);
6252 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006253 dprintf(outFd, "Stopped watching all clients.\n");
6254 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006255 return OK;
6256}
6257
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006258status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6259 Mutex::Autolock lock(mLogLock);
6260 size_t clearedSize = mWatchedClientsDumpCache.size();
6261 mWatchedClientsDumpCache.clear();
6262 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6263 return OK;
6264}
6265
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006266status_t CameraService::printWatchedTags(int outFd) {
6267 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006268 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006269
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006270 bool printedSomething = false; // tracks if any monitoring information was printed
6271 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006272
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006273 bool serviceLock = tryLock(mServiceLock);
6274 // get all watched clients that are currently connected
6275 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6276 if (clientDescriptor == nullptr) { continue; }
6277
6278 sp<BasicClient> client = clientDescriptor->getValue();
6279 if (client.get() == nullptr) { continue; }
6280 if (!isClientWatchedLocked(client.get())) { continue; }
6281
6282 std::vector<std::string> dumpVector;
6283 client->dumpWatchedEventsToVector(dumpVector);
6284
6285 size_t printIdx = dumpVector.size();
6286 if (printIdx == 0) {
6287 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006288 }
6289
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006290 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006291 const std::string &cameraId = clientDescriptor->getKey();
6292 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006293 while(printIdx > 0) {
6294 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006295 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006296 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006297 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006298 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006299 printedSomething = true;
6300
6301 connectedMonitoredClients.emplace(client->getPackageName());
6302 }
6303 if (serviceLock) { mServiceLock.unlock(); }
6304
6305 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6306 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006307 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006308 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6309 continue;
6310 }
6311
Austin Borgered99f642023-06-01 16:51:35 -07006312 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006313 dprintf(outFd, "%s\n", kv.second.c_str());
6314 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006315 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006316
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006317 if (!printedSomething) {
6318 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006319 }
6320
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006321 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006322}
6323
Avichal Rakesh84147132021-11-11 17:47:11 -08006324// Print all events in vector `events' that came after lastPrintedEvent
6325void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006326 const std::string &cameraId,
6327 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006328 const std::vector<std::string> &events,
6329 const std::string &lastPrintedEvent) {
6330 if (events.empty()) { return; }
6331
6332 // index of lastPrintedEvent in events.
6333 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6334 size_t lastPrintedIdx;
6335 for (lastPrintedIdx = 0;
6336 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6337 lastPrintedIdx++);
6338
6339 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6340
Avichal Rakesh84147132021-11-11 17:47:11 -08006341 // print events in chronological order (latest event last)
6342 size_t idxToPrint = lastPrintedIdx;
6343 do {
6344 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006345 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6346 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006347 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006348}
6349
6350// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6351// command should be interrupted if the user presses the return key, or if user loses any way to
6352// signal interrupt.
6353// If timeoutMs == 0, this function will always return false
6354bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6355 struct timeval startTime;
6356 int startTimeError = gettimeofday(&startTime, nullptr);
6357 if (startTimeError) {
6358 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6359 return true;
6360 }
6361
6362 const nfds_t numFds = 1;
6363 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6364
6365 struct timeval currTime;
6366 char buffer[2];
6367 while(true) {
6368 int currTimeError = gettimeofday(&currTime, nullptr);
6369 if (currTimeError) {
6370 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6371 return true;
6372 }
6373
6374 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6375 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6376 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6377
6378 if (remainingTimeMs <= 0) {
6379 // No user interrupt within timeoutMs, don't interrupt watch command
6380 return false;
6381 }
6382
6383 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6384 if (numFdsUpdated < 0) {
6385 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6386 return true;
6387 }
6388
6389 if (numFdsUpdated == 0) {
6390 // No user input within timeoutMs, don't interrupt watch command
6391 return false;
6392 }
6393
6394 if (!(pollFd.revents & POLLIN)) {
6395 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6396 return true;
6397 }
6398
6399 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6400 if (sizeRead < 0) {
6401 dprintf(outFd, "Error reading user input. Exiting.\n");
6402 return true;
6403 }
6404
6405 if (sizeRead == 0) {
6406 // Reached end of input fd (can happen if input is piped)
6407 // User has no way to signal an interrupt, so interrupt here
6408 return true;
6409 }
6410
6411 if (buffer[0] == '\n') {
6412 // User pressed return, interrupt watch command.
6413 return true;
6414 }
6415 }
6416}
6417
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006418status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6419 int inFd, int outFd) {
6420 // Figure out refresh interval, if present in args
6421 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006422 if (args.size() > 2) {
6423 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006424 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006425 intervalIdx++);
6426
6427 size_t intervalValIdx = intervalIdx + 1;
6428 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006429 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006430 if (errno) { return BAD_VALUE; }
6431 }
6432 }
6433
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006434 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6435 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006436
Avichal Rakesh84147132021-11-11 17:47:11 -08006437 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006438 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006439
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006440 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006441 bool serviceLock = tryLock(mServiceLock);
6442 auto cameraClients = mActiveClientManager.getAll();
6443 if (serviceLock) { mServiceLock.unlock(); }
6444
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006445 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006446 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006447 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006448
6449 sp<BasicClient> client = clientDescriptor->getValue();
6450 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006451 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006452
Austin Borgered99f642023-06-01 16:51:35 -07006453 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006454 // This also initializes the map entries with an empty string
6455 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6456
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006457 std::vector<std::string> latestEvents;
6458 client->dumpWatchedEventsToVector(latestEvents);
6459
6460 if (!latestEvents.empty()) {
6461 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006462 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006463 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006464 latestEvents,
6465 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006466 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006467 }
6468 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006469 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006470 break;
6471 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006472 }
6473 return OK;
6474}
6475
Austin Borgered99f642023-06-01 16:51:35 -07006476void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006477 mWatchedClientPackages.clear();
6478
Austin Borgered99f642023-06-01 16:51:35 -07006479 std::istringstream iss(clients);
6480 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006481
Austin Borgered99f642023-06-01 16:51:35 -07006482 while (std::getline(iss, nextClient, ',')) {
6483 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006484 // Don't need to track any other package if 'all' is present
6485 mWatchedClientPackages.clear();
6486 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6487 break;
6488 }
6489
6490 // track package names
6491 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006492 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006493}
6494
Svet Ganova453d0d2018-01-11 15:37:58 -08006495status_t CameraService::printHelp(int out) {
6496 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006497 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6498 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6499 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006500 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6501 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6502 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006503 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6504 " Valid values 0=false, 1=true, 2=auto\n"
6505 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006506 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6507 " Valid values 0=OFF, 1=ON for JPEG\n"
6508 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006509 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006510 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6511 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6512 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6513 " on. In case the number of usecases is smaller than the number of streams, the\n"
6514 " last use case is assigned to all the remaining streams. In case of multiple\n"
6515 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6516 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6517 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6518 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006519 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6520 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006521 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6522 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006523 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006524 " help print this message\n");
6525}
6526
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006527bool CameraService::isClientWatched(const BasicClient *client) {
6528 Mutex::Autolock lock(mLogLock);
6529 return isClientWatchedLocked(client);
6530}
6531
6532bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6533 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6534 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6535}
6536
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006537int32_t CameraService::updateAudioRestriction() {
6538 Mutex::Autolock lock(mServiceLock);
6539 return updateAudioRestrictionLocked();
6540}
6541
6542int32_t CameraService::updateAudioRestrictionLocked() {
6543 int32_t mode = 0;
6544 // iterate through all active client
6545 for (const auto& i : mActiveClientManager.getAll()) {
6546 const auto clientSp = i->getValue();
6547 mode |= clientSp->getAudioRestriction();
6548 }
6549
6550 bool modeChanged = (mAudioRestriction != mode);
6551 mAudioRestriction = mode;
6552 if (modeChanged) {
6553 mAppOps.setCameraAudioRestriction(mode);
6554 }
6555 return mode;
6556}
6557
Austin Borgered99f642023-06-01 16:51:35 -07006558status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006559 sp<BasicClient> clientSp) {
6560 std::unique_ptr<AutoConditionLock> lock =
6561 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6562 status_t res = NO_ERROR;
6563 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006564 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006565 mInjectionStatusListener->notifyInjectionError(
6566 externalCamId, UNKNOWN_TRANSACTION);
6567 clientSp->notifyError(
6568 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6569 CaptureResultExtras());
6570
6571 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6572 // other clients from connecting in mServiceLockWrapper if held
6573 mServiceLock.unlock();
6574
6575 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006576 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006577 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006578 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006579
6580 // Reacquire mServiceLock
6581 mServiceLock.lock();
6582 }
6583
6584 return res;
6585}
6586
Cliff Wud3a05312021-04-26 23:07:31 +08006587void CameraService::clearInjectionParameters() {
6588 {
6589 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006590 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006591 mInjectionInternalCamId = "";
6592 }
6593 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006594 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006595}
6596
Biswarup Pal37a75182024-01-16 15:53:35 +00006597} // namespace android