blob: fa5eb6f6d77786a0ce966d357952e78f718828dd [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";
98
99 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
100 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
101 return android::kDefaultDeviceId;
102 }
103
104 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
105 return deviceIdEntry.data.i32[0];
106 }
107} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Austin Borgerea931242021-12-13 23:10:41 +0000111using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700112using namespace camera3::SessionConfigurationUtils;
113
114using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000115using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700116using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700117using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800118using hardware::ICamera;
119using hardware::ICameraClient;
120using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800121using hardware::camera2::ICameraInjectionCallback;
122using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800123using hardware::camera2::utils::CameraIdAndSessionConfiguration;
124using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000125
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700126namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000127namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130// Logging support -- this is for debugging only
131// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700132volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Steve Blockb8a80522011-12-20 16:23:08 +0000134#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
135#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
137static void setLogLevel(int level) {
138 android_atomic_write(level, &gLogLevel);
139}
140
Henri Chataingbcb99452023-11-01 17:40:30 +0000141int32_t format_as(CameraService::StatusInternal s) {
142 return fmt::underlying(s);
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Austin Borger249e6592024-03-10 22:28:11 -0700147// Permission strings (references to AttributionAndPermissionUtils for brevity)
148static const std::string &sDumpPermission =
149 AttributionAndPermissionUtils::sDumpPermission;
150static const std::string &sManageCameraPermission =
151 AttributionAndPermissionUtils::sManageCameraPermission;
152static const std::string &sCameraSendSystemEventsPermission =
153 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
154static const std::string &sCameraInjectExternalCameraPermission =
155 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
156
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000157// Constant integer for FGS Logging, used to denote the API type for logger
158static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700159const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800160static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
161static constexpr int32_t kSystemNativeClientState =
162 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700163static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700164
Austin Borgered99f642023-06-01 16:51:35 -0700165const std::string CameraService::kOfflineDevice("offline-");
166const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700167
Biswarup Pal7d072862024-04-17 15:24:47 +0000168constexpr int32_t kInvalidDeviceId = -1;
169
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700171static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700172
Austin Borger74fca042022-05-23 12:41:21 -0700173CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700174 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
175 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
176 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
177 std::make_shared<AttributionAndPermissionUtils>()\
178 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700179 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
180 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800181 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800182 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700183 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mSoundRef(0), mInitialized(false),
185 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000186 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700187 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800188 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700189 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
190 if (mMemFd == -1) {
191 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193}
194
Charles Chena7b613c2023-01-24 21:57:33 +0000195// Enable processes with isolated AID to request the binder
196void CameraService::instantiate() {
197 CameraService::publish(true);
198}
199
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700201 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800202 return;
203 }
204
205 ALOGV("appops service registered. setting camera audio restriction");
206 mAppOps.setCameraAudioRestriction(mAudioRestriction);
207}
208
Iliyan Malchev8951a972011-04-14 16:55:59 -0700209void CameraService::onFirstRef()
210{
Ruben Brunkcc776712015-02-17 20:18:47 -0800211 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800212
Iliyan Malchev8951a972011-04-14 16:55:59 -0700213 BnCameraService::onFirstRef();
214
Ruben Brunk99e69712015-05-26 17:25:07 -0700215 // Update battery life tracking if service is restarting
216 BatteryNotifier& notifier(BatteryNotifier::getInstance());
217 notifier.noteResetCamera();
218 notifier.noteResetFlashlight();
219
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800220 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800221
Emilian Peevf53f66e2017-04-11 14:29:43 +0100222 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223 if (res == OK) {
224 mInitialized = true;
225 }
226
Svet Ganova453d0d2018-01-11 15:37:58 -0800227 mUidPolicy = new UidPolicy(this);
228 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700229 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800230 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800231 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800232
233 // appops function setCamerAudioRestriction uses getService which
234 // is blocking till the appops service is ready. To enable early
235 // boot availability for cameraservice, use checkService which is
236 // non blocking and register for notifications
237 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700238 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700240 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800241 } else {
242 mAppOps.setCameraAudioRestriction(mAudioRestriction);
243 }
244
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700245 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
246 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000247 // Deprecated, so it will fail to register on newer devices
248 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700249 __FUNCTION__);
250 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700251
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700252 if (!AidlCameraService::registerService(this)) {
253 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
254 }
255
Shuzhen Wang24b44152019-09-20 10:38:11 -0700256 // This needs to be last call in this function, so that it's as close to
257 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700258 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700259 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260}
261
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800262status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100264
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000266 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 {
268 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800269
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800270 if (nullptr == mCameraProviderManager.get()) {
271 mCameraProviderManager = new CameraProviderManager();
272 res = mCameraProviderManager->initialize(this);
273 if (res != OK) {
274 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
275 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700276 logServiceError("Unable to initialize camera provider manager",
277 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800278 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100279 }
280 }
281
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 // Setup vendor tags before we call get_camera_info the first time
283 // because HAL might need to setup static vendor keys in get_camera_info
284 // TODO: maybe put this into CameraProviderManager::initialize()?
285 mCameraProviderManager->setUpVendorTags();
286
287 if (nullptr == mFlashlight.get()) {
288 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700289 }
290
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800291 res = mFlashlight->findFlashUnits();
292 if (res != OK) {
293 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
294 }
295
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000296 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 }
298
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800299 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700300 if (getCameraState(cameraId) == nullptr) {
301 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800302 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000303 if (unavailPhysicalIds.count(cameraId) > 0) {
304 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700305 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000306 }
307 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800308 }
309
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700310 // Derive primary rear/front cameras, and filter their charactierstics.
311 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700312 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700313 // Assume internal cameras are advertised from the same
314 // provider. If multiple providers are registered at different time,
315 // and each provider contains multiple internal color cameras, the current
316 // logic may filter the characteristics of more than one front/rear color
317 // cameras.
318 Mutex::Autolock l(mServiceLock);
319 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700320 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700321
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800322 return OK;
323}
324
Austin Borgered99f642023-06-01 16:51:35 -0700325void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700326 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000327 // Get the device id and app-visible camera id for the given HAL-visible camera id.
328 auto [deviceId, mappedCameraId] =
329 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
330
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800331 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700333 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
334 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000335 ALOGV("%s: Skipping torch callback for system-only camera device %s",
336 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700337 continue;
338 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000339
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000341 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700342 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
343 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800344 }
345}
346
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800348 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800349 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800350 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800351 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Emilian Peevaee727d2017-05-04 16:35:48 +0100354void CameraService::onNewProviderRegistered() {
355 enumerateProviders();
356}
357
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700358void CameraService::filterAPI1SystemCameraLocked(
359 const std::vector<std::string> &normalDeviceIds) {
360 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000361 for (auto &cameraId : normalDeviceIds) {
362 if (vd_flags::camera_device_awareness()) {
363 CameraMetadata cameraInfo;
364 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000365 cameraId, false, &cameraInfo,
366 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000367 int32_t deviceId = kDefaultDeviceId;
368 if (res != OK) {
369 ALOGW("%s: Not able to get camera characteristics for camera id %s",
370 __FUNCTION__, cameraId.c_str());
371 } else {
372 deviceId = getDeviceId(cameraInfo);
373 }
374 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
375 // system cameras, so skip for non-default device id's.
376 if (deviceId != kDefaultDeviceId) {
377 continue;
378 }
379 }
380
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700381 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000382 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
383 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700384 continue;
385 }
386 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700387 // All system camera ids will necessarily come after public camera
388 // device ids as per the HAL interface contract.
389 break;
390 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000391 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700392 }
393 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
394 mNormalDeviceIdsWithoutSystemCamera.size());
395}
396
Austin Borgered99f642023-06-01 16:51:35 -0700397status_t CameraService::getSystemCameraKind(const std::string& cameraId,
398 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700399 auto state = getCameraState(cameraId);
400 if (state != nullptr) {
401 *kind = state->getSystemCameraKind();
402 return OK;
403 }
404 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700405 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700406}
407
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800408void CameraService::updateCameraNumAndIds() {
409 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700410 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
411 // Excludes hidden secure cameras
412 mNumberOfCameras =
413 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
414 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800415 mNormalDeviceIds =
416 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700417 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800418}
419
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700420void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700421 // To claim to be S Performance primary cameras, the cameras must be
422 // backward compatible. So performance class primary camera Ids must be API1
423 // compatible.
424 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
425 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
426 int facing = -1;
427 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800428 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000429 getDeviceVersion(cameraId,
430 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
431 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700432 if (facing == -1) {
433 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
434 return;
435 }
436
437 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
438 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700439 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
440 if (res == OK) {
441 mPerfClassPrimaryCameraIds.insert(cameraId);
442 } else {
443 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
444 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
445 break;
446 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447
448 if (facing == hardware::CAMERA_FACING_BACK) {
449 firstRearCameraSeen = true;
450 }
451 if (facing == hardware::CAMERA_FACING_FRONT) {
452 firstFrontCameraSeen = true;
453 }
454 }
455
456 if (firstRearCameraSeen && firstFrontCameraSeen) {
457 break;
458 }
459 }
460}
461
Austin Borgered99f642023-06-01 16:51:35 -0700462void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700463 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100464 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
465 if (res != OK) {
466 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
467 return;
468 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000469 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700470 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
471 if (res != OK) {
472 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
473 return;
474 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000475 std::vector<std::string> physicalCameraIds;
476 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700477 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100478 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700479 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100480 }
481
482 {
483 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700484 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000485 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100486 }
487
Austin Borgered99f642023-06-01 16:51:35 -0700488 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100489 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700490 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800491
Austin Borgered99f642023-06-01 16:51:35 -0700492 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800494
495 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700496 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497}
498
Austin Borgered99f642023-06-01 16:51:35 -0700499void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800500 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700501 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100502 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700503 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100504 }
505
506 {
507 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700508 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100509 }
510}
511
Austin Borgered99f642023-06-01 16:51:35 -0700512void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 CameraDeviceStatus newHalStatus) {
514 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700515 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 StatusInternal newStatus = mapToInternal(newHalStatus);
518
Austin Borgered99f642023-06-01 16:51:35 -0700519 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800520
521 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700522 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100523 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700524 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100525
526 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700527 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100528
Austin Borgered99f642023-06-01 16:51:35 -0700529 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700530 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700531 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700532 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700533 return;
534 }
535
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800536 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800538 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700539 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
540 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700541 return;
542 }
543
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800544 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000545 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
546 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800547 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
548 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000550 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800551
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800552 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700553 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 // Don't do this in updateStatus to avoid deadlock over mServiceLock
555 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700556
Ruben Brunkcc776712015-02-17 20:18:47 -0800557 // Remove cached shim parameters
558 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700559
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800560 // Remove online as well as offline client from the list of active clients,
561 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700562 clientToDisconnectOnline = removeClientLocked(cameraId);
563 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700564 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800565
Austin Borgered99f642023-06-01 16:51:35 -0700566 disconnectClient(cameraId, clientToDisconnectOnline);
567 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700568
Austin Borgered99f642023-06-01 16:51:35 -0700569 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800570 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800571 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000572 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
573 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700574 }
Austin Borgered99f642023-06-01 16:51:35 -0700575 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700576 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800577}
Igor Murashkincba2c162013-03-20 15:56:31 -0700578
Austin Borgered99f642023-06-01 16:51:35 -0700579void CameraService::onDeviceStatusChanged(const std::string& id,
580 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800581 CameraDeviceStatus newHalStatus) {
582 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700583 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800584
585 StatusInternal newStatus = mapToInternal(newHalStatus);
586
587 std::shared_ptr<CameraState> state = getCameraState(id);
588
589 if (state == nullptr) {
590 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700591 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800592 return;
593 }
594
595 StatusInternal logicalCameraStatus = state->getStatus();
596 if (logicalCameraStatus != StatusInternal::PRESENT &&
597 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
598 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700599 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800600 return;
601 }
602
603 bool updated = false;
604 if (newStatus == StatusInternal::PRESENT) {
605 updated = state->removeUnavailablePhysicalId(physicalId);
606 } else {
607 updated = state->addUnavailablePhysicalId(physicalId);
608 }
609
610 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700611 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800612 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000613 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800614 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000615 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800616 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700617 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
618 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
619 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700620 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700621 return;
622 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800623 Mutex::Autolock lock(mStatusListenerLock);
624 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700625 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
626 listener->getListenerPid(), listener->getListenerUid())) {
627 ALOGV("Skipping discovery callback for system-only camera device %s",
628 id.c_str());
629 continue;
630 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700631 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000632 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700633 listener->handleBinderStatus(ret,
634 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
635 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
636 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800637 }
638 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700639}
640
Austin Borgered99f642023-06-01 16:51:35 -0700641void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800642 if (clientToDisconnect.get() != nullptr) {
643 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700644 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800645 // Notify the client of disconnection
646 clientToDisconnect->notifyError(
647 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
648 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800649 clientToDisconnect->disconnect();
650 }
651}
652
Austin Borgered99f642023-06-01 16:51:35 -0700653void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800654 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700655 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
656 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
657 if (res != OK) {
658 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700659 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700660 return;
661 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800662 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700663 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664}
665
Austin Borgered99f642023-06-01 16:51:35 -0700666void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700667 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
668 Mutex::Autolock al(mTorchStatusMutex);
669 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
670}
671
Austin Borgered99f642023-06-01 16:51:35 -0700672void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800673 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000674 // Get the device id and app-visible camera id for the given HAL-visible camera id.
675 auto [deviceId, mappedCameraId] =
676 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
677
Rucha Katakwar38284522021-11-10 11:25:21 -0800678 Mutex::Autolock lock(mStatusListenerLock);
679 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000680 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
681 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700682 i->handleBinderStatus(ret,
683 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
684 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800685 }
686}
687
Austin Borgered99f642023-06-01 16:51:35 -0700688void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700689 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800690 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700691 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800692
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800693 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800694 status_t res = getTorchStatusLocked(cameraId, &status);
695 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700696 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700697 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800698 return;
699 }
700 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800701 return;
702 }
703
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800704 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800705 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800706 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
707 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800708 return;
709 }
710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700712 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700713 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700714 auto iter = mTorchUidMap.find(cameraId);
715 if (iter != mTorchUidMap.end()) {
716 int oldUid = iter->second.second;
717 int newUid = iter->second.first;
718 BatteryNotifier& notifier(BatteryNotifier::getInstance());
719 if (oldUid != newUid) {
720 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800721 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700722 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700723 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800724 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700725 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700726 }
727 iter->second.second = newUid;
728 } else {
729 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800730 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700731 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700732 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700733 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700734 }
735 }
736 }
737 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700738 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800739}
740
Austin Borger249e6592024-03-10 22:28:11 -0700741bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700742 // Returns false if this is not an automotive device type.
743 if (!isAutomotiveDevice())
744 return false;
745
746 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700747 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700748 return false;
749
750 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
751 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
752 // This isn't a known camera ID, so it's not a system camera.
753 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
754 return false;
755 }
756
757 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
758 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
759 return false;
760 }
761
762 CameraMetadata cameraInfo;
763 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000764 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700765 if (res != OK){
766 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
767 cam_id.c_str());
768 return false;
769 }
770
771 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
772 if (auto_location.count != 1)
773 return false;
774
775 uint8_t location = auto_location.data.u8[0];
776 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
777 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
778 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
779 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
780 return false;
781 }
782
783 return true;
784}
785
Austin Borger65e64642024-06-11 15:58:23 -0700786Status CameraService::getNumberOfCameras(int32_t type,
787 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000788 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700789 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700790 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000791 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700792 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000793 return Status::ok();
794 }
795
Emilian Peevaee727d2017-05-04 16:35:48 +0100796 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700797 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800798 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
799 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700800 switch (type) {
801 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 if (hasSystemCameraPermissions) {
803 *numCameras = static_cast<int>(mNormalDeviceIds.size());
804 } else {
805 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
806 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800807 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700808 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700809 if (hasSystemCameraPermissions) {
810 *numCameras = mNumberOfCameras;
811 } else {
812 *numCameras = mNumberOfCamerasWithoutSystemCamera;
813 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800816 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700817 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800818 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
819 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700824Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700825 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700826 /* out */
827 hardware::camera2::impl::CameraMetadataNative* request) {
828 ATRACE_CALL();
829
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700830 if (!mInitialized) {
831 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
832 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
833 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
834 }
835
Austin Borger65e64642024-06-11 15:58:23 -0700836 std::optional<std::string> cameraIdOptional =
837 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000838 if (!cameraIdOptional.has_value()) {
839 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700840 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000841 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
842 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
843 }
844 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700845
846 binder::Status res;
847 if (request == nullptr) {
848 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
849 "Camera %s: Error creating default request", cameraId.c_str());
850 return res;
851 }
852 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
853 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
854 cameraId, templateId, &tempId);
855 if (!res.isOk()) {
856 ALOGE("%s: Camera %s: failed to map request Template %d",
857 __FUNCTION__, cameraId.c_str(), templateId);
858 return res;
859 }
860
861 if (shouldRejectSystemCameraConnection(cameraId)) {
862 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
863 "request for system only device %s: ", cameraId.c_str());
864 }
865
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700866 CameraMetadata metadata;
867 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
868 if (err == OK) {
869 request->swap(metadata);
870 } else if (err == BAD_VALUE) {
871 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
872 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
873 cameraId.c_str(), templateId, strerror(-err), err);
874 } else {
875 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
876 "Camera %s: Error creating default request for template %d: %s (%d)",
877 cameraId.c_str(), templateId, strerror(-err), err);
878 }
879 return res;
880}
881
882Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700883 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700884 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700885 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700886 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700887 ATRACE_CALL();
888
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700889 if (!mInitialized) {
890 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
891 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
892 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
893 }
894
Austin Borger65e64642024-06-11 15:58:23 -0700895 std::optional<std::string> cameraIdOptional =
896 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000897 if (!cameraIdOptional.has_value()) {
898 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700899 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000900 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
901 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
902 }
903 std::string cameraId = cameraIdOptional.value();
904
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700905 if (supported == nullptr) {
906 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
907 unresolvedCameraId.c_str());
908 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
909 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
910 }
911
912 if (shouldRejectSystemCameraConnection(cameraId)) {
913 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
914 "session configuration with parameters support for system only device %s: ",
915 cameraId.c_str());
916 }
917
Avichal Rakeshe005df52024-09-25 17:13:27 -0700918 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700919 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
920
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700921 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
922 sessionConfiguration, overrideForPerfClass, supported);
923 if (flags::analytics_24q3()) {
924 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
925 getCallingUid(), sessionConfiguration, ret);
926 }
927 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700928}
929
930Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
931 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
932 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700933 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700934 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
935 cameraId, sessionConfiguration, overrideForPerfClass,
936 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700937 binder::Status res;
938 switch (ret) {
939 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700940 // Expected. Do Nothing.
941 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700942 case INVALID_OPERATION: {
943 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700944 "Camera %s: Session configuration with parameters supported query not "
945 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700946 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700947 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
948 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
949 *supported = false;
950 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700951 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700952 break;
953 case NAME_NOT_FOUND: {
954 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
955 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
956 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
957 *supported = false;
958 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
959 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700960 break;
961 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700962 std::string msg = fmt::sprintf(
963 "Unable to retrieve session configuration support for camera "
964 "device %s: Error: %s (%d)",
965 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700966 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700967 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
968 *supported = false;
969 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700971 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700972 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973}
974
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800975Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000976 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700977 const SessionConfiguration& sessionConfiguration,
978 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000979 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800980 ATRACE_CALL();
981
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800982 if (outMetadata == nullptr) {
983 std::string msg =
984 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
985 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
986 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
987 }
988
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700989 if (!mInitialized) {
990 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
991 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
992 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
993 }
994
Austin Borger65e64642024-06-11 15:58:23 -0700995 std::optional<std::string> cameraIdOptional =
996 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000997 if (!cameraIdOptional.has_value()) {
998 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700999 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001000 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1001 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1002 }
1003 std::string cameraId = cameraIdOptional.value();
1004
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001005 if (shouldRejectSystemCameraConnection(cameraId)) {
1006 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1007 "Unable to retrieve camera"
1008 "characteristics for system only device %s: ",
1009 cameraId.c_str());
1010 }
1011
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001012 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1013 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesheb961c72024-09-25 17:26:26 -07001014
1015 bool sessionConfigSupported;
1016 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1017 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1018 if (!res.isOk()) {
1019 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1020 // report the correct Status to send to the client. Simply forward the error to
1021 // the client.
1022 outMetadata->clear();
1023 return res;
1024 }
1025
1026 if (!sessionConfigSupported) {
1027 std::string msg = fmt::sprintf("Session configuration not supported for camera device %s.",
1028 cameraId.c_str());
1029 outMetadata->clear();
1030 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001031 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001032
1033 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001034 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001035
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001036 switch (ret) {
1037 case OK:
1038 // Expected, no handling needed.
1039 break;
1040 case INVALID_OPERATION: {
1041 std::string msg = fmt::sprintf(
1042 "Camera %s: Session characteristics query not supported!",
1043 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001044 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001045 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1046 outMetadata->clear();
1047 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1048 }
1049 break;
1050 case NAME_NOT_FOUND: {
1051 std::string msg = fmt::sprintf(
1052 "Camera %s: Unknown camera ID.",
1053 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001054 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001055 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1056 outMetadata->clear();
1057 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001058 }
1059 break;
1060 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001061 std::string msg = fmt::sprintf(
1062 "Unable to retrieve session characteristics for camera device %s: "
1063 "Error: %s (%d)",
1064 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001065 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001066 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1067 outMetadata->clear();
1068 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001069 }
1070 }
1071
Avichal Rakesheb961c72024-09-25 17:26:26 -07001072 res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001073 if (flags::analytics_24q3()) {
1074 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1075 getCallingUid(), sessionConfiguration, res);
1076 }
1077 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001078}
1079
1080Status CameraService::filterSensitiveMetadataIfNeeded(
1081 const std::string& cameraId, CameraMetadata* metadata) {
1082 int callingPid = getCallingPid();
1083 int callingUid = getCallingUid();
1084
1085 if (callingPid == getpid()) {
1086 // Caller is cameraserver; no need to remove keys
1087 return Status::ok();
1088 }
1089
1090 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1091 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1092 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1093 metadata->clear();
1094 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1095 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1096 }
1097 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1098 // Attempting to query system only camera without system camera permission would have
1099 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1100 // for a system only camera, then the caller has the required permission.
1101 // No need to remove keys
1102 return Status::ok();
1103 }
1104
1105 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001106 // Get the device id that owns this camera.
1107 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1108 cameraId);
1109 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1110 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001111 if (hasCameraPermission) {
1112 // Caller has camera permission; no need to remove keys
1113 return Status::ok();
1114 }
1115
1116 status_t ret = metadata->removePermissionEntries(
1117 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1118 if (ret != OK) {
1119 metadata->clear();
1120 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1121 "Failed to remove camera characteristics needing camera permission "
1122 "for device %s:%s (%d)",
1123 cameraId.c_str(), strerror(-ret), ret);
1124 }
1125
1126 if (!tagsRemoved.empty()) {
1127 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1128 tagsRemoved.data(), tagsRemoved.size());
1129 if (ret != OK) {
1130 metadata->clear();
1131 return STATUS_ERROR_FMT(
1132 ERROR_INVALID_OPERATION,
1133 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1134 cameraId.c_str(), strerror(-ret), ret);
1135 }
1136 }
1137 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001138}
1139
malikakash22af94c2023-12-04 18:13:14 +00001140Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001141 const std::string& cameraId,
1142 const CameraMetadata& sessionParams) {
1143 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001144 const int pid = getCallingPid();
1145 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001146 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1147 __FUNCTION__, pid, uid);
1148 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1149 "Permission Denial: no permission to inject session params");
1150 }
1151
Biswarup Pal37a75182024-01-16 15:53:35 +00001152 // Do not allow session params injection for a virtual camera.
1153 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1154 if (deviceId != kDefaultDeviceId) {
1155 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1156 "Cannot inject session params for a virtual camera");
1157 }
1158
malikakash22af94c2023-12-04 18:13:14 +00001159 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1160 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1161
1162 auto clientDescriptor = mActiveClientManager.get(cameraId);
1163 if (clientDescriptor == nullptr) {
1164 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1165 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1166 "No active client for camera id %s", cameraId.c_str());
1167 }
1168
1169 sp<BasicClient> clientSp = clientDescriptor->getValue();
1170 status_t res = clientSp->injectSessionParams(sessionParams);
1171
1172 if (res != OK) {
1173 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1174 "Error injecting session params into camera \"%s\": %s (%d)",
1175 cameraId.c_str(), strerror(-res), res);
1176 }
1177 return Status::ok();
1178}
1179
Biswarup Pal37a75182024-01-16 15:53:35 +00001180std::optional<std::string> CameraService::resolveCameraId(
1181 const std::string& inputCameraId,
1182 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001183 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001184 if ((deviceId == kDefaultDeviceId)
1185 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1186 auto [storedDeviceId, _] =
1187 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1188 if (storedDeviceId != kDefaultDeviceId) {
1189 // Trying to access a virtual camera from default-policy device context, we should fail.
1190 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1191 inputCameraId.c_str(), deviceId);
1192 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1193 return std::nullopt;
1194 }
malikakash98260df2024-05-10 23:33:57 +00001195 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001196 }
1197
1198 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1199}
1200
Austin Borger65e64642024-06-11 15:58:23 -07001201Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1202 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1203 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001204 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001205 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001206 std::string cameraIdStr =
1207 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001208 if (cameraIdStr.empty()) {
1209 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001210 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001211 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1212 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1213 }
malikakashedb38962023-09-06 00:03:35 +00001214
Austin Borgered99f642023-06-01 16:51:35 -07001215 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001216 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1217 "characteristics for system only device %s: ", cameraIdStr.c_str());
1218 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001219
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001220 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001221 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001222 return STATUS_ERROR(ERROR_DISCONNECTED,
1223 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001224 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001225 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001226 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001227 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1228 if (hasSystemCameraPermissions) {
1229 cameraIdBound = mNumberOfCameras;
1230 }
1231 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001232 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1233 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 }
1235
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001236 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001237 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001238 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001239 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001240 if (err != OK) {
1241 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1242 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1243 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001244 logServiceError(std::string("Error retrieving camera info from device ")
1245 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001246 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001247
Ruben Brunkcc776712015-02-17 20:18:47 -08001248 return ret;
1249}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001250
Biswarup Pal37a75182024-01-16 15:53:35 +00001251std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1252 int32_t deviceId, int32_t devicePolicy) {
1253 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1254 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1255 std::optional<std::string> cameraIdOptional =
1256 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1257 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1258 }
1259
1260 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001261 auto callingPid = getCallingPid();
1262 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001263 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1264 callingPid, callingUid, /* checkCameraPermissions= */ false);
1265 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001266 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001267 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001268 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1269 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1270 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001271 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001272 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001273
malikakash98260df2024-05-10 23:33:57 +00001274 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001275}
1276
Biswarup Pal37a75182024-01-16 15:53:35 +00001277std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1278 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001279 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001280 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001281}
1282
Austin Borgered99f642023-06-01 16:51:35 -07001283Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001284 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1285 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001286 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001287
Zhijun He2b59be82013-09-25 10:14:30 -07001288 if (!cameraInfo) {
1289 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001290 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001291 }
1292
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001293 if (!mInitialized) {
1294 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001295 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001296 return STATUS_ERROR(ERROR_DISCONNECTED,
1297 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001298 }
1299
Austin Borger65e64642024-06-11 15:58:23 -07001300 std::optional<std::string> cameraIdOptional =
1301 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001302 if (!cameraIdOptional.has_value()) {
1303 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001304 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001305 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1306 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1307 }
1308 std::string cameraId = cameraIdOptional.value();
1309
Austin Borgered99f642023-06-01 16:51:35 -07001310 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001311 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001312 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001313 }
1314
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001315 bool overrideForPerfClass =
1316 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001317 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001318 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001319 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001320 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001321 if (res == NAME_NOT_FOUND) {
1322 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001323 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001324 strerror(-res), res);
1325 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001326 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1327 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001328 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001329 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001330 strerror(-res), res);
1331 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001332 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001333
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001334 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001335}
1336
Austin Borger65e64642024-06-11 15:58:23 -07001337Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1338 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001339 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001340 ATRACE_CALL();
1341 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001342
Austin Borger65e64642024-06-11 15:58:23 -07001343 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1344 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001345 if (!cameraIdOptional.has_value()) {
1346 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001347 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001348 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1349 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1350 }
1351 std::string cameraId = cameraIdOptional.value();
1352
Rucha Katakwar38284522021-11-10 11:25:21 -08001353 if (!mInitialized) {
1354 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1355 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1356 }
1357
Biswarup Pal37a75182024-01-16 15:53:35 +00001358 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001359 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1360 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1361 }
1362
Austin Borgered99f642023-06-01 16:51:35 -07001363 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001364 if (res != OK) {
1365 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001366 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001367 strerror(-res), res);
1368 }
1369 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1370 return Status::ok();
1371}
1372
Austin Borgered99f642023-06-01 16:51:35 -07001373std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001374 time_t now = time(nullptr);
1375 char formattedTime[64];
1376 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001377 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001378}
1379
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001380Status CameraService::getCameraVendorTagDescriptor(
1381 /*out*/
1382 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001383 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001384 if (!mInitialized) {
1385 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001386 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001387 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001388 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1389 if (globalDescriptor != nullptr) {
1390 *desc = *(globalDescriptor.get());
1391 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001392 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001393}
1394
Emilian Peev71c73a22017-03-21 16:35:51 +00001395Status CameraService::getCameraVendorTagCache(
1396 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1397 ATRACE_CALL();
1398 if (!mInitialized) {
1399 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1400 return STATUS_ERROR(ERROR_DISCONNECTED,
1401 "Camera subsystem not available");
1402 }
1403 sp<VendorTagDescriptorCache> globalCache =
1404 VendorTagDescriptorCache::getGlobalVendorTagCache();
1405 if (globalCache != nullptr) {
1406 *cache = *(globalCache.get());
1407 }
1408 return Status::ok();
1409}
1410
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001411void CameraService::clearCachedVariables() {
1412 BasicClient::BasicClient::sCameraService = nullptr;
1413}
1414
Austin Borgered99f642023-06-01 16:51:35 -07001415std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001416 int rotationOverride, int* portraitRotation, int* facing,
1417 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001418 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001419
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001420 int deviceVersion = 0;
1421
Emilian Peevf53f66e2017-04-11 14:29:43 +01001422 status_t res;
1423 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001424 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001425 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001426 if (res != OK || transport == IPCTransport::INVALID) {
1427 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001428 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001429 return std::make_pair(-1, IPCTransport::INVALID) ;
1430 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001431 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001432
Emilian Peevf53f66e2017-04-11 14:29:43 +01001433 hardware::CameraInfo info;
1434 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001435 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001436 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001437 if (res != OK) {
1438 return std::make_pair(-1, IPCTransport::INVALID);
1439 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001440 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001441 if (orientation) {
1442 *orientation = info.orientation;
1443 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001444 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001445
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001446 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001447}
1448
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001450 switch(err) {
1451 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001452 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001453 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001454 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1455 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001456 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001457 return STATUS_ERROR(ERROR_DISCONNECTED,
1458 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001459 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001460 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1461 "Camera HAL encountered error %d: %s",
1462 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001463 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001464}
1465
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001466Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001467 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1468 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001469 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001470 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001471 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001472 bool forceSlowJpegMode, const std::string& originalCameraId,
1473 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001474 // For HIDL devices
1475 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1476 // Create CameraClient based on device version reported by the HAL.
1477 int deviceVersion = deviceVersionAndTransport.first;
1478 switch(deviceVersion) {
1479 case CAMERA_DEVICE_API_VERSION_1_0:
1480 ALOGE("Camera using old HAL version: %d", deviceVersion);
1481 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1482 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001483 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001484 break;
1485 case CAMERA_DEVICE_API_VERSION_3_0:
1486 case CAMERA_DEVICE_API_VERSION_3_1:
1487 case CAMERA_DEVICE_API_VERSION_3_2:
1488 case CAMERA_DEVICE_API_VERSION_3_3:
1489 case CAMERA_DEVICE_API_VERSION_3_4:
1490 case CAMERA_DEVICE_API_VERSION_3_5:
1491 case CAMERA_DEVICE_API_VERSION_3_6:
1492 case CAMERA_DEVICE_API_VERSION_3_7:
1493 break;
1494 default:
1495 // Should not be reachable
1496 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1497 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1498 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001499 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001500 }
1501 }
1502 if (effectiveApiLevel == API_1) { // Camera1 API route
1503 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001504 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001505 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001506 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001507 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001508 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001509 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1510 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001511 } else { // Camera2 API route
1512 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1513 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001514 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001515 cameraService->mCameraServiceProxyWrapper,
1516 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001517 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001518 overrideForPerfClass, rotationOverride, originalCameraId);
1519 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001521 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001522}
1523
Austin Borgered99f642023-06-01 16:51:35 -07001524std::string CameraService::toString(std::set<userid_t> intSet) {
1525 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001526 bool first = true;
1527 for (userid_t i : intSet) {
1528 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001529 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001530 first = false;
1531 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001532 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001533 }
1534 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001535 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001536}
1537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001538int32_t CameraService::mapToInterface(TorchModeStatus status) {
1539 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1540 switch (status) {
1541 case TorchModeStatus::NOT_AVAILABLE:
1542 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1543 break;
1544 case TorchModeStatus::AVAILABLE_OFF:
1545 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1546 break;
1547 case TorchModeStatus::AVAILABLE_ON:
1548 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1549 break;
1550 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001551 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001552 }
1553 return serviceStatus;
1554}
1555
1556CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1557 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1558 switch (status) {
1559 case CameraDeviceStatus::NOT_PRESENT:
1560 serviceStatus = StatusInternal::NOT_PRESENT;
1561 break;
1562 case CameraDeviceStatus::PRESENT:
1563 serviceStatus = StatusInternal::PRESENT;
1564 break;
1565 case CameraDeviceStatus::ENUMERATING:
1566 serviceStatus = StatusInternal::ENUMERATING;
1567 break;
1568 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001569 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001570 }
1571 return serviceStatus;
1572}
1573
1574int32_t CameraService::mapToInterface(StatusInternal status) {
1575 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1576 switch (status) {
1577 case StatusInternal::NOT_PRESENT:
1578 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1579 break;
1580 case StatusInternal::PRESENT:
1581 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1582 break;
1583 case StatusInternal::ENUMERATING:
1584 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1585 break;
1586 case StatusInternal::NOT_AVAILABLE:
1587 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1588 break;
1589 case StatusInternal::UNKNOWN:
1590 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1591 break;
1592 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001593 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001594 }
1595 return serviceStatus;
1596}
1597
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001598Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001599 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001600
Austin Borgered99f642023-06-01 16:51:35 -07001601 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001603 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001604
Austin Borgerb01a8702024-07-22 16:20:34 -07001605 int callingPid = getCallingPid();
1606 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001607
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001609 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001610 kServiceName, /*systemNativeClient*/ false, {}, uid, callingPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001611 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001612 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1613 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borger7d2b9232024-07-22 14:17:14 -07001614 /*forceSlowJpegMode*/false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001615 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001616 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001617 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001618 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001619}
1620
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001621Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001622 /*out*/
1623 CameraParameters* parameters) {
1624
1625 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1626
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001628
1629 if (parameters == NULL) {
1630 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001632 }
1633
malikakash98260df2024-05-10 23:33:57 +00001634 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001635
1636 // Check if we already have parameters
1637 {
1638 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001639 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001640 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001641 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001642 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001643 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001644 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001645 }
1646 CameraParameters p = cameraState->getShimParams();
1647 if (!p.isEmpty()) {
1648 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001649 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001650 }
1651 }
1652
Austin Borger22c5c852024-03-08 13:31:36 -08001653 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001654 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001655 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001656 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001657 // Error already logged by callee
1658 return ret;
1659 }
1660
1661 // Check for parameters again
1662 {
1663 // Scope for service lock
1664 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001665 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001666 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001667 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001668 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001669 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001670 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 CameraParameters p = cameraState->getShimParams();
1672 if (!p.isEmpty()) {
1673 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001674 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001675 }
1676 }
1677
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1679 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001680 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001681}
1682
Austin Borgered99f642023-06-01 16:51:35 -07001683Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001684 const std::string& clientName8, int clientUid, int clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001685
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001686#ifdef __BRILLO__
1687 UNUSED(clientName8);
1688 UNUSED(clientUid);
1689 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001690#else
Austin Borger6e831c42024-07-22 13:07:56 -07001691 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001692 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001693 return allowed;
1694 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001695#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001696
Austin Borger22c5c852024-03-08 13:31:36 -08001697 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001698
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001699 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001700 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1701 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001702 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001703 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001704 }
1705
Ruben Brunkcc776712015-02-17 20:18:47 -08001706 if (getCameraState(cameraId) == nullptr) {
1707 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001708 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001709 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001710 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 }
1712
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001713 status_t err = checkIfDeviceIsUsable(cameraId);
1714 if (err != NO_ERROR) {
1715 switch(err) {
1716 case -ENODEV:
1717 case -EBUSY:
1718 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001719 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001720 default:
1721 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001722 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001723 }
1724 }
1725 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001726}
1727
Austin Borgerb01a8702024-07-22 16:20:34 -07001728Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1729 const std::string& clientName, int clientUid, int clientPid) const {
1730 int callingPid = getCallingPid();
1731 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001732
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001733 if (shouldRejectSystemCameraConnection(cameraId)) {
1734 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1735 cameraId.c_str());
1736 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001737 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001738 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001739 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1740 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001741 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001742 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001743 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001744 }
1745
Biswarup Pale506e732024-03-27 13:46:20 +00001746 // Get the device id that owns this camera.
1747 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1748
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001749 // If it's not calling from cameraserver, check the permission if the
1750 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1751 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001752 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001753 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001754 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001755 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001756 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001757 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1758 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001759 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001760 }
1761
Svet Ganova453d0d2018-01-11 15:37:58 -08001762 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001763 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001764 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001765 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1766 clientPid, clientUid);
1767 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001768 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1769 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001770 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001771 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001772 }
1773
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001774 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1775 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1776 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1777 if ((!isAutomotivePrivilegedClient(callingUid) ||
1778 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1779 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001780 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1781 return STATUS_ERROR_FMT(ERROR_DISABLED,
1782 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001783 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001784 }
1785
Austin Borger6e831c42024-07-22 13:07:56 -07001786 userid_t clientUserId = multiuser_get_user_id(clientUid);
1787
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001788 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1789 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001790
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001791 // For non-system clients : Only allow clients who are being used by the current foreground
1792 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001793 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001794 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001795 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1796 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001797 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001798 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1799 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001800 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001801 }
1802
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001803 if (flags::camera_hsum_permission()) {
1804 // If the System User tries to access the camera when the device is running in
1805 // headless system user mode, ensure that client has the required permission
1806 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001807 if (isHeadlessSystemUserMode()
1808 && (clientUserId == USER_SYSTEM)
1809 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001810 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001811 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1812 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1813 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001814 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001815 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001816 }
1817
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001818 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001819}
1820
Austin Borgered99f642023-06-01 16:51:35 -07001821status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001822 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001823 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001824 if (cameraState == nullptr) {
1825 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001826 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001827 return -ENODEV;
1828 }
1829
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001830 StatusInternal currentStatus = cameraState->getStatus();
1831 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001832 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001833 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001834 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001835 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001836 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001837 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001838 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001839 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001840
Ruben Brunkcc776712015-02-17 20:18:47 -08001841 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001842}
1843
Ruben Brunkcc776712015-02-17 20:18:47 -08001844void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001845 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001846
Ruben Brunkcc776712015-02-17 20:18:47 -08001847 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001848 auto clientDescriptor =
1849 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001850 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001851 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1852
1853 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001854 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001855
1856 if (evicted.size() > 0) {
1857 // This should never happen - clients should already have been removed in disconnect
1858 for (auto& i : evicted) {
1859 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001860 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001861 }
1862
1863 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1864 __FUNCTION__);
1865 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001866
1867 // And register a death notification for the client callback. Do
1868 // this last to avoid Binder policy where a nested Binder
1869 // transaction might be pre-empted to service the client death
1870 // notification if the client process dies before linkToDeath is
1871 // invoked.
1872 sp<IBinder> remoteCallback = client->getRemote();
1873 if (remoteCallback != nullptr) {
1874 remoteCallback->linkToDeath(this);
1875 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001876}
1877
Austin Borgered99f642023-06-01 16:51:35 -07001878status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1879 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1880 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001881 /*out*/
1882 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001883 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001884 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001885 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001886 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001887 DescriptorPtr clientDescriptor;
1888 {
1889 if (effectiveApiLevel == API_1) {
1890 // If we are using API1, any existing client for this camera ID with the same remote
1891 // should be returned rather than evicted to allow MediaRecorder to work properly.
1892
1893 auto current = mActiveClientManager.get(cameraId);
1894 if (current != nullptr) {
1895 auto clientSp = current->getValue();
1896 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001897 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001898 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001899 " API level, evicting prior client...");
1900 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001901 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001902 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001903 *client = clientSp;
1904 return NO_ERROR;
1905 }
1906 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001907 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001908 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001909
Ruben Brunkcc776712015-02-17 20:18:47 -08001910 // Get state for the given cameraId
1911 auto state = getCameraState(cameraId);
1912 if (state == nullptr) {
1913 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001914 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001915 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001916 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001917 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001918
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001919 sp<IServiceManager> sm = defaultServiceManager();
1920 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001921 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001922 // If processinfo service is not available and the client is automotive privileged
1923 // client used for safety critical uses cases such as rear-view and surround-view which
1924 // needs to be available before android boot completes, then use the hardcoded values
1925 // for the process state and priority score. As this scenario is before android system
1926 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1927 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1928 // visible on the top.
1929 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1930 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1931 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1932 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1933 } else {
1934 // Get current active client PIDs
1935 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1936 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001937
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001938 std::vector<int> priorityScores(ownerPids.size());
1939 std::vector<int> states(ownerPids.size());
1940
1941 // Get priority scores of all active PIDs
1942 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1943 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1944 if (err != OK) {
1945 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1946 return err;
1947 }
1948
1949 // Update all active clients' priorities
1950 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1951 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1952 pidToPriorityMap.emplace(ownerPids[i],
1953 resource_policy::ClientPriority(priorityScores[i], states[i],
1954 /* isVendorClient won't get copied over*/ false,
1955 /* oomScoreOffset won't get copied over*/ 0));
1956 }
1957 mActiveClientManager.updatePriorities(pidToPriorityMap);
1958
1959 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1960 int32_t actualState = states[states.size() - 1];
1961
1962 // Make descriptor for incoming client. We store the oomScoreOffset
1963 // since we might need it later on new handleEvictionsLocked and
1964 // ProcessInfoService would not take that into account.
1965 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1966 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1967 state->getConflicting(), actualScore, clientPid, actualState,
1968 oomScoreOffset, systemNativeClient);
1969 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001970
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001971 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1972
Ruben Brunkcc776712015-02-17 20:18:47 -08001973 // Find clients that would be evicted
1974 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1975
1976 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1977 // background, so we cannot do evictions
1978 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1979 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1980 " priority).", clientPid);
1981
1982 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001983 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001984 auto incompatibleClients =
1985 mActiveClientManager.getIncompatibleClients(clientDescriptor);
1986
Austin Borgered99f642023-06-01 16:51:35 -07001987 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
1988 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
1989 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001990 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08001991
1992 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07001993 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00001994 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07001995 i->getKey().c_str(),
1996 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00001997 i->getOwnerId(), i->getPriority().getScore(),
1998 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07001999 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002000 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2001 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002002 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002003 }
2004
2005 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002006 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002007 mEventLog.add(msg);
2008
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002009 auto current = mActiveClientManager.get(cameraId);
2010 if (current != nullptr) {
2011 return -EBUSY; // CAMERA_IN_USE
2012 } else {
2013 return -EUSERS; // MAX_CAMERAS_IN_USE
2014 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002015 }
2016
2017 for (auto& i : evicted) {
2018 sp<BasicClient> clientSp = i->getValue();
2019 if (clientSp.get() == nullptr) {
2020 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2021
2022 // TODO: Remove this
2023 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2024 __FUNCTION__);
2025 mActiveClientManager.remove(i);
2026 continue;
2027 }
2028
2029 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002030 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002031 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002032
Ruben Brunkcc776712015-02-17 20:18:47 -08002033 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002034 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002035 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2036 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002037 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002038 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002039 i->getPriority().getState(), cameraId.c_str(),
2040 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002041 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002042
2043 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002044 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002045 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002046 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002047 }
2048
Ruben Brunkcc776712015-02-17 20:18:47 -08002049 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2050 // other clients from connecting in mServiceLockWrapper if held
2051 mServiceLock.unlock();
2052
2053 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002054 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002055
2056 // Destroy evicted clients
2057 for (auto& i : evictedClients) {
2058 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002059 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002060 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002061
Austin Borger22c5c852024-03-08 13:31:36 -08002062 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002063
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002064 for (const auto& i : evictedClients) {
2065 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002066 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002067 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2068 if (ret == TIMED_OUT) {
2069 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002070 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2071 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002072 return -EBUSY;
2073 }
2074 if (ret != NO_ERROR) {
2075 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002076 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2077 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002078 return ret;
2079 }
2080 }
2081
2082 evictedClients.clear();
2083
Ruben Brunkcc776712015-02-17 20:18:47 -08002084 // Once clients have been disconnected, relock
2085 mServiceLock.lock();
2086
2087 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2088 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2089 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002090 }
2091
Ruben Brunkcc776712015-02-17 20:18:47 -08002092 *partial = clientDescriptor;
2093 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002094}
2095
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002096Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002097 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002098 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002099 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002100 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002101 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002102 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002103 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002104 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002105 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002106 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002107 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002108
Austin Borger65e64642024-06-11 15:58:23 -07002109 std::string cameraIdStr =
2110 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002111 if (cameraIdStr.empty()) {
2112 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002113 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002114 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2115 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2116 }
malikakashedb38962023-09-06 00:03:35 +00002117
Austin Borger7d2b9232024-07-22 14:17:14 -07002118 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2119 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002120
Austin Borger95a00152024-09-23 17:20:24 -07002121 AttributionSourceState resolvedClientAttribution(clientAttribution);
2122 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraIdStr);
2123 if (!ret.isOk()) {
2124 logRejected(cameraIdStr, getCallingPid(),
2125 clientAttribution.packageName.value_or("<unknown>"),
2126 toStdString(ret.toString8()));
2127 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002128 }
2129
Austin Borger95a00152024-09-23 17:20:24 -07002130 const int clientPid = resolvedClientAttribution.pid;
2131 const int clientUid = resolvedClientAttribution.uid;
2132 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2133
2134 logConnectionAttempt(clientPid, clientPackageName, cameraIdStr, API_1);
Austin Borgerb01a8702024-07-22 16:20:34 -07002135
Ruben Brunkcc776712015-02-17 20:18:47 -08002136 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002137 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borger7d2b9232024-07-22 14:17:14 -07002138 clientPackageName, /*systemNativeClient*/ false, {},
Austin Borgerb01a8702024-07-22 16:20:34 -07002139 clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002140 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borger7d2b9232024-07-22 14:17:14 -07002141 rotationOverride, forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002142
Biswarup Pal37a75182024-01-16 15:53:35 +00002143 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002144 logRejected(cameraIdStr, getCallingPid(),
2145 clientAttribution.packageName.value_or("<unknown>"),
2146 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002147 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002148 }
2149
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002150 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002151
2152 const sp<IServiceManager> sm(defaultServiceManager());
2153 const auto& mActivityManager = getActivityManager();
2154 if (mActivityManager) {
2155 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002156 getCallingUid(),
2157 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002158 }
2159
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002160 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002161}
2162
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002163bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2164 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002165 // If the client is not a vendor client, don't add listener if
2166 // a) the camera is a publicly hidden secure camera OR
2167 // b) the camera is a system only camera and the client doesn't
2168 // have android.permission.SYSTEM_CAMERA permissions.
2169 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2170 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002171 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002172 return true;
2173 }
2174 return false;
2175}
2176
Austin Borgered99f642023-06-01 16:51:35 -07002177bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002178 // Rules for rejection:
2179 // 1) If cameraserver tries to access this camera device, accept the
2180 // connection.
2181 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002182 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002183 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2184 // and the serving thread is a non hwbinder thread, the client must have
2185 // android.permission.SYSTEM_CAMERA permissions to connect.
2186
Austin Borger22c5c852024-03-08 13:31:36 -08002187 int cPid = getCallingPid();
2188 int cUid = getCallingUid();
2189 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002190 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2191 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002192 // This isn't a known camera ID, so it's not a system camera
2193 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2194 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002195 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002196
2197 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002198 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002199 return false;
2200 }
2201 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002202 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002203 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2204 return true;
2205 }
2206 // (3) Here we only check for permissions if it is a system only camera device. This is since
2207 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2208 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2209 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002210 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002211 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002212 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2213 cameraId.c_str());
2214 return true;
2215 }
2216
2217 return false;
2218}
2219
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002220Status CameraService::connectDevice(
2221 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002222 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002223 int oomScoreOffset, int targetSdkVersion,
2224 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002225 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002226 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002227 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002228 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002229 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002230 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002231 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002232 int callingPid = getCallingPid();
2233 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002234 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002235 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002236 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002237 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002238 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002239 }
Austin Borger249e6592024-03-10 22:28:11 -07002240
Austin Borger65e64642024-06-11 15:58:23 -07002241 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2242 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002243 if (!cameraIdOptional.has_value()) {
2244 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002245 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002246 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2247 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2248 }
2249 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002250
Austin Borger7d2b9232024-07-22 14:17:14 -07002251 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
Austin Borger7d2b9232024-07-22 14:17:14 -07002252
Austin Borger95a00152024-09-23 17:20:24 -07002253 AttributionSourceState resolvedClientAttribution(clientAttribution);
2254 if (!flags::use_context_attribution_source()) {
2255 resolvedClientAttribution.pid = USE_CALLING_PID;
2256 }
2257 ret = resolveAttributionSource(resolvedClientAttribution, __FUNCTION__, cameraId);
2258 if (!ret.isOk()) {
2259 logRejected(cameraId, getCallingPid(), clientAttribution.packageName.value_or(""),
2260 toStdString(ret.toString8()));
2261 return ret;
Austin Borgerb01a8702024-07-22 16:20:34 -07002262 }
2263
Austin Borger95a00152024-09-23 17:20:24 -07002264 const int clientPid = resolvedClientAttribution.pid;
2265 const int clientUid = resolvedClientAttribution.uid;
2266 const std::string& clientPackageName = *resolvedClientAttribution.packageName;
2267 userid_t clientUserId = multiuser_get_user_id(resolvedClientAttribution.uid);
Austin Borgerb01a8702024-07-22 16:20:34 -07002268
Austin Borger95a00152024-09-23 17:20:24 -07002269 logConnectionAttempt(clientPid, clientPackageName, cameraId, API_2);
Austin Borgerb01a8702024-07-22 16:20:34 -07002270
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002271 if (oomScoreOffset < 0) {
Austin Borger95a00152024-09-23 17:20:24 -07002272 std::string msg = fmt::sprintf(
2273 "Cannot increase the priority of a client %s pid %d for "
2274 "camera id %s",
2275 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002276 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2277 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002278 }
2279
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002280 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2281 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002282 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2283 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002284 std::string msg = "Camera disabled by device policy";
2285 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2286 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002287 }
2288
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002289 // enforce system camera permissions
Austin Borger95a00152024-09-23 17:20:24 -07002290 if (oomScoreOffset > 0 && !hasPermissionsForSystemCamera(cameraId, clientPid, callingUid) &&
2291 !isTrustedCallingUid(callingUid)) {
2292 std::string msg = fmt::sprintf(
2293 "Cannot change the priority of a client %s pid %d for "
2294 "camera id %s without SYSTEM_CAMERA permissions",
2295 clientPackageName.c_str(), clientPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002296 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2297 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002298 }
2299
Austin Borger95a00152024-09-23 17:20:24 -07002300 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks, CameraDeviceClient>(
2301 cameraCb, cameraId, /*api1CameraId*/ -1, clientPackageName, systemNativeClient,
2302 resolvedClientAttribution.attributionTag, clientUid, clientPid, API_2,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002303 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger95a00152024-09-23 17:20:24 -07002304 /*forceSlowJpegMode*/ false, unresolvedCameraId, isNonSystemNdk, /*out*/ client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002305
Biswarup Pal37a75182024-01-16 15:53:35 +00002306 if (!ret.isOk()) {
Austin Borger95a00152024-09-23 17:20:24 -07002307 logRejected(cameraId, clientPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002308 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002309 }
2310
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002311 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002312 Mutex::Autolock lock(mServiceLock);
2313
2314 // Clear the previous cached logs and reposition the
2315 // file offset to beginning of the file to log new data.
2316 // If either truncate or lseek fails, close the previous file and create a new one.
2317 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2318 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2319 // Close the previous memfd.
2320 close(mMemFd);
2321 // If failure to wipe the data, then create a new file and
2322 // assign the new value to mMemFd.
2323 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2324 if (mMemFd == -1) {
2325 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2326 }
2327 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002328 const sp<IServiceManager> sm(defaultServiceManager());
2329 const auto& mActivityManager = getActivityManager();
2330 if (mActivityManager) {
2331 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002332 callingUid,
2333 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002334 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002335 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002336}
2337
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002338bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2339 int callingPid, int callingUid) {
2340 if (!isAutomotiveDevice()) {
2341 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2342 }
2343
2344 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2345 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2346 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2347 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2348 "using camera %s", callingUid, cam_id.c_str());
2349 return false;
2350 }
2351
2352 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2353 return true;
2354 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2355 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002356 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2357 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002358 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2359 return false;
2360 } else {
2361 return true;
2362 }
2363 }
2364 return false;
2365}
2366
Austin Borger7d2b9232024-07-22 14:17:14 -07002367void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
Austin Borger95a00152024-09-23 17:20:24 -07002368 const std::string& cameraId,
2369 apiLevel effectiveApiLevel) const {
Austin Borger7d2b9232024-07-22 14:17:14 -07002370 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borger95a00152024-09-23 17:20:24 -07002371 "Camera API version %d",
2372 clientPid, clientPackageName.c_str(), cameraId.c_str(),
2373 static_cast<int>(effectiveApiLevel));
Austin Borger7d2b9232024-07-22 14:17:14 -07002374}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002375
Austin Borger7d2b9232024-07-22 14:17:14 -07002376template<class CALLBACK, class CLIENT>
2377Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2378 int api1CameraId, const std::string& clientPackageName, bool systemNativeClient,
2379 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2380 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2381 int rotationOverride, bool forceSlowJpegMode,
2382 const std::string& originalCameraId, bool isNonSystemNdk, /*out*/sp<CLIENT>& device) {
2383 binder::Status ret = binder::Status::ok();
2384
Shuzhen Wang316781a2020-08-18 18:11:01 -07002385 nsecs_t openTimeNs = systemTime();
2386
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002387 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002388 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002389 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002390
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002391 {
2392 // Acquire mServiceLock and prevent other clients from connecting
2393 std::unique_ptr<AutoConditionLock> lock =
2394 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2395
2396 if (lock == nullptr) {
2397 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2398 , clientPid);
2399 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2400 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002401 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002402 }
2403
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002404 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002405 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002406 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002407 return ret;
2408 }
2409
2410 // Check the shim parameters after acquiring lock, if they have already been updated and
2411 // we were doing a shim update, return immediately
2412 if (shimUpdateOnly) {
2413 auto cameraState = getCameraState(cameraId);
2414 if (cameraState != nullptr) {
2415 if (!cameraState->getShimParams().isEmpty()) return ret;
2416 }
2417 }
2418
2419 status_t err;
2420
2421 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002422 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002423 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002424 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2425 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002426 switch (err) {
2427 case -ENODEV:
2428 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2429 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002430 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002431 case -EBUSY:
2432 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2433 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002434 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002435 case -EUSERS:
2436 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2437 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002438 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002439 default:
2440 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2441 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002442 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002443 }
2444 }
2445
2446 if (clientTmp.get() != nullptr) {
2447 // Handle special case for API1 MediaRecorder where the existing client is returned
2448 device = static_cast<CLIENT*>(clientTmp.get());
2449 return ret;
2450 }
2451
2452 // give flashlight a chance to close devices if necessary.
2453 mFlashlight->prepareDeviceOpen(cameraId);
2454
Austin Borger18b30a72022-10-27 12:20:29 -07002455 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002456 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002457 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002458 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002459 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002460 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002461 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002462 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002463 }
2464
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002465 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002466 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002467 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002468
Austin Borger6e831c42024-07-22 13:07:56 -07002469 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2470 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002471 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002472 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger7d2b9232024-07-22 14:17:14 -07002473 orientation, getCallingPid(), clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002474 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002475 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002476 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002477 return ret;
2478 }
2479 client = static_cast<CLIENT*>(tmp.get());
2480
2481 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2482 __FUNCTION__);
2483
Austin Borgered99f642023-06-01 16:51:35 -07002484 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002485 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002486 if (err != OK) {
2487 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002488 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002489 mServiceLock.unlock();
2490 client->disconnect();
2491 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002492 switch(err) {
2493 case BAD_VALUE:
2494 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002495 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002496 case -EBUSY:
2497 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002498 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002499 case -EUSERS:
2500 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2501 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002502 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002503 case PERMISSION_DENIED:
2504 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002505 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002506 case -EACCES:
2507 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002508 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002509 case -ENODEV:
2510 default:
2511 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002512 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002513 strerror(-err), err);
2514 }
2515 }
2516
2517 // Update shim paremeters for legacy clients
2518 if (effectiveApiLevel == API_1) {
2519 // Assume we have always received a Client subclass for API1
2520 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2521 String8 rawParams = shimClient->getParameters();
2522 CameraParameters params(rawParams);
2523
2524 auto cameraState = getCameraState(cameraId);
2525 if (cameraState != nullptr) {
2526 cameraState->setShimParams(params);
2527 } else {
2528 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002529 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002530 }
2531 }
2532
Ravneetaeb20dc2022-03-30 05:33:03 +00002533 // Enable/disable camera service watchdog
2534 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2535
Emilian Peev6d45db82024-01-18 20:11:54 +00002536 CameraMetadata chars;
2537 bool rotateAndCropSupported = true;
2538 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002539 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002540 if (err == OK) {
2541 auto availableRotateCropEntry = chars.find(
2542 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2543 if (availableRotateCropEntry.count <= 1) {
2544 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002545 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002546 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002547 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2548 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002549 }
2550
Emilian Peev6d45db82024-01-18 20:11:54 +00002551 if (rotateAndCropSupported) {
2552 // Set rotate-and-crop override behavior
2553 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2554 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002555 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2556 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002557 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2558 switch (portraitRotation) {
2559 case 90:
2560 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2561 break;
2562 case 180:
2563 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2564 break;
2565 case 270:
2566 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2567 break;
2568 default:
2569 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2570 break;
2571 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002572 // Here we're communicating to the client the chosen rotate
2573 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002574 client->setRotateAndCropOverride(rotateAndCropMode);
2575 } else {
2576 client->setRotateAndCropOverride(
2577 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2578 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2579 }
2580 }
2581
2582 bool autoframingSupported = true;
2583 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2584 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2585 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2586 autoframingSupported = false;
2587 }
2588
2589 if (autoframingSupported) {
2590 // Set autoframing override behaviour
2591 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2592 client->setAutoframingOverride(mOverrideAutoframingMode);
2593 } else {
2594 client->setAutoframingOverride(
2595 mCameraServiceProxyWrapper->getAutoframingOverride(
2596 clientPackageName));
2597 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002598 }
2599
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002600 bool isCameraPrivacyEnabled;
2601 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002602 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002603 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
Austin Borger95a00152024-09-23 17:20:24 -07002604 toString16(client->getPackageName()), cameraId, clientPid, clientUid);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002605 } else {
2606 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002607 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002608 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002609
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002610 if (client->supportsCameraMute()) {
2611 client->setCameraMute(
2612 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2613 } else if (isCameraPrivacyEnabled) {
2614 // no camera mute supported, but privacy is on! => disconnect
2615 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2616 client->getPackageName().c_str(), cameraId.c_str());
2617 // Do not hold mServiceLock while disconnecting clients, but
2618 // retain the condition blocking other clients from connecting
2619 // in mServiceLockWrapper if held.
2620 mServiceLock.unlock();
2621 // Clear caller identity temporarily so client disconnect PID
2622 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002623 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002624 // Note AppOp to trigger the "Unblock" dialog
2625 client->noteAppOp();
2626 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002627 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002628 // Reacquire mServiceLock
2629 mServiceLock.lock();
2630
2631 return STATUS_ERROR_FMT(ERROR_DISABLED,
2632 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002633 }
2634
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002635 if (shimUpdateOnly) {
2636 // If only updating legacy shim parameters, immediately disconnect client
2637 mServiceLock.unlock();
2638 client->disconnect();
2639 mServiceLock.lock();
2640 } else {
2641 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002642 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002643 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002644
2645 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002646 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002647 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002648 } // lock is destroyed, allow further connect calls
2649
2650 // Important: release the mutex here so the client can call back into the service from its
2651 // destructor (can be at the end of the call)
2652 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002653
2654 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002655 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002656 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002657
Cliff Wud3a05312021-04-26 23:07:31 +08002658 {
2659 Mutex::Autolock lock(mInjectionParametersLock);
2660 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2661 mInjectionInitPending = false;
2662 status_t res = NO_ERROR;
2663 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2664 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002665 sp<BasicClient> clientSp = clientDescriptor->getValue();
2666 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2667 if(res != OK) {
2668 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2669 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002670 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002671 }
2672 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002673 if (res != OK) {
2674 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2675 }
2676 } else {
2677 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002678 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002679 res = NO_INIT;
2680 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2681 }
2682 }
2683 }
2684
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002685 return ret;
2686}
2687
Austin Borgered99f642023-06-01 16:51:35 -07002688status_t CameraService::addOfflineClient(const std::string &cameraId,
2689 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002690 if (offlineClient.get() == nullptr) {
2691 return BAD_VALUE;
2692 }
2693
2694 {
2695 // Acquire mServiceLock and prevent other clients from connecting
2696 std::unique_ptr<AutoConditionLock> lock =
2697 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2698
2699 if (lock == nullptr) {
2700 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2701 , __FUNCTION__, offlineClient->getClientPid());
2702 return TIMED_OUT;
2703 }
2704
2705 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2706 if (onlineClientDesc.get() == nullptr) {
2707 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2708 cameraId.c_str());
2709 return BAD_VALUE;
2710 }
2711
2712 // Offline clients do not evict or conflict with other online devices. Resource sharing
2713 // conflicts are handled by the camera provider which will either succeed or fail before
2714 // reaching this method.
2715 const auto& onlinePriority = onlineClientDesc->getPriority();
2716 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2717 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002718 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002719 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002720 // native clients don't have offline processing support.
2721 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002722 if (offlineClientDesc == nullptr) {
2723 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2724 return BAD_VALUE;
2725 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002726
2727 // Allow only one offline device per camera
2728 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2729 if (!incompatibleClients.empty()) {
2730 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2731 return BAD_VALUE;
2732 }
2733
Austin Borgered99f642023-06-01 16:51:35 -07002734 std::string monitorTags = isClientWatched(offlineClient.get())
2735 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002736 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002737 if (err != OK) {
2738 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2739 return err;
2740 }
2741
2742 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2743 if (evicted.size() > 0) {
2744 for (auto& i : evicted) {
2745 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002746 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002747 }
2748
2749 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2750 "properly", __FUNCTION__);
2751
2752 return BAD_VALUE;
2753 }
2754
2755 logConnectedOffline(offlineClientDesc->getKey(),
2756 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002757 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002758
2759 sp<IBinder> remoteCallback = offlineClient->getRemote();
2760 if (remoteCallback != nullptr) {
2761 remoteCallback->linkToDeath(this);
2762 }
2763 } // lock is destroyed, allow further connect calls
2764
2765 return OK;
2766}
2767
Austin Borgered99f642023-06-01 16:51:35 -07002768Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002769 int32_t torchStrength, const sp<IBinder>& clientBinder,
2770 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002771 Mutex::Autolock lock(mServiceLock);
2772
2773 ATRACE_CALL();
2774 if (clientBinder == nullptr) {
2775 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2776 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2777 "Torch client binder in null.");
2778 }
2779
Austin Borger22c5c852024-03-08 13:31:36 -08002780 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002781 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2782 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002783 if (!cameraIdOptional.has_value()) {
2784 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002785 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002786 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2787 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2788 }
2789 std::string cameraId = cameraIdOptional.value();
2790
Austin Borgered99f642023-06-01 16:51:35 -07002791 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002792 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002793 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002794 }
2795
2796 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002797 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002798 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002799 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002800 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002801 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002802 }
2803
2804 StatusInternal cameraStatus = state->getStatus();
2805 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2806 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002807 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002808 (int)cameraStatus);
2809 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002810 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002811 }
2812
2813 {
2814 Mutex::Autolock al(mTorchStatusMutex);
2815 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002816 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002817 if (err != OK) {
2818 if (err == NAME_NOT_FOUND) {
2819 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002820 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002821 }
2822 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002823 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002824 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2825 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002826 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002827 }
2828
2829 if (status == TorchModeStatus::NOT_AVAILABLE) {
2830 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2831 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002832 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002833 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2834 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002835 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002836 } else {
2837 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002838 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002839 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2840 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002841 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002842 }
2843 }
2844 }
2845
2846 {
2847 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002848 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002849 }
2850 // Check if the current torch strength level is same as the new one.
2851 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002852 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002853
Austin Borgered99f642023-06-01 16:51:35 -07002854 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002855
2856 if (err != OK) {
2857 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002858 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002859 switch (err) {
2860 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002861 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2862 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002863 errorCode = ERROR_ILLEGAL_ARGUMENT;
2864 break;
2865 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002866 msg = fmt::sprintf("Camera \"%s\" is in use",
2867 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002868 errorCode = ERROR_CAMERA_IN_USE;
2869 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002870 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002871 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002872 "valid range.", torchStrength);
2873 errorCode = ERROR_ILLEGAL_ARGUMENT;
2874 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002875 default:
Austin Borgered99f642023-06-01 16:51:35 -07002876 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002877 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002878 }
Austin Borgered99f642023-06-01 16:51:35 -07002879 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2880 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002881 }
2882
2883 {
2884 // update the link to client's death
2885 // Store the last client that turns on each camera's torch mode.
2886 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002887 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002888 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002889 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002890 } else {
2891 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2892 mTorchClientMap.replaceValueAt(index, clientBinder);
2893 }
2894 clientBinder->linkToDeath(this);
2895 }
2896
Austin Borger22c5c852024-03-08 13:31:36 -08002897 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002898 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002899 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002900 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002901 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002902 }
2903 return Status::ok();
2904}
2905
malikakash73125c62023-07-21 22:44:34 +00002906Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002907 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2908 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002909 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002910
2911 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002912 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002913 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002914 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2915 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002916 }
2917
Austin Borger22c5c852024-03-08 13:31:36 -08002918 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002919 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2920 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002921 if (!cameraIdOptional.has_value()) {
2922 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002923 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002924 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2925 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2926 }
2927 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002928
Austin Borgered99f642023-06-01 16:51:35 -07002929 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002930 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002931 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002932 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002933 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002934 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002935 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002936 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002937 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002938 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002939 }
2940
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002941 StatusInternal cameraStatus = state->getStatus();
2942 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002943 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002944 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2945 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002946 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002947 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002948 }
2949
2950 {
2951 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002952 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002953 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002954 if (err != OK) {
2955 if (err == NAME_NOT_FOUND) {
2956 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002957 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002958 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002959 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002960 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002961 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002962 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002963 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002964 }
2965
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002966 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002967 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002968 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002969 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002970 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2971 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002972 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002973 } else {
2974 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002975 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002976 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2977 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002978 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002979 }
2980 }
2981 }
2982
Ruben Brunk99e69712015-05-26 17:25:07 -07002983 {
2984 // Update UID map - this is used in the torch status changed callbacks, so must be done
2985 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07002986 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002987 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07002988 }
2989
Austin Borgered99f642023-06-01 16:51:35 -07002990 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07002991
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002992 if (err != OK) {
2993 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002994 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002995 switch (err) {
2996 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002997 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
2998 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002999 errorCode = ERROR_ILLEGAL_ARGUMENT;
3000 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003001 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003002 msg = fmt::sprintf("Camera \"%s\" is in use",
3003 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003004 errorCode = ERROR_CAMERA_IN_USE;
3005 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003006 default:
Austin Borgered99f642023-06-01 16:51:35 -07003007 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003008 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003009 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003010 errorCode = ERROR_INVALID_OPERATION;
3011 }
Austin Borgered99f642023-06-01 16:51:35 -07003012 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3013 logServiceError(msg, errorCode);
3014 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003015 }
3016
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003017 {
3018 // update the link to client's death
3019 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003020 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003021 if (enabled) {
3022 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003023 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003024 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003025 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003026 mTorchClientMap.replaceValueAt(index, clientBinder);
3027 }
3028 clientBinder->linkToDeath(this);
3029 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003030 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003031 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003032 }
3033
Austin Borger22c5c852024-03-08 13:31:36 -08003034 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003035 std::string torchState = enabled ? "on" : "off";
3036 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3037 torchState.c_str(), clientPid);
3038 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003039 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003040}
3041
Austin Borgered99f642023-06-01 16:51:35 -07003042void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3043 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3044 mTorchUidMap[cameraId].first = uid;
3045 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003046 } else {
3047 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003048 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003049 }
3050}
3051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003052Status CameraService::notifySystemEvent(int32_t eventId,
3053 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003054 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003055 const int selfPid = getpid();
3056
3057 // Permission checks
3058 if (pid != selfPid) {
3059 // Ensure we're being called by system_server, or similar process with
3060 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003061 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003062 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003063 ALOGE("Permission Denial: cannot send updates to camera service about system"
3064 " events from pid=%d, uid=%d", pid, uid);
3065 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003066 "No permission to send updates to camera service about system events"
3067 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003068 }
3069 }
3070
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003071 ATRACE_CALL();
3072
Ruben Brunk36597b22015-03-20 22:15:57 -07003073 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003074 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003075 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003076 // from a system server crash
3077 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003078 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003079 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003080 break;
3081 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003082 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3083 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003084 if (args.size() != 1) {
3085 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3086 "USB Device Event requires 1 argument");
3087 }
3088
Valentin Iftime29e2e152021-08-13 15:17:33 +02003089 // Notify CameraProviderManager for lazy HALs
3090 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3091 std::to_string(args[0]));
3092 break;
3093 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003094 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003095 default: {
3096 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3097 eventId);
3098 break;
3099 }
3100 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003101 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003102}
3103
Emilian Peev53722fa2019-02-22 17:47:20 -08003104void CameraService::notifyMonitoredUids() {
3105 Mutex::Autolock lock(mStatusListenerLock);
3106
3107 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003108 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003109 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3110 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003111 }
3112}
3113
Austin Borgerdddb7552023-03-30 17:53:01 -07003114void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3115 Mutex::Autolock lock(mStatusListenerLock);
3116
3117 for (const auto& it : mListenerList) {
3118 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3119 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3120 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3121 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3122 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3123 }
3124 }
3125}
3126
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003127Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003128 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003129 const int selfPid = getpid();
3130
3131 // Permission checks
3132 if (pid != selfPid) {
3133 // Ensure we're being called by system_server, or similar process with
3134 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003135 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003136 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003137 ALOGE("Permission Denial: cannot send updates to camera service about device"
3138 " state changes from pid=%d, uid=%d", pid, uid);
3139 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3140 "No permission to send updates to camera service about device state"
3141 " changes from pid=%d, uid=%d", pid, uid);
3142 }
3143 }
3144
3145 ATRACE_CALL();
3146
Austin Borger18b30a72022-10-27 12:20:29 -07003147 {
3148 Mutex::Autolock lock(mServiceLock);
3149 mDeviceState = newState;
3150 }
3151
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003152 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003153
3154 return Status::ok();
3155}
3156
Emilian Peev8b64f282021-03-25 16:49:57 -07003157Status CameraService::notifyDisplayConfigurationChange() {
3158 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003159 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003160 const int selfPid = getpid();
3161
3162 // Permission checks
3163 if (callingPid != selfPid) {
3164 // Ensure we're being called by system_server, or similar process with
3165 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003166 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003167 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003168 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3169 " changes from pid=%d, uid=%d", callingPid, uid);
3170 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3171 "No permission to send updates to camera service about orientation"
3172 " changes from pid=%d, uid=%d", callingPid, uid);
3173 }
3174 }
3175
3176 Mutex::Autolock lock(mServiceLock);
3177
3178 // Don't do anything if rotate-and-crop override via cmd is active
3179 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3180
3181 const auto clients = mActiveClientManager.getAll();
3182 for (auto& current : clients) {
3183 if (current != nullptr) {
3184 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003185 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3186 basicClient->setRotateAndCropOverride(
3187 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3188 basicClient->getPackageName(),
3189 basicClient->getCameraFacing(),
3190 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003191 }
3192 }
3193 }
3194
3195 return Status::ok();
3196}
3197
3198Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003199 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3200 ATRACE_CALL();
3201 if (!concurrentCameraIds) {
3202 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3203 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3204 }
3205
3206 if (!mInitialized) {
3207 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003208 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003209 return STATUS_ERROR(ERROR_DISCONNECTED,
3210 "Camera subsystem is not available");
3211 }
3212 // First call into the provider and get the set of concurrent camera
3213 // combinations
3214 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003215 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003216 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003217 std::vector<std::pair<std::string, int32_t>> validCombination;
3218 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003219 for (auto &cameraId : combination) {
3220 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003221 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003222 if (state == nullptr) {
3223 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3224 continue;
3225 }
3226 StatusInternal status = state->getStatus();
3227 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3228 continue;
3229 }
Austin Borgered99f642023-06-01 16:51:35 -07003230 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003231 continue;
3232 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003233 auto [cameraOwnerDeviceId, mappedCameraId] =
3234 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3235 if (firstDeviceId == kInvalidDeviceId) {
3236 firstDeviceId = cameraOwnerDeviceId;
3237 } else if (firstDeviceId != cameraOwnerDeviceId) {
3238 // Found an invalid combination which contains cameras with different device id's,
3239 // hence discard it.
3240 validCombination.clear();
3241 break;
3242 }
3243 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003244 }
3245 if (validCombination.size() != 0) {
3246 concurrentCameraIds->push_back(std::move(validCombination));
3247 }
3248 }
3249 return Status::ok();
3250}
3251
3252Status CameraService::isConcurrentSessionConfigurationSupported(
3253 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003254 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003255 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003256 if (!isSupported) {
3257 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3258 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3259 }
3260
3261 if (!mInitialized) {
3262 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3263 return STATUS_ERROR(ERROR_DISCONNECTED,
3264 "Camera subsystem is not available");
3265 }
3266
Biswarup Pal7d072862024-04-17 15:24:47 +00003267 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3268 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003269 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3270 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003271 if (!cameraIdOptional.has_value()) {
3272 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003273 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003274 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3275 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3276 }
3277 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3278 }
3279
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003280 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003281 int callingPid = getCallingPid();
3282 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003283 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003284 hasPermissionsForCamera(callingPid, callingUid,
3285 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003286 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003287 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003288 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3289 "android.permission.CAMERA needed to call"
3290 "isConcurrentSessionConfigurationSupported");
3291 }
3292
3293 status_t res =
3294 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003295 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3296 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003297 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003298 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003299 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003300 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3301 "support %s (%d)", strerror(-res), res);
3302 }
3303 return Status::ok();
3304}
3305
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003306Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3307 /*out*/
3308 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003309 return addListenerHelper(listener, cameraStatuses);
3310}
3311
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003312binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3313 std::vector<hardware::CameraStatus>* cameraStatuses) {
3314 return addListenerHelper(listener, cameraStatuses, false, true);
3315}
3316
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003317Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3318 /*out*/
3319 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003320 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003321 ATRACE_CALL();
3322
Igor Murashkinbfc99152013-02-27 12:55:20 -08003323 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003324
Ruben Brunk3450ba72015-06-16 11:00:37 -07003325 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003326 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003327 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003328 }
3329
Austin Borger22c5c852024-03-08 13:31:36 -08003330 auto clientPid = getCallingPid();
3331 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003332 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003333
Igor Murashkinbfc99152013-02-27 12:55:20 -08003334 Mutex::Autolock lock(mServiceLock);
3335
Ruben Brunkcc776712015-02-17 20:18:47 -08003336 {
3337 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003338 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003339 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003340 ALOGW("%s: Tried to add listener %p which was already subscribed",
3341 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003342 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003343 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003344 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003345
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003346 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003347 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3348 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003349 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003350 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003351 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003352 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003353 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3354 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3355 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003356 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003357 // The listener still needs to be added to the list of listeners, regardless of what
3358 // permissions the listener process has / whether it is a vendor listener. Since it might be
3359 // eligible to listen to other camera ids.
3360 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003361 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003362 }
3363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003364 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003365 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003366 Mutex::Autolock lock(mCameraStatesLock);
3367 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003368 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3369 auto [deviceId, mappedCameraId] =
3370 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3371
3372 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003373 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003374 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3375 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003376 }
3377 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003378 // Remove the camera statuses that should be hidden from the client, we do
3379 // this after collecting the states in order to avoid holding
3380 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3381 // the same time.
3382 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3383 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003384 std::string cameraId = s.cameraId;
3385 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003386 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003387 if (!cameraIdOptional.has_value()) {
3388 std::string msg =
3389 fmt::sprintf(
3390 "Camera %s: Invalid camera id for device id %d",
3391 s.cameraId.c_str(), s.deviceId);
3392 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3393 return true;
3394 }
3395 cameraId = cameraIdOptional.value();
3396 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3397 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3398 ALOGE("%s: Invalid camera id %s, skipping status update",
3399 __FUNCTION__, s.cameraId.c_str());
3400 return true;
3401 }
3402 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3403 clientUid);
3404 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003405
Biswarup Pal37a75182024-01-16 15:53:35 +00003406 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003407 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003408 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003409 // Add only default device cameras here, as virtual cameras currently don't support torch
3410 // anyway. Note that this is a simplification of the implementation here, and we should
3411 // change this when virtual cameras support torch.
3412 if (s.deviceId == kDefaultDeviceId) {
3413 idsChosenForCallback.insert(s.cameraId);
3414 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003415 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003416
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003417 /*
3418 * Immediately signal current torch status to this listener only
3419 * This may be a subset of all the devices, so don't include it in the response directly
3420 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003421 {
3422 Mutex::Autolock al(mTorchStatusMutex);
3423 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003424 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003425 // The camera id is visible to the client. Fine to send torch
3426 // callback.
3427 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003428 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3429 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003430 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003431 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003432 }
3433
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003434 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003435}
Ruben Brunkcc776712015-02-17 20:18:47 -08003436
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003437Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003438 ATRACE_CALL();
3439
Igor Murashkinbfc99152013-02-27 12:55:20 -08003440 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3441
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003442 if (listener == 0) {
3443 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003444 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003445 }
3446
Igor Murashkinbfc99152013-02-27 12:55:20 -08003447 Mutex::Autolock lock(mServiceLock);
3448
Ruben Brunkcc776712015-02-17 20:18:47 -08003449 {
3450 Mutex::Autolock lock(mStatusListenerLock);
3451 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003452 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003453 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003454 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003455 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003456 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003457 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003458 }
3459 }
3460
3461 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3462 __FUNCTION__, listener.get());
3463
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003464 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003465}
3466
Austin Borgered99f642023-06-01 16:51:35 -07003467Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003468
3469 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003470 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3471
3472 if (parameters == NULL) {
3473 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003474 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003475 }
3476
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003477 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003478
3479 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003480 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003481 // Error logged by caller
3482 return ret;
3483 }
3484
3485 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003486
Austin Borgered99f642023-06-01 16:51:35 -07003487 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003488
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003489 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003490}
3491
malikakash98260df2024-05-10 23:33:57 +00003492Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003493 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003494 ATRACE_CALL();
3495
Austin Borgered99f642023-06-01 16:51:35 -07003496 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003497
3498 switch (apiVersion) {
3499 case API_VERSION_1:
3500 case API_VERSION_2:
3501 break;
3502 default:
Austin Borgered99f642023-06-01 16:51:35 -07003503 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3504 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3505 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003506 }
3507
Austin Borger18b30a72022-10-27 12:20:29 -07003508 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003509 auto deviceVersionAndTransport =
3510 getDeviceVersion(cameraId,
3511 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3512 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003513 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003514 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3515 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3516 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003517 }
3518 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3519 int deviceVersion = deviceVersionAndTransport.first;
3520 switch (deviceVersion) {
3521 case CAMERA_DEVICE_API_VERSION_1_0:
3522 case CAMERA_DEVICE_API_VERSION_3_0:
3523 case CAMERA_DEVICE_API_VERSION_3_1:
3524 if (apiVersion == API_VERSION_2) {
3525 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003526 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003527 *isSupported = false;
3528 } else { // if (apiVersion == API_VERSION_1) {
3529 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003530 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003531 *isSupported = true;
3532 }
3533 break;
3534 case CAMERA_DEVICE_API_VERSION_3_2:
3535 case CAMERA_DEVICE_API_VERSION_3_3:
3536 case CAMERA_DEVICE_API_VERSION_3_4:
3537 case CAMERA_DEVICE_API_VERSION_3_5:
3538 case CAMERA_DEVICE_API_VERSION_3_6:
3539 case CAMERA_DEVICE_API_VERSION_3_7:
3540 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003541 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003542 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003543 break;
3544 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003545 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3546 deviceVersion, cameraId.c_str());
3547 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3548 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003549 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003550 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003551 } else {
3552 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003553 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003554 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003555}
3556
malikakash98260df2024-05-10 23:33:57 +00003557Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003558 /*out*/ bool *isSupported) {
3559 ATRACE_CALL();
3560
Austin Borgered99f642023-06-01 16:51:35 -07003561 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3562 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003563
3564 return Status::ok();
3565}
3566
Cliff Wud8cae102021-03-11 01:37:42 +08003567Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003568 const std::string& packageName, const std::string& internalCamId,
3569 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003570 const sp<ICameraInjectionCallback>& callback,
3571 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003572 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003573 ATRACE_CALL();
3574
Austin Borgered99f642023-06-01 16:51:35 -07003575 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003576 const int pid = getCallingPid();
3577 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003578 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3579 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003580 "Permission Denial: no permission to inject camera");
3581 }
3582
3583 // Do not allow any camera injection that injects or replaces a virtual camera.
3584 auto [deviceIdForInternalCamera, _] =
3585 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3586 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3587 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3588 "Cannot replace a virtual camera");
3589 }
3590 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3591 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3592 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3593 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3594 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003595 }
3596
3597 ALOGV(
3598 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3599 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003600 __FUNCTION__, packageName.c_str(),
3601 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003602
Cliff Wud3a05312021-04-26 23:07:31 +08003603 {
3604 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003605 mInjectionInternalCamId = internalCamId;
3606 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003607 mInjectionStatusListener->addListener(callback);
3608 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003609 status_t res = NO_ERROR;
3610 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3611 // If the client already exists, we can directly connect to the camera device through the
3612 // client's injectCamera(), otherwise we need to wait until the client is established
3613 // (execute connectHelper()) before injecting the camera to the camera device.
3614 if (clientDescriptor != nullptr) {
3615 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003616 sp<BasicClient> clientSp = clientDescriptor->getValue();
3617 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3618 if(res != OK) {
3619 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3620 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003621 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003622 }
3623 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003624 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003625 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3626 }
3627 } else {
3628 mInjectionInitPending = true;
3629 }
3630 }
Cliff Wud8cae102021-03-11 01:37:42 +08003631
Cliff Wud3a05312021-04-26 23:07:31 +08003632 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003633}
3634
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003635Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003636 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003637 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3638 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3639 return Status::ok();
3640}
3641
Ruben Brunkcc776712015-02-17 20:18:47 -08003642void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003643 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003644 for (auto& i : mActiveClientManager.getAll()) {
3645 auto clientSp = i->getValue();
3646 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003647 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003648 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003649 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003650 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003651 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003652}
3653
Ruben Brunkcc776712015-02-17 20:18:47 -08003654bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003655 bool ret = false;
3656 {
3657 // Acquire mServiceLock and prevent other clients from connecting
3658 std::unique_ptr<AutoConditionLock> lock =
3659 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003660
Ruben Brunkcc776712015-02-17 20:18:47 -08003661 std::vector<sp<BasicClient>> evicted;
3662 for (auto& i : mActiveClientManager.getAll()) {
3663 auto clientSp = i->getValue();
3664 if (clientSp.get() == nullptr) {
3665 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3666 mActiveClientManager.remove(i);
3667 continue;
3668 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003669 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003670 mActiveClientManager.remove(i);
3671 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003672
Ruben Brunkcc776712015-02-17 20:18:47 -08003673 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003674 clientSp->notifyError(
3675 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003676 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003677 }
3678 }
3679
Ruben Brunkcc776712015-02-17 20:18:47 -08003680 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3681 // other clients from connecting in mServiceLockWrapper if held
3682 mServiceLock.unlock();
3683
Ruben Brunk36597b22015-03-20 22:15:57 -07003684 // Do not clear caller identity, remote caller should be client proccess
3685
Ruben Brunkcc776712015-02-17 20:18:47 -08003686 for (auto& i : evicted) {
3687 if (i.get() != nullptr) {
3688 i->disconnect();
3689 ret = true;
3690 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003691 }
3692
Ruben Brunkcc776712015-02-17 20:18:47 -08003693 // Reacquire mServiceLock
3694 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003695
Ruben Brunkcc776712015-02-17 20:18:47 -08003696 } // lock is destroyed, allow further connect calls
3697
3698 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003699}
3700
Ruben Brunkcc776712015-02-17 20:18:47 -08003701std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003702 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003703 std::shared_ptr<CameraState> state;
3704 {
3705 Mutex::Autolock lock(mCameraStatesLock);
3706 auto iter = mCameraStates.find(cameraId);
3707 if (iter != mCameraStates.end()) {
3708 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003709 }
3710 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003711 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003712}
3713
Austin Borgered99f642023-06-01 16:51:35 -07003714sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003715 // Remove from active clients list
3716 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3717 if (clientDescriptorPtr == nullptr) {
3718 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003719 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003720 return sp<BasicClient>{nullptr};
3721 }
3722
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003723 sp<BasicClient> client = clientDescriptorPtr->getValue();
3724 if (client.get() != nullptr) {
3725 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3726 }
3727 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003728}
3729
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003730void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003731 // Acquire mServiceLock and prevent other clients from connecting
3732 std::unique_ptr<AutoConditionLock> lock =
3733 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3734
Ruben Brunk6267b532015-04-30 17:44:07 -07003735 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003736 for (size_t i = 0; i < newUserIds.size(); i++) {
3737 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003738 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003739 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003740 return;
3741 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003742 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003743 }
3744
Ruben Brunka8ca9152015-04-07 14:23:40 -07003745
Ruben Brunk6267b532015-04-30 17:44:07 -07003746 if (newAllowedUsers == mAllowedUsers) {
3747 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3748 return;
3749 }
3750
3751 logUserSwitch(mAllowedUsers, newAllowedUsers);
3752
3753 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003754
3755 // Current user has switched, evict all current clients.
3756 std::vector<sp<BasicClient>> evicted;
3757 for (auto& i : mActiveClientManager.getAll()) {
3758 auto clientSp = i->getValue();
3759
3760 if (clientSp.get() == nullptr) {
3761 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3762 continue;
3763 }
3764
Ruben Brunk6267b532015-04-30 17:44:07 -07003765 // Don't evict clients that are still allowed.
3766 uid_t clientUid = clientSp->getClientUid();
3767 userid_t clientUserId = multiuser_get_user_id(clientUid);
3768 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3769 continue;
3770 }
3771
Ruben Brunk36597b22015-03-20 22:15:57 -07003772 evicted.push_back(clientSp);
3773
Ruben Brunk36597b22015-03-20 22:15:57 -07003774 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003775 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003776
Ruben Brunk36597b22015-03-20 22:15:57 -07003777 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003778 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003779 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003780 " to user switch.", i->getKey().c_str(),
3781 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003782 i->getOwnerId(), i->getPriority().getScore(),
3783 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003784
3785 }
3786
3787 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3788 // blocking other clients from connecting in mServiceLockWrapper if held.
3789 mServiceLock.unlock();
3790
3791 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003792 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003793
3794 for (auto& i : evicted) {
3795 i->disconnect();
3796 }
3797
Austin Borger22c5c852024-03-08 13:31:36 -08003798 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003799
3800 // Reacquire mServiceLock
3801 mServiceLock.lock();
3802}
Ruben Brunkcc776712015-02-17 20:18:47 -08003803
Austin Borgered99f642023-06-01 16:51:35 -07003804void CameraService::logEvent(const std::string &event) {
3805 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003806 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003807 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003808 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003809 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003810 mEventLog.add(msg);
3811 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3812 // Error event not added to the dumpsys log before
3813 mEventLog.add(msg);
3814 sServiceErrorEventSet.insert(msg);
3815 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003816}
3817
Austin Borgered99f642023-06-01 16:51:35 -07003818void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3819 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003820 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003821 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3822 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003823}
3824
Austin Borgered99f642023-06-01 16:51:35 -07003825void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3826 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003827 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003828 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3829 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003830}
3831
Austin Borgered99f642023-06-01 16:51:35 -07003832void CameraService::logConnected(const std::string &cameraId, int clientPid,
3833 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003834 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003835 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3836 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003837}
3838
Austin Borgered99f642023-06-01 16:51:35 -07003839void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3840 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003841 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003842 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3843 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003844}
3845
Austin Borgered99f642023-06-01 16:51:35 -07003846void CameraService::logRejected(const std::string &cameraId, int clientPid,
3847 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003848 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003849 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3850 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003851}
3852
Austin Borgered99f642023-06-01 16:51:35 -07003853void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3854 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003855 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003856 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3857 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003858}
3859
Ruben Brunk6267b532015-04-30 17:44:07 -07003860void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3861 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003862 std::string newUsers = toString(newUserIds);
3863 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003864 if (oldUsers.size() == 0) {
3865 oldUsers = "<None>";
3866 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003867 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003868 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3869 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003870}
3871
Austin Borgered99f642023-06-01 16:51:35 -07003872void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003873 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003874 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003875}
3876
Austin Borgered99f642023-06-01 16:51:35 -07003877void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003878 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003879 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003880}
3881
Austin Borgered99f642023-06-01 16:51:35 -07003882void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003883 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003884 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003885}
3886
Austin Borgered99f642023-06-01 16:51:35 -07003887void CameraService::logServiceError(const std::string &msg, int errorCode) {
3888 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3889 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003890}
3891
Ruben Brunk36597b22015-03-20 22:15:57 -07003892status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3893 uint32_t flags) {
3894
Mathias Agopian65ab4712010-07-14 17:59:35 -07003895 // Permission checks
3896 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003897 case SHELL_COMMAND_TRANSACTION: {
3898 int in = data.readFileDescriptor();
3899 int out = data.readFileDescriptor();
3900 int err = data.readFileDescriptor();
3901 int argc = data.readInt32();
3902 Vector<String16> args;
3903 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3904 args.add(data.readString16());
3905 }
3906 sp<IBinder> unusedCallback;
3907 sp<IResultReceiver> resultReceiver;
3908 status_t status;
3909 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3910 return status;
3911 }
3912 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3913 return status;
3914 }
3915 status = shellCommand(in, out, err, args);
3916 if (resultReceiver != nullptr) {
3917 resultReceiver->send(status);
3918 }
3919 return NO_ERROR;
3920 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003921 }
3922
3923 return BnCameraService::onTransact(code, data, reply, flags);
3924}
3925
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926// We share the media players for shutter and recording sound for all clients.
3927// A reference count is kept to determine when we will actually release the
3928// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003929sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3930 sp<MediaPlayer> mp = new MediaPlayer();
3931 status_t error;
3932 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003933 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003934 error = mp->prepare();
3935 }
3936 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003937 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003938 mp->disconnect();
3939 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003940 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003941 }
3942 return mp;
3943}
3944
username5755fea2018-12-27 09:48:08 +08003945void CameraService::increaseSoundRef() {
3946 Mutex::Autolock lock(mSoundLock);
3947 mSoundRef++;
3948}
3949
3950void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003951 ATRACE_CALL();
3952
username5755fea2018-12-27 09:48:08 +08003953 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3954 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3955 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3956 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3957 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
3958 }
3959 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
3960 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
3961 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
3962 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003963 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08003964 }
3965 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
3966 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
3967 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
3968 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
3969 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003970 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003971}
3972
username5755fea2018-12-27 09:48:08 +08003973void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07003974 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003975 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003976 if (--mSoundRef) return;
3977
3978 for (int i = 0; i < NUM_SOUNDS; i++) {
3979 if (mSoundPlayer[i] != 0) {
3980 mSoundPlayer[i]->disconnect();
3981 mSoundPlayer[i].clear();
3982 }
3983 }
3984}
3985
3986void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003987 ATRACE_CALL();
3988
Mathias Agopian65ab4712010-07-14 17:59:35 -07003989 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07003990 if (kind < 0 || kind >= NUM_SOUNDS) {
3991 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
3992 return;
3993 }
3994
Mathias Agopian65ab4712010-07-14 17:59:35 -07003995 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08003996 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07003997 sp<MediaPlayer> player = mSoundPlayer[kind];
3998 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08003999 player->seekTo(0);
4000 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004001 }
4002}
4003
4004// ----------------------------------------------------------------------------
4005
4006CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004007 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004008 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004009 const std::string& clientPackageName, bool systemNativeClient,
4010 const std::optional<std::string>& clientFeatureId,
4011 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004012 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004013 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004014 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004015 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004016 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004017 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004018 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004019 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004020 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004021 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004022 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004023{
Austin Borger22c5c852024-03-08 13:31:36 -08004024 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004025 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004026
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004027 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004028
username5755fea2018-12-27 09:48:08 +08004029 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004030
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004031 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032}
4033
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034// tear down the client
4035CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004036 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004037 mDestructionStarted = true;
4038
username5755fea2018-12-27 09:48:08 +08004039 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004040 // unconditionally disconnect. function is idempotent
4041 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004042}
4043
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004044sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4045
Igor Murashkin634a5152013-02-20 17:15:11 -08004046CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004047 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004048 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004049 const std::string& clientPackageName, bool nativeClient,
4050 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004051 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004052 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004053 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004054 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004055 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004056 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4057 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004058 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004059 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004060 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004061 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004062 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004063 mRemoteBinder(remoteCallback),
4064 mOpsActive(false),
4065 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004066{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004067 if (sCameraService == nullptr) {
4068 sCameraService = cameraService;
4069 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004070
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004071 // There are 2 scenarios in which a client won't have AppOps operations
4072 // (both scenarios : native clients)
4073 // 1) It's an system native client*, the package name will be empty
4074 // and it will return from this function in the previous if condition
4075 // (This is the same as the previously existing behavior).
4076 // 2) It is a system native client, but its package name has been
4077 // modified for debugging, however it still must not use AppOps since
4078 // the package name is not a real one.
4079 //
4080 // * system native client - native client with UID < AID_APP_START. It
4081 // doesn't exclude clients not on the system partition.
4082 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004083 mAppOpsManager = std::make_unique<AppOpsManager>();
4084 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004085
Charles Chenf075f082024-03-04 23:32:55 +00004086 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004087}
4088
4089CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004090 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004091 mDestructionStarted = true;
4092}
4093
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004094binder::Status CameraService::BasicClient::disconnect() {
4095 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004096 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004097 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004098 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004099 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004100
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004101 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004102 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004103 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004104 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004105
4106 sp<IBinder> remote = getRemote();
4107 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004108 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004109 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004110
4111 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004112 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004113 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004114 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004115 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004116
Igor Murashkincba2c162013-03-20 15:56:31 -07004117 // client shouldn't be able to call into us anymore
4118 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004119
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004120 const auto& mActivityManager = getActivityManager();
4121 if (mActivityManager) {
4122 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004123 getCallingUid(),
4124 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004125 }
4126
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004127 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004128}
4129
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004130status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4131 // No dumping of clients directly over Binder,
4132 // must go through CameraService::dump
4133 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004134 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004135 return OK;
4136}
4137
Austin Borgered99f642023-06-01 16:51:35 -07004138status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004139 // Can't watch tags directly, must go through CameraService::startWatchingTags
4140 return OK;
4141}
4142
4143status_t CameraService::BasicClient::stopWatchingTags(int) {
4144 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4145 return OK;
4146}
4147
4148status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4149 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4150 return OK;
4151}
4152
Austin Borgered99f642023-06-01 16:51:35 -07004153std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004154 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004155}
4156
Emilian Peev8b64f282021-03-25 16:49:57 -07004157int CameraService::BasicClient::getCameraFacing() const {
4158 return mCameraFacing;
4159}
4160
4161int CameraService::BasicClient::getCameraOrientation() const {
4162 return mOrientation;
4163}
Ruben Brunkcc776712015-02-17 20:18:47 -08004164
4165int CameraService::BasicClient::getClientPid() const {
4166 return mClientPid;
4167}
4168
Ruben Brunk6267b532015-04-30 17:44:07 -07004169uid_t CameraService::BasicClient::getClientUid() const {
4170 return mClientUid;
4171}
4172
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004173bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4174 // Defaults to API2.
4175 return level == API_2;
4176}
4177
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004178status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004179 {
4180 Mutex::Autolock l(mAudioRestrictionLock);
4181 mAudioRestriction = mode;
4182 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004183 sCameraService->updateAudioRestriction();
4184 return OK;
4185}
4186
4187int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004188 return sCameraService->updateAudioRestriction();
4189}
4190
4191int32_t CameraService::BasicClient::getAudioRestriction() const {
4192 Mutex::Autolock l(mAudioRestrictionLock);
4193 return mAudioRestriction;
4194}
4195
4196bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4197 switch (mode) {
4198 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4199 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4200 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4201 return true;
4202 default:
4203 return false;
4204 }
4205}
4206
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004207status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4208 if (mode == AppOpsManager::MODE_ERRORED) {
4209 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004210 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004211 return PERMISSION_DENIED;
4212 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4213 // If the calling Uid is trusted (a native service), the AppOpsManager could
4214 // return MODE_IGNORED. Do not treat such case as error.
4215 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4216 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004217
4218 bool isCameraPrivacyEnabled;
4219 if (flags::camera_privacy_allowlist()) {
4220 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4221 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4222 } else {
4223 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004224 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004225 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004226 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4227 // We prefer to successfully open the camera and perform camera muting
4228 // or blocking in connectHelper as handleAppOpMode can be called before the
4229 // connection has been fully established and at that time camera muting
4230 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004231 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004232 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4233 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4234 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4235 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004236 // Return the same error as for device policy manager rejection
4237 return -EACCES;
4238 }
4239 }
4240 return OK;
4241}
4242
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004243status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004244 ATRACE_CALL();
4245
Igor Murashkine6800ce2013-03-04 17:25:57 -08004246 {
4247 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004248 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004249 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004250 if (mAppOpsManager != nullptr) {
4251 // Notify app ops that the camera is not available
4252 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004253
Austin Borger5755d9b2024-09-09 11:15:44 -07004254 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4255 toString16(mClientPackageName),
4256 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004257
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004258 // Just check for camera acccess here on open - delay startOp until
4259 // camera frames start streaming in startCameraStreamingOps
4260 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004261 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004262 status_t res = handleAppOpMode(mode);
4263 if (res != OK) {
4264 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004265 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004266 }
4267
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004268 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004269
4270 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004271 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004272
Austin Borgerdddb7552023-03-30 17:53:01 -07004273 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004274
Shuzhen Wang695044d2020-03-06 09:02:23 -08004275 // Notify listeners of camera open/close status
4276 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4277
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004278 return OK;
4279}
4280
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004281status_t CameraService::BasicClient::startCameraStreamingOps() {
4282 ATRACE_CALL();
4283
4284 if (!mOpsActive) {
4285 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4286 return INVALID_OPERATION;
4287 }
4288 if (mOpsStreaming) {
4289 ALOGV("%s: Streaming already active!", __FUNCTION__);
4290 return OK;
4291 }
4292
4293 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004294 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004295
4296 if (mAppOpsManager != nullptr) {
4297 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004298 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4299 toString16(mClientFeatureId),
4300 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004301 status_t res = handleAppOpMode(mode);
4302 if (res != OK) {
4303 return res;
4304 }
4305 }
4306
4307 mOpsStreaming = true;
4308
4309 return OK;
4310}
4311
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004312status_t CameraService::BasicClient::noteAppOp() {
4313 ATRACE_CALL();
4314
4315 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004316 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004317
4318 // noteAppOp is only used for when camera mute is not supported, in order
4319 // to trigger the sensor privacy "Unblock" dialog
4320 if (mAppOpsManager != nullptr) {
4321 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004322 toString16(mClientPackageName), toString16(mClientFeatureId),
4323 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004324 status_t res = handleAppOpMode(mode);
4325 if (res != OK) {
4326 return res;
4327 }
4328 }
4329
4330 return OK;
4331}
4332
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004333status_t CameraService::BasicClient::finishCameraStreamingOps() {
4334 ATRACE_CALL();
4335
4336 if (!mOpsActive) {
4337 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4338 return INVALID_OPERATION;
4339 }
4340 if (!mOpsStreaming) {
4341 ALOGV("%s: Streaming not active!", __FUNCTION__);
4342 return OK;
4343 }
4344
4345 if (mAppOpsManager != nullptr) {
4346 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004347 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004348 mOpsStreaming = false;
4349 }
4350
4351 return OK;
4352}
4353
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004354status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004355 ATRACE_CALL();
4356
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004357 if (mOpsStreaming) {
4358 // Make sure we've notified everyone about camera stopping
4359 finishCameraStreamingOps();
4360 }
4361
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004362 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004363 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004364 mOpsActive = false;
4365
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004366 // This function is called when a client disconnects. This should
4367 // release the camera, but actually only if it was in a proper
4368 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004369 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004370 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004371
Ruben Brunkcc776712015-02-17 20:18:47 -08004372 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004373 sCameraService->updateStatus(StatusInternal::PRESENT,
4374 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004375 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004376 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004377 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4378 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004379 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004380 mOpsCallback.clear();
4381
Austin Borgerdddb7552023-03-30 17:53:01 -07004382 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004383
Shuzhen Wang695044d2020-03-06 09:02:23 -08004384 // Notify listeners of camera open/close status
4385 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4386
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004387 return OK;
4388}
4389
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004390void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004391 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004392 if (mAppOpsManager == nullptr) {
4393 return;
4394 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004395 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004396 if (op != AppOpsManager::OP_CAMERA) {
4397 ALOGW("Unexpected app ops notification received: %d", op);
4398 return;
4399 }
4400
4401 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004402 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004403 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004404 ALOGV("checkOp returns: %d, %s ", res,
4405 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4406 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4407 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4408 "UNKNOWN");
4409
Shuzhen Wang64900852021-02-05 09:03:29 -08004410 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004411 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4412 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004413 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004414 } else if (res == AppOpsManager::MODE_IGNORED) {
4415 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004416
Austin Borgerca1e0062023-06-28 11:32:55 -07004417 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4418 // If not visible, but still active, then we want to block instead of muting the camera.
4419 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4420 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4421
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004422 bool isCameraPrivacyEnabled;
4423 if (flags::camera_privacy_allowlist()) {
4424 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4425 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4426 } else {
4427 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004428 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004429 }
4430
4431 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004432 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4433 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4434 isCameraPrivacyEnabled);
4435 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4436 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4437 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004438 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004439 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4440 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004441 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004442 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004443 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004444 }
Evan Severson09ab4002021-02-10 14:15:19 -08004445 } else if (res == AppOpsManager::MODE_ALLOWED) {
4446 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004447 }
4448}
4449
Svet Ganova453d0d2018-01-11 15:37:58 -08004450void CameraService::BasicClient::block() {
4451 ATRACE_CALL();
4452
4453 // Reset the client PID to allow server-initiated disconnect,
4454 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004455 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004456 CaptureResultExtras resultExtras; // a dummy result (invalid)
4457 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4458 disconnect();
4459}
4460
Mathias Agopian65ab4712010-07-14 17:59:35 -07004461// ----------------------------------------------------------------------------
4462
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004463void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004464 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004465 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004466 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4467 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4468 api1ErrorCode = CAMERA_ERROR_DISABLED;
4469 }
4470 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004471 } else {
4472 ALOGE("mRemoteCallback is NULL!!");
4473 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004474}
4475
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004476// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004477binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004478 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004479 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004480}
4481
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004482bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4483 return level == API_1;
4484}
4485
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004486CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4487 mClient(client) {
4488}
4489
4490void CameraService::Client::OpsCallback::opChanged(int32_t op,
4491 const String16& packageName) {
4492 sp<BasicClient> client = mClient.promote();
4493 if (client != NULL) {
4494 client->opChanged(op, packageName);
4495 }
4496}
4497
Mathias Agopian65ab4712010-07-14 17:59:35 -07004498// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004499// UidPolicy
4500// ----------------------------------------------------------------------------
4501
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004502void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004503 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004504 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004505
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004506 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004507 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004508 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004509 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004510 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4511 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004512 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004513 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004514 if (res == OK) {
4515 mRegistered = true;
4516 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004517 } else {
4518 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004519 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004520}
4521
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004522void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004523 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004524 return;
4525 }
4526
4527 registerWithActivityManager();
4528}
4529
4530void CameraService::UidPolicy::registerSelf() {
4531 // Use check service to see if the activity service is available
4532 // If not available then register for notifications, instead of blocking
4533 // till the service is ready
4534 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004535 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004536 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004537 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004538 } else {
4539 registerWithActivityManager();
4540 }
4541}
4542
Svet Ganova453d0d2018-01-11 15:37:58 -08004543void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004544 Mutex::Autolock _l(mUidLock);
4545
Steven Moreland2f348142019-07-02 15:59:07 -07004546 mAm.unregisterUidObserver(this);
4547 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004548 mRegistered = false;
4549 mActiveUids.clear();
4550 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004551}
4552
4553void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4554 onUidIdle(uid, disabled);
4555}
4556
4557void CameraService::UidPolicy::onUidActive(uid_t uid) {
4558 Mutex::Autolock _l(mUidLock);
4559 mActiveUids.insert(uid);
4560}
4561
4562void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4563 bool deleted = false;
4564 {
4565 Mutex::Autolock _l(mUidLock);
4566 if (mActiveUids.erase(uid) > 0) {
4567 deleted = true;
4568 }
4569 }
4570 if (deleted) {
4571 sp<CameraService> service = mService.promote();
4572 if (service != nullptr) {
4573 service->blockClientsForUid(uid);
4574 }
4575 }
4576}
4577
Emilian Peev53722fa2019-02-22 17:47:20 -08004578void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004579 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004580 bool procStateChange = false;
4581 {
4582 Mutex::Autolock _l(mUidLock);
4583 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4584 mMonitoredUids[uid].procState != procState) {
4585 mMonitoredUids[uid].procState = procState;
4586 procStateChange = true;
4587 }
4588 }
4589
4590 if (procStateChange) {
4591 sp<CameraService> service = mService.promote();
4592 if (service != nullptr) {
4593 service->notifyMonitoredUids();
4594 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004595 }
4596}
4597
Austin Borgerdddb7552023-03-30 17:53:01 -07004598/**
4599 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4600 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4601 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4602 * monitoredUids. If it is revised above some other monitoredUid, signal
4603 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4604 * foreground apps in split screen - state changes will capture all other cases.
4605 */
4606void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4607 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004608 {
4609 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004610 auto it = mMonitoredUids.find(uid);
4611
4612 if (it != mMonitoredUids.end()) {
4613 if (it->second.hasCamera) {
4614 for (auto &monitoredUid : mMonitoredUids) {
4615 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004616 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004617 notifyUidSet.emplace(monitoredUid.first);
4618 }
4619 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004620 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004621 notifyUidSet.emplace(uid);
4622 } else {
4623 for (auto &monitoredUid : mMonitoredUids) {
4624 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004625 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004626 notifyUidSet.emplace(uid);
4627 }
4628 }
4629 }
4630 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004631 }
4632 }
4633
Austin Borgerdddb7552023-03-30 17:53:01 -07004634 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004635 sp<CameraService> service = mService.promote();
4636 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004637 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004638 }
4639 }
4640}
4641
Austin Borgerdddb7552023-03-30 17:53:01 -07004642/**
4643 * Register a uid for monitoring, and note whether it owns a camera.
4644 */
4645void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004646 Mutex::Autolock _l(mUidLock);
4647 auto it = mMonitoredUids.find(uid);
4648 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004649 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004650 } else {
Austin Borger65577682022-02-17 00:25:43 +00004651 MonitoredUid monitoredUid;
4652 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004653 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004654 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004655 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004656 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004657 if (res != OK) {
4658 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4659 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004660 }
4661
4662 if (openCamera) {
4663 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004664 }
4665}
4666
Austin Borgerdddb7552023-03-30 17:53:01 -07004667/**
4668 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4669 */
4670void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004671 Mutex::Autolock _l(mUidLock);
4672 auto it = mMonitoredUids.find(uid);
4673 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004674 it->second.refCount--;
4675 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004676 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004677 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004678 if (res != OK) {
4679 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4680 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004681 } else if (closeCamera) {
4682 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004683 }
4684 } else {
4685 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4686 }
4687}
4688
Austin Borgered99f642023-06-01 16:51:35 -07004689bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004690 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004691 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004692}
4693
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004694static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4695static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004696
Austin Borgered99f642023-06-01 16:51:35 -07004697bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004698 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004699 // If activity manager is unreachable, assume everything is active
4700 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004701 return true;
4702 }
4703 auto it = mOverrideUids.find(uid);
4704 if (it != mOverrideUids.end()) {
4705 return it->second;
4706 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004707 bool active = mActiveUids.find(uid) != mActiveUids.end();
4708 if (!active) {
4709 // We want active UIDs to always access camera with their first attempt since
4710 // there is no guarantee the app is robustly written and would retry getting
4711 // the camera on failure. The inverse case is not a problem as we would take
4712 // camera away soon once we get the callback that the uid is no longer active.
4713 ActivityManager am;
4714 // Okay to access with a lock held as UID changes are dispatched without
4715 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004716 int64_t startTimeMillis = 0;
4717 do {
4718 // TODO: Fix this b/109950150!
4719 // Okay this is a hack. There is a race between the UID turning active and
4720 // activity being resumed. The proper fix is very risky, so we temporary add
4721 // some polling which should happen pretty rarely anyway as the race is hard
4722 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004723 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004724 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004725 if (active) {
4726 break;
4727 }
4728 if (startTimeMillis <= 0) {
4729 startTimeMillis = uptimeMillis();
4730 }
4731 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004732 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004733 if (remainingTimeMillis <= 0) {
4734 break;
4735 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004736 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4737
4738 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004739 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004740 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004741 } while (true);
4742
Svet Ganov7b4ab782018-03-25 12:48:10 -07004743 if (active) {
4744 // Now that we found out the UID is actually active, cache that
4745 mActiveUids.insert(uid);
4746 }
4747 }
4748 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004749}
4750
Varun Shahb42f1eb2019-04-16 14:45:13 -07004751int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4752 Mutex::Autolock _l(mUidLock);
4753 return getProcStateLocked(uid);
4754}
4755
4756int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4757 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4758 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004759 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004760 }
4761 return procState;
4762}
4763
Austin Borgered99f642023-06-01 16:51:35 -07004764void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4765 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004766 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004767}
4768
Austin Borgered99f642023-06-01 16:51:35 -07004769void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004770 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004771}
4772
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004773void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4774 Mutex::Autolock _l(mUidLock);
4775 ALOGV("UidPolicy: ActivityManager has died");
4776 mRegistered = false;
4777 mActiveUids.clear();
4778}
4779
Austin Borgered99f642023-06-01 16:51:35 -07004780void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004781 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004782 bool wasActive = false;
4783 bool isActive = false;
4784 {
4785 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004786 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004787 mOverrideUids.erase(uid);
4788 if (insert) {
4789 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4790 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004791 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004792 }
4793 if (wasActive != isActive && !isActive) {
4794 sp<CameraService> service = mService.promote();
4795 if (service != nullptr) {
4796 service->blockClientsForUid(uid);
4797 }
4798 }
4799}
4800
4801// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004802// SensorPrivacyPolicy
4803// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004804
4805void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4806{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004807 Mutex::Autolock _l(mSensorPrivacyLock);
4808 if (mRegistered) {
4809 return;
4810 }
Evan Severson09ab4002021-02-10 14:15:19 -08004811 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004812 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004813 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004814 mSpm.addToggleSensorPrivacyListener(this);
4815 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004816 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004817 if (flags::camera_privacy_allowlist()) {
4818 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4819 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4820 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4821 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004822 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004823 if (res == OK) {
4824 mRegistered = true;
4825 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4826 }
4827}
4828
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004829void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4830 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004831 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004832 return;
4833 }
4834
4835 registerWithSensorPrivacyManager();
4836}
4837
4838void CameraService::SensorPrivacyPolicy::registerSelf() {
4839 // Use checkservice to see if the sensor_privacy service is available
4840 // If service is not available then register for notification
4841 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004842 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004843 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004844 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004845 } else {
4846 registerWithSensorPrivacyManager();
4847 }
4848}
4849
Michael Grooverd1d435a2018-12-18 17:39:42 -08004850void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4851 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004852 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004853 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004854 mSpm.removeToggleSensorPrivacyListener(this);
4855 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004856 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004857 mRegistered = false;
4858 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4859}
4860
4861bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004862 if (!mRegistered) {
4863 registerWithSensorPrivacyManager();
4864 }
4865
Michael Grooverd1d435a2018-12-18 17:39:42 -08004866 Mutex::Autolock _l(mSensorPrivacyLock);
4867 return mSensorPrivacyEnabled;
4868}
4869
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004870int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4871 if (!mRegistered) {
4872 registerWithSensorPrivacyManager();
4873 }
4874
4875 Mutex::Autolock _l(mSensorPrivacyLock);
4876 return mCameraPrivacyState;
4877}
4878
Evan Seversond0b69922022-01-27 10:47:34 -08004879bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004880 if (!hasCameraPrivacyFeature()) {
4881 return false;
4882 }
Evan Seversond0b69922022-01-27 10:47:34 -08004883 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004884}
4885
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004886bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4887 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004888 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004889 }
4890 return mSpm.isCameraPrivacyEnabled(packageName);
4891}
4892
Evan Seversond0b69922022-01-27 10:47:34 -08004893binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004894 int toggleType, int sensor, bool enabled) {
4895 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4896 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4897 {
4898 Mutex::Autolock _l(mSensorPrivacyLock);
4899 mSensorPrivacyEnabled = enabled;
4900 }
4901 // if sensor privacy is enabled then block all clients from accessing the camera
4902 if (enabled) {
4903 sp<CameraService> service = mService.promote();
4904 if (service != nullptr) {
4905 service->blockAllClients();
4906 }
4907 }
4908 }
4909 return binder::Status::ok();
4910}
4911
4912binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4913 int, int sensor, int state) {
4914 if (!flags::camera_privacy_allowlist()
4915 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4916 return binder::Status::ok();
4917 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004918 {
4919 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004920 mCameraPrivacyState = state;
4921 }
4922 sp<CameraService> service = mService.promote();
4923 if (!service) {
4924 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004925 }
4926 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004927 if (state == SensorPrivacyManager::ENABLED) {
4928 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004929 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004930 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004931 }
4932 return binder::Status::ok();
4933}
4934
4935void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4936 Mutex::Autolock _l(mSensorPrivacyLock);
4937 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4938 mRegistered = false;
4939}
4940
Evan Severson09ab4002021-02-10 14:15:19 -08004941bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004942 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4943 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4944 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4945 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4946 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004947}
4948
Michael Grooverd1d435a2018-12-18 17:39:42 -08004949// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004950// CameraState
4951// ----------------------------------------------------------------------------
4952
Austin Borgered99f642023-06-01 16:51:35 -07004953CameraService::CameraState::CameraState(const std::string& id, int cost,
4954 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004955 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004956 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004957 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08004958
4959CameraService::CameraState::~CameraState() {}
4960
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004961CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004962 Mutex::Autolock lock(mStatusLock);
4963 return mStatus;
4964}
4965
Austin Borgered99f642023-06-01 16:51:35 -07004966std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08004967 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07004968 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08004969 return res;
4970}
4971
Ruben Brunkcc776712015-02-17 20:18:47 -08004972CameraParameters CameraService::CameraState::getShimParams() const {
4973 return mShimParams;
4974}
4975
4976void CameraService::CameraState::setShimParams(const CameraParameters& params) {
4977 mShimParams = params;
4978}
4979
4980int CameraService::CameraState::getCost() const {
4981 return mCost;
4982}
4983
Austin Borgered99f642023-06-01 16:51:35 -07004984std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08004985 return mConflicting;
4986}
4987
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004988SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
4989 return mSystemCameraKind;
4990}
4991
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004992bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
4993 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
4994 != mPhysicalCameras.end();
4995}
4996
Austin Borgered99f642023-06-01 16:51:35 -07004997bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08004998 Mutex::Autolock lock(mStatusLock);
4999 auto result = mUnavailablePhysicalIds.insert(physicalId);
5000 return result.second;
5001}
5002
Austin Borgered99f642023-06-01 16:51:35 -07005003bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005004 Mutex::Autolock lock(mStatusLock);
5005 auto count = mUnavailablePhysicalIds.erase(physicalId);
5006 return count > 0;
5007}
5008
Austin Borgered99f642023-06-01 16:51:35 -07005009void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005010 Mutex::Autolock lock(mStatusLock);
5011 mClientPackage = clientPackage;
5012}
5013
Austin Borgered99f642023-06-01 16:51:35 -07005014std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005015 Mutex::Autolock lock(mStatusLock);
5016 return mClientPackage;
5017}
5018
Ruben Brunkcc776712015-02-17 20:18:47 -08005019// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005020// ClientEventListener
5021// ----------------------------------------------------------------------------
5022
5023void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005024 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005025 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005026 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005027 if (basicClient.get() != nullptr) {
5028 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005029 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005030 static_cast<int>(basicClient->getClientUid()));
5031 }
5032}
5033
5034void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005035 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005036 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005037 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005038 if (basicClient.get() != nullptr) {
5039 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005040 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005041 static_cast<int>(basicClient->getClientUid()));
5042 }
5043}
5044
Ruben Brunk99e69712015-05-26 17:25:07 -07005045// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005046// CameraClientManager
5047// ----------------------------------------------------------------------------
5048
Ruben Brunk99e69712015-05-26 17:25:07 -07005049CameraService::CameraClientManager::CameraClientManager() {
5050 setListener(std::make_shared<ClientEventListener>());
5051}
5052
Ruben Brunkcc776712015-02-17 20:18:47 -08005053CameraService::CameraClientManager::~CameraClientManager() {}
5054
5055sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005056 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005057 auto descriptor = get(id);
5058 if (descriptor == nullptr) {
5059 return sp<BasicClient>{nullptr};
5060 }
5061 return descriptor->getValue();
5062}
5063
Austin Borgered99f642023-06-01 16:51:35 -07005064std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005065 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005066 std::ostringstream ret;
5067 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005068 bool hasAny = false;
5069 for (auto& i : all) {
5070 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005071 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005072 int32_t cost = i->getCost();
5073 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005074 int32_t score = i->getPriority().getScore();
5075 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005076 auto conflicting = i->getConflicting();
5077 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005078 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005079 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005080 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005081 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005082 uid_t clientUid = clientSp->getClientUid();
5083 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005084 }
Austin Borgered99f642023-06-01 16:51:35 -07005085 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5086 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005087
Ruben Brunk6267b532015-04-30 17:44:07 -07005088 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005089 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005090 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005091 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005092 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005093 }
5094
Austin Borgered99f642023-06-01 16:51:35 -07005095 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005096 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005097 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005098 }
Austin Borgered99f642023-06-01 16:51:35 -07005099 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005100 }
Austin Borgered99f642023-06-01 16:51:35 -07005101 if (hasAny) ret << "\n";
5102 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005103 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005104}
5105
5106CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005107 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5108 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005109 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005110
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005111 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005112 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005113
Austin Borgered99f642023-06-01 16:51:35 -07005114 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005115 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5116 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005117}
5118
5119CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005120 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005121 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005122 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005123 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005124 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5125 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005126}
5127
5128// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005129// InjectionStatusListener
5130// ----------------------------------------------------------------------------
5131
5132void CameraService::InjectionStatusListener::addListener(
5133 const sp<ICameraInjectionCallback>& callback) {
5134 Mutex::Autolock lock(mListenerLock);
5135 if (mCameraInjectionCallback) return;
5136 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5137 if (res == OK) {
5138 mCameraInjectionCallback = callback;
5139 }
5140}
5141
5142void CameraService::InjectionStatusListener::removeListener() {
5143 Mutex::Autolock lock(mListenerLock);
5144 if (mCameraInjectionCallback == nullptr) {
5145 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5146 return;
5147 }
5148 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5149 mCameraInjectionCallback = nullptr;
5150}
5151
5152void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005153 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005154 if (mCameraInjectionCallback == nullptr) {
5155 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5156 return;
5157 }
Cliff Wud3a05312021-04-26 23:07:31 +08005158
5159 switch (err) {
5160 case -ENODEV:
5161 mCameraInjectionCallback->onInjectionError(
5162 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5163 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005164 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005165 break;
5166 case -EBUSY:
5167 mCameraInjectionCallback->onInjectionError(
5168 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5169 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005170 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005171 break;
5172 case DEAD_OBJECT:
5173 mCameraInjectionCallback->onInjectionError(
5174 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5175 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005176 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005177 break;
5178 case INVALID_OPERATION:
5179 mCameraInjectionCallback->onInjectionError(
5180 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5181 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005182 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005183 break;
5184 case UNKNOWN_TRANSACTION:
5185 mCameraInjectionCallback->onInjectionError(
5186 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5187 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005188 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005189 break;
5190 default:
5191 mCameraInjectionCallback->onInjectionError(
5192 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5193 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005194 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005195 }
Cliff Wud8cae102021-03-11 01:37:42 +08005196}
5197
5198void CameraService::InjectionStatusListener::binderDied(
5199 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005200 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5201 auto parent = mParent.promote();
5202 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005203 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5204 if (clientDescriptor != nullptr) {
5205 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5206 baseClientPtr->stopInjection();
5207 }
Cliff Wu3b268182021-07-06 15:44:43 +08005208 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005209 }
5210}
5211
5212// ----------------------------------------------------------------------------
5213// CameraInjectionSession
5214// ----------------------------------------------------------------------------
5215
5216binder::Status CameraService::CameraInjectionSession::stopInjection() {
5217 Mutex::Autolock lock(mInjectionSessionLock);
5218 auto parent = mParent.promote();
5219 if (parent == nullptr) {
5220 ALOGE("CameraInjectionSession: Parent is gone");
5221 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5222 "Camera service encountered error");
5223 }
Cliff Wud3a05312021-04-26 23:07:31 +08005224
5225 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005226 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5227 if (clientDescriptor != nullptr) {
5228 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5229 res = baseClientPtr->stopInjection();
5230 if (res != OK) {
5231 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5232 " ret != NO_ERROR: %d", res);
5233 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5234 "Camera session encountered error");
5235 }
5236 }
Cliff Wu3b268182021-07-06 15:44:43 +08005237 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005238 return binder::Status::ok();
5239}
5240
5241// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005242
5243static const int kDumpLockRetries = 50;
5244static const int kDumpLockSleep = 60000;
5245
5246static bool tryLock(Mutex& mutex)
5247{
5248 bool locked = false;
5249 for (int i = 0; i < kDumpLockRetries; ++i) {
5250 if (mutex.tryLock() == NO_ERROR) {
5251 locked = true;
5252 break;
5253 }
5254 usleep(kDumpLockSleep);
5255 }
5256 return locked;
5257}
5258
Rucha Katakwardf223072021-06-15 10:21:00 -07005259void CameraService::cacheDump() {
5260 if (mMemFd != -1) {
5261 const Vector<String16> args;
5262 ATRACE_CALL();
5263 // Acquiring service lock here will avoid the deadlock since
5264 // cacheDump will not be called during the second disconnect.
5265 Mutex::Autolock lock(mServiceLock);
5266
5267 Mutex::Autolock l(mCameraStatesLock);
5268 // Start collecting the info for open sessions and store it in temp file.
5269 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005270 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005271 auto clientDescriptor = mActiveClientManager.get(cameraId);
5272 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005273 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005274 // Log the current open session info before device is disconnected.
5275 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5276 }
5277 }
5278 }
5279}
5280
Mathias Agopian65ab4712010-07-14 17:59:35 -07005281status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005282 ATRACE_CALL();
5283
Austin Borgered99f642023-06-01 16:51:35 -07005284 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005285 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005286 getCallingPid(),
5287 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005288 return NO_ERROR;
5289 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005290 bool locked = tryLock(mServiceLock);
5291 // failed to lock - CameraService is probably deadlocked
5292 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005293 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005294 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005295
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005296 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005297 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005298
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005299 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005300 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005301
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005302 if (locked) mServiceLock.unlock();
5303 return NO_ERROR;
5304 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005305 dprintf(fd, "\n== Service global info: ==\n\n");
5306 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005307 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005308 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5309 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005310 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5311 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5312 }
Austin Borgered99f642023-06-01 16:51:35 -07005313 std::string activeClientString = mActiveClientManager.toString();
5314 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5315 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005316 if (mStreamUseCaseOverrides.size() > 0) {
5317 dprintf(fd, "Active stream use case overrides:");
5318 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5319 dprintf(fd, " %" PRId64, useCaseOverride);
5320 }
5321 dprintf(fd, "\n");
5322 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005323
5324 dumpEventLog(fd);
5325
5326 bool stateLocked = tryLock(mCameraStatesLock);
5327 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005328 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005329 }
5330
Emilian Peevbd8c5032018-02-14 23:05:40 +00005331 int argSize = args.size();
5332 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005333 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005334 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005335 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005336 }
5337 break;
5338 }
5339 }
5340
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005341 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005342 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005343
Austin Borgered99f642023-06-01 16:51:35 -07005344 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005345
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005346 CameraParameters p = state.second->getShimParams();
5347 if (!p.isEmpty()) {
5348 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5349 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005350 }
5351
5352 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005353 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005354 // log the current open session info
5355 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005356 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005357 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005358 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005359
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005360 }
5361
5362 if (stateLocked) mCameraStatesLock.unlock();
5363
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005364 if (locked) mServiceLock.unlock();
5365
Emilian Peevf53f66e2017-04-11 14:29:43 +01005366 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005367
5368 dprintf(fd, "\n== Vendor tags: ==\n\n");
5369
5370 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5371 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005372 sp<VendorTagDescriptorCache> cache =
5373 VendorTagDescriptorCache::getGlobalVendorTagCache();
5374 if (cache == NULL) {
5375 dprintf(fd, "No vendor tags.\n");
5376 } else {
5377 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5378 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005379 } else {
5380 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5381 }
5382
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005383 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005384 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005385 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005386
5387 // Process dump arguments, if any
5388 int n = args.size();
5389 String16 verboseOption("-v");
5390 String16 unreachableOption("--unreachable");
5391 for (int i = 0; i < n; i++) {
5392 if (args[i] == verboseOption) {
5393 // change logging level
5394 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005395 std::string levelStr = toStdString(args[i+1]);
5396 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005397 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005398 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005399 } else if (args[i] == unreachableOption) {
5400 // Dump memory analysis
5401 // TODO - should limit be an argument parameter?
5402 UnreachableMemoryInfo info;
5403 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5404 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005405 dprintf(fd, "\n== Unable to dump unreachable memory. "
5406 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005407 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005408 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005409 std::string s = info.ToString(/*log_contents*/ true);
5410 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005411 }
5412 }
5413 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005414
5415 bool serviceLocked = tryLock(mServiceLock);
5416
5417 // Dump info from previous open sessions.
5418 // Reposition the offset to beginning of the file before reading
5419
5420 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5421 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5422 ssize_t size_read;
5423 char buf[4096];
5424 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5425 // Read data from file to a small buffer and write it to fd.
5426 write(fd, buf, size_read);
5427 if (size_read == -1) {
5428 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5429 break;
5430 }
5431 }
5432 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5433 } else {
5434 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5435 }
5436
5437 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005438 return NO_ERROR;
5439}
5440
Rucha Katakwardf223072021-06-15 10:21:00 -07005441void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005442 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005443 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005444 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005445 getFormattedCurrentTime().c_str(),
5446 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005447 dprintf(fd, " Client priority score: %d state: %d\n",
5448 clientDescriptor->getPriority().getScore(),
5449 clientDescriptor->getPriority().getState());
5450 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5451
5452 auto client = clientDescriptor->getValue();
5453 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005454 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005455
5456 client->dumpClient(fd, args);
5457}
5458
Austin Borgered99f642023-06-01 16:51:35 -07005459void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005460 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005461 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005462}
5463
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005464void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005465 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005466
5467 Mutex::Autolock l(mLogLock);
5468 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005469 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005470 }
5471
5472 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005473 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005474 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005475 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005476 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005477 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005478}
5479
Austin Borgered99f642023-06-01 16:51:35 -07005480void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005481 Mutex::Autolock lock(mLogLock);
5482 if (!isClientWatchedLocked(client)) { return; }
5483
5484 std::vector<std::string> dumpVector;
5485 client->dumpWatchedEventsToVector(dumpVector);
5486
5487 if (dumpVector.empty()) { return; }
5488
Austin Borgered99f642023-06-01 16:51:35 -07005489 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005490
Austin Borgered99f642023-06-01 16:51:35 -07005491 std::string currentTime = getFormattedCurrentTime();
5492 dumpString << "Cached @ ";
5493 dumpString << currentTime;
5494 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005495
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005496 size_t i = dumpVector.size();
5497
5498 // Store the string in reverse order (latest last)
5499 while (i > 0) {
5500 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005501 dumpString << cameraId;
5502 dumpString << ":";
5503 dumpString << client->getPackageName();
5504 dumpString << " ";
5505 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005506 }
5507
Austin Borgered99f642023-06-01 16:51:35 -07005508 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005509}
5510
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005511void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005512 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005513 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5514 if (mTorchClientMap[i] == who) {
5515 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005516 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005517 status_t res = mFlashlight->setTorchMode(cameraId, false);
5518 if (res) {
5519 ALOGE("%s: torch client died but couldn't turn off torch: "
5520 "%s (%d)", __FUNCTION__, strerror(-res), res);
5521 return;
5522 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005523 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005524 break;
5525 }
5526 }
5527}
5528
Ruben Brunkcc776712015-02-17 20:18:47 -08005529/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005530
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005531 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005532 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5533 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005534 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005535 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005536 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005537
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005538 // check torch client
5539 handleTorchClientBinderDied(who);
5540
5541 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005542 if(!evictClientIdByRemote(who)) {
5543 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005544 return;
5545 }
5546
Ruben Brunkcc776712015-02-17 20:18:47 -08005547 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5548 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005549}
5550
Austin Borgered99f642023-06-01 16:51:35 -07005551void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005552 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005553}
5554
Austin Borgered99f642023-06-01 16:51:35 -07005555void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005556 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005557 // Do not lock mServiceLock here or can get into a deadlock from
5558 // connect() -> disconnect -> updateStatus
5559
5560 auto state = getCameraState(cameraId);
5561
5562 if (state == nullptr) {
5563 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005564 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005565 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005566 }
5567
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005568 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5569 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5570 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005571 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005572 return;
5573 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005574
Biswarup Pal37a75182024-01-16 15:53:35 +00005575 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5576 CameraMetadata cameraInfo;
5577 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005578 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005579 if (res != OK) {
5580 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5581 __FUNCTION__, cameraId.c_str());
5582 } else {
5583 int32_t deviceId = getDeviceId(cameraInfo);
5584 if (deviceId != kDefaultDeviceId) {
5585 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5586 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5587 static_cast<camera_metadata_enum_android_lens_facing_t>(
5588 lensFacingEntry.data.u8[0]);
5589 std::string mappedCameraId;
5590 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5591 mappedCameraId = kVirtualDeviceBackCameraId;
5592 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5593 mappedCameraId = kVirtualDeviceFrontCameraId;
5594 } else {
5595 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5596 __func__);
5597 }
5598 if (!mappedCameraId.empty()) {
5599 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5600 }
5601 }
5602 }
5603 }
5604
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005605 // Collect the logical cameras without holding mStatusLock in updateStatus
5606 // as that can lead to a deadlock(b/162192331).
5607 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005608 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005609 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005610 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005611 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005612 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005613 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5614 auto [deviceId, mappedCameraId] =
5615 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005616
Biswarup Pal37a75182024-01-16 15:53:35 +00005617 if (status != StatusInternal::ENUMERATING) {
5618 // Update torch status if it has a flash unit.
5619 Mutex::Autolock al(mTorchStatusMutex);
5620 TorchModeStatus torchStatus;
5621 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5622 NAME_NOT_FOUND) {
5623 TorchModeStatus newTorchStatus =
5624 status == StatusInternal::PRESENT ?
5625 TorchModeStatus::AVAILABLE_OFF :
5626 TorchModeStatus::NOT_AVAILABLE;
5627 if (torchStatus != newTorchStatus) {
5628 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5629 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005630 }
5631 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005632
Biswarup Pal37a75182024-01-16 15:53:35 +00005633 Mutex::Autolock lock(mStatusListenerLock);
5634 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5635 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005636
Biswarup Pal37a75182024-01-16 15:53:35 +00005637 for (auto& listener : mListenerList) {
5638 bool isVendorListener = listener->isVendorListener();
5639 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5640 listener->getListenerPid(), listener->getListenerUid())) {
5641 ALOGV("Skipping discovery callback for system-only camera device %s",
5642 cameraId.c_str());
5643 continue;
5644 }
5645
5646 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5647 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005648 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005649 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005650 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5651 ret.exceptionCode());
5652 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005653 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005654}
5655
Austin Borgered99f642023-06-01 16:51:35 -07005656void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5657 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005658 auto state = getCameraState(cameraId);
5659 if (state == nullptr) {
5660 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005661 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005662 return;
5663 }
5664 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005665 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005666 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005667 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005668 }
5669
Biswarup Pal37a75182024-01-16 15:53:35 +00005670 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5671 auto [deviceId, mappedCameraId] =
5672 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5673
Shuzhen Wang695044d2020-03-06 09:02:23 -08005674 Mutex::Autolock lock(mStatusListenerLock);
5675
5676 for (const auto& it : mListenerList) {
5677 if (!it->isOpenCloseCallbackAllowed()) {
5678 continue;
5679 }
5680
5681 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005682 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005683 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5684 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005685 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005686 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005687 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005688
5689 it->handleBinderStatus(ret,
5690 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5691 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005692 }
5693}
5694
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005695template<class Func>
5696void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005697 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005698 std::initializer_list<StatusInternal> rejectSourceStates,
5699 Func onStatusUpdatedLocked) {
5700 Mutex::Autolock lock(mStatusLock);
5701 StatusInternal oldStatus = mStatus;
5702 mStatus = status;
5703
5704 if (oldStatus == status) {
5705 return;
5706 }
5707
5708 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005709 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005710
5711 if (oldStatus == StatusInternal::NOT_PRESENT &&
5712 (status != StatusInternal::PRESENT &&
5713 status != StatusInternal::ENUMERATING)) {
5714
5715 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5716 __FUNCTION__);
5717 mStatus = oldStatus;
5718 return;
5719 }
5720
5721 /**
5722 * Sometimes we want to conditionally do a transition.
5723 * For example if a client disconnects, we want to go to PRESENT
5724 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5725 */
5726 for (auto& rejectStatus : rejectSourceStates) {
5727 if (oldStatus == rejectStatus) {
5728 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005729 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005730 mStatus = oldStatus;
5731 return;
5732 }
5733 }
5734
5735 onStatusUpdatedLocked(cameraId, status);
5736}
5737
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005738status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005739 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005740 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005741 if (!status) {
5742 return BAD_VALUE;
5743 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005744 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5745 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005746 // invalid camera ID or the camera doesn't have a flash unit
5747 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005748 }
5749
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005750 *status = mTorchStatusMap.valueAt(index);
5751 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005752}
5753
Austin Borgered99f642023-06-01 16:51:35 -07005754status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005755 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005756 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5757 if (index == NAME_NOT_FOUND) {
5758 return BAD_VALUE;
5759 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005760 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005761
5762 return OK;
5763}
5764
Austin Borgered99f642023-06-01 16:51:35 -07005765std::list<std::string> CameraService::getLogicalCameras(
5766 const std::string& physicalCameraId) {
5767 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005768 Mutex::Autolock lock(mCameraStatesLock);
5769 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005770 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5771 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005772 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005773 }
5774 return retList;
5775}
5776
5777void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005778 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005779 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005780 // mStatusListenerLock is expected to be locked
5781 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005782 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005783 // Note: we check only the deviceKind of the physical camera id
5784 // since, logical camera ids and their physical camera ids are
5785 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005786 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5787 listener->getListenerPid(), listener->getListenerUid())) {
5788 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005789 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005790 continue;
5791 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005792 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005793 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005794 listener->handleBinderStatus(ret,
5795 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5796 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5797 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005798 }
5799 }
5800}
5801
Svet Ganova453d0d2018-01-11 15:37:58 -08005802void CameraService::blockClientsForUid(uid_t uid) {
5803 const auto clients = mActiveClientManager.getAll();
5804 for (auto& current : clients) {
5805 if (current != nullptr) {
5806 const auto basicClient = current->getValue();
5807 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5808 basicClient->block();
5809 }
5810 }
5811 }
5812}
5813
Michael Grooverd1d435a2018-12-18 17:39:42 -08005814void CameraService::blockAllClients() {
5815 const auto clients = mActiveClientManager.getAll();
5816 for (auto& current : clients) {
5817 if (current != nullptr) {
5818 const auto basicClient = current->getValue();
5819 if (basicClient.get() != nullptr) {
5820 basicClient->block();
5821 }
5822 }
5823 }
5824}
5825
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005826void CameraService::blockPrivacyEnabledClients() {
5827 const auto clients = mActiveClientManager.getAll();
5828 for (auto& current : clients) {
5829 if (current != nullptr) {
5830 const auto basicClient = current->getValue();
5831 if (basicClient.get() != nullptr) {
5832 std::string pkgName = basicClient->getPackageName();
5833 bool cameraPrivacyEnabled =
5834 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5835 if (cameraPrivacyEnabled) {
5836 basicClient->block();
5837 }
5838 }
5839 }
5840 }
5841}
5842
Svet Ganova453d0d2018-01-11 15:37:58 -08005843// NOTE: This is a remote API - make sure all args are validated
5844status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005845 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005846 return PERMISSION_DENIED;
5847 }
5848 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5849 return BAD_VALUE;
5850 }
Austin Borgered99f642023-06-01 16:51:35 -07005851 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005852 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005853 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005854 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005855 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005856 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005857 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005858 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005859 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005860 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005861 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005862 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005863 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005864 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005865 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005866 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005867 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005868 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005869 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005870 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005871 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005872 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005873 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005874 handleClearStreamUseCaseOverrides();
5875 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005876 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005877 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005878 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005879 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005880 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005881 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005882 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005883 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005884 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005885 }
5886 printHelp(err);
5887 return BAD_VALUE;
5888}
5889
5890status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005891 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005892
Svet Ganova453d0d2018-01-11 15:37:58 -08005893 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005894 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005895 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005896 } else if ((args[2] != toString16("idle"))) {
5897 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005898 return BAD_VALUE;
5899 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005900
5901 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005902 if (args.size() >= 5 && args[3] == toString16("--user")) {
5903 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005904 }
5905
5906 uid_t uid;
5907 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5908 return BAD_VALUE;
5909 }
5910
5911 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005912 return NO_ERROR;
5913}
5914
5915status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005916 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005917
5918 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005919 if (args.size() >= 4 && args[2] == toString16("--user")) {
5920 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005921 }
5922
5923 uid_t uid;
5924 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005925 return BAD_VALUE;
5926 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005927
5928 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005929 return NO_ERROR;
5930}
5931
5932status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005933 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005934
5935 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005936 if (args.size() >= 4 && args[2] == toString16("--user")) {
5937 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005938 }
5939
5940 uid_t uid;
5941 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005942 return BAD_VALUE;
5943 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005944
5945 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005946 return dprintf(out, "active\n");
5947 } else {
5948 return dprintf(out, "idle\n");
5949 }
5950}
5951
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005952status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005953 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005954 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5955 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5956 Mutex::Autolock lock(mServiceLock);
5957
5958 mOverrideRotateAndCropMode = rotateValue;
5959
5960 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
5961
5962 const auto clients = mActiveClientManager.getAll();
5963 for (auto& current : clients) {
5964 if (current != nullptr) {
5965 const auto basicClient = current->getValue();
5966 if (basicClient.get() != nullptr) {
5967 basicClient->setRotateAndCropOverride(rotateValue);
5968 }
5969 }
5970 }
5971
5972 return OK;
5973}
5974
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005975status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
5976 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07005977 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005978 if ((*end != '\0') ||
5979 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
5980 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
5981 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
5982 return BAD_VALUE;
5983 }
5984
5985 Mutex::Autolock lock(mServiceLock);
5986 mOverrideAutoframingMode = autoframingValue;
5987
5988 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
5989
5990 const auto clients = mActiveClientManager.getAll();
5991 for (auto& current : clients) {
5992 if (current != nullptr) {
5993 const auto basicClient = current->getValue();
5994 if (basicClient.get() != nullptr) {
5995 basicClient->setAutoframingOverride(autoframingValue);
5996 }
5997 }
5998 }
5999
6000 return OK;
6001}
6002
Ravneetaeb20dc2022-03-30 05:33:03 +00006003status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006004 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006005
6006 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6007
6008 Mutex::Autolock lock(mServiceLock);
6009
6010 mCameraServiceWatchdogEnabled = enableWatchdog;
6011
6012 const auto clients = mActiveClientManager.getAll();
6013 for (auto& current : clients) {
6014 if (current != nullptr) {
6015 const auto basicClient = current->getValue();
6016 if (basicClient.get() != nullptr) {
6017 basicClient->setCameraServiceWatchdog(enableWatchdog);
6018 }
6019 }
6020 }
6021
6022 return OK;
6023}
6024
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006025status_t CameraService::handleGetRotateAndCrop(int out) {
6026 Mutex::Autolock lock(mServiceLock);
6027
6028 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6029}
6030
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006031status_t CameraService::handleGetAutoframing(int out) {
6032 Mutex::Autolock lock(mServiceLock);
6033
6034 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6035}
6036
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006037status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6038 char *endPtr;
6039 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006040 std::string maskString = toStdString(args[1]);
6041 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006042
6043 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006044 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006045 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6046
6047 Mutex::Autolock lock(mServiceLock);
6048
6049 mImageDumpMask = maskValue;
6050
6051 return OK;
6052}
6053
6054status_t CameraService::handleGetImageDumpMask(int out) {
6055 Mutex::Autolock lock(mServiceLock);
6056
6057 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6058}
6059
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006060status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006061 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006062 if (errno != 0) return BAD_VALUE;
6063
6064 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6065 Mutex::Autolock lock(mServiceLock);
6066
6067 mOverrideCameraMuteMode = (muteValue == 1);
6068
6069 const auto clients = mActiveClientManager.getAll();
6070 for (auto& current : clients) {
6071 if (current != nullptr) {
6072 const auto basicClient = current->getValue();
6073 if (basicClient.get() != nullptr) {
6074 if (basicClient->supportsCameraMute()) {
6075 basicClient->setCameraMute(mOverrideCameraMuteMode);
6076 }
6077 }
6078 }
6079 }
6080
6081 return OK;
6082}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006083
Shuzhen Wang16610a62022-12-15 22:38:07 -08006084status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6085 std::vector<int64_t> useCasesOverride;
6086 for (size_t i = 1; i < args.size(); i++) {
6087 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006088 std::string arg = toStdString(args[i]);
6089 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006090 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006091 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006092 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006093 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006094 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006095 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006096 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006097 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006098 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006099 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006100 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006101 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006102 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6103 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006104 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006105 return BAD_VALUE;
6106 }
6107 useCasesOverride.push_back(useCase);
6108 }
6109
6110 Mutex::Autolock lock(mServiceLock);
6111 mStreamUseCaseOverrides = std::move(useCasesOverride);
6112
6113 return OK;
6114}
6115
6116void CameraService::handleClearStreamUseCaseOverrides() {
6117 Mutex::Autolock lock(mServiceLock);
6118 mStreamUseCaseOverrides.clear();
6119}
6120
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006121status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6122 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006123 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006124 if ((*end != '\0') ||
6125 (zoomOverrideValue != -1 &&
6126 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6127 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6128 return BAD_VALUE;
6129 }
6130
6131 Mutex::Autolock lock(mServiceLock);
6132 mZoomOverrideValue = zoomOverrideValue;
6133
6134 const auto clients = mActiveClientManager.getAll();
6135 for (auto& current : clients) {
6136 if (current != nullptr) {
6137 const auto basicClient = current->getValue();
6138 if (basicClient.get() != nullptr) {
6139 if (basicClient->supportsZoomOverride()) {
6140 basicClient->setZoomOverride(mZoomOverrideValue);
6141 }
6142 }
6143 }
6144 }
6145
6146 return OK;
6147}
6148
Avichal Rakesh84147132021-11-11 17:47:11 -08006149status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006150 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006151 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006152 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006153 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006154 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006155 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006156 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006157 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006158 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006159 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006160 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006161 dprintf(outFd, "Camera service watch commands:\n"
6162 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6163 " starts watching the provided tags for clients with provided package\n"
6164 " recognizes tag shorthands like '3a'\n"
6165 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006166 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006167 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006168 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006169 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006170 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006171 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006172 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006173}
6174
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006175status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6176 Mutex::Autolock lock(mLogLock);
6177 size_t tagsIdx; // index of '-m'
6178 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006179 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006180 if (tagsIdx < args.size() - 1) {
6181 tags = args[tagsIdx + 1];
6182 } else {
6183 dprintf(outFd, "No tags provided.\n");
6184 return BAD_VALUE;
6185 }
6186
6187 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006188 // watch all clients if no clients are provided
6189 String16 clients = toString16(kWatchAllClientsFlag);
6190 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006191 clientsIdx++);
6192 if (clientsIdx < args.size() - 1) {
6193 clients = args[clientsIdx + 1];
6194 }
Austin Borgered99f642023-06-01 16:51:35 -07006195 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006196
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006197 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006198 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006199
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006200 bool serviceLock = tryLock(mServiceLock);
6201 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006202 auto cameraClients = mActiveClientManager.getAll();
6203 for (const auto &clientDescriptor: cameraClients) {
6204 if (clientDescriptor == nullptr) { continue; }
6205 sp<BasicClient> client = clientDescriptor->getValue();
6206 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006207
6208 if (isClientWatchedLocked(client.get())) {
6209 client->startWatchingTags(mMonitorTags, outFd);
6210 numWatchedClients++;
6211 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006212 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006213 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6214
6215 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006216 return OK;
6217}
6218
6219status_t CameraService::stopWatchingTags(int outFd) {
6220 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006221 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006222 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006223
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006224 mWatchedClientPackages.clear();
6225 mWatchedClientsDumpCache.clear();
6226
6227 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006228 auto cameraClients = mActiveClientManager.getAll();
6229 for (const auto &clientDescriptor : cameraClients) {
6230 if (clientDescriptor == nullptr) { continue; }
6231 sp<BasicClient> client = clientDescriptor->getValue();
6232 if (client.get() == nullptr) { continue; }
6233 client->stopWatchingTags(outFd);
6234 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006235 dprintf(outFd, "Stopped watching all clients.\n");
6236 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006237 return OK;
6238}
6239
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006240status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6241 Mutex::Autolock lock(mLogLock);
6242 size_t clearedSize = mWatchedClientsDumpCache.size();
6243 mWatchedClientsDumpCache.clear();
6244 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6245 return OK;
6246}
6247
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006248status_t CameraService::printWatchedTags(int outFd) {
6249 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006250 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006251
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006252 bool printedSomething = false; // tracks if any monitoring information was printed
6253 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006254
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006255 bool serviceLock = tryLock(mServiceLock);
6256 // get all watched clients that are currently connected
6257 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6258 if (clientDescriptor == nullptr) { continue; }
6259
6260 sp<BasicClient> client = clientDescriptor->getValue();
6261 if (client.get() == nullptr) { continue; }
6262 if (!isClientWatchedLocked(client.get())) { continue; }
6263
6264 std::vector<std::string> dumpVector;
6265 client->dumpWatchedEventsToVector(dumpVector);
6266
6267 size_t printIdx = dumpVector.size();
6268 if (printIdx == 0) {
6269 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006270 }
6271
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006272 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006273 const std::string &cameraId = clientDescriptor->getKey();
6274 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006275 while(printIdx > 0) {
6276 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006277 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006278 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006279 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006280 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006281 printedSomething = true;
6282
6283 connectedMonitoredClients.emplace(client->getPackageName());
6284 }
6285 if (serviceLock) { mServiceLock.unlock(); }
6286
6287 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6288 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006289 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006290 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6291 continue;
6292 }
6293
Austin Borgered99f642023-06-01 16:51:35 -07006294 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006295 dprintf(outFd, "%s\n", kv.second.c_str());
6296 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006297 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006298
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006299 if (!printedSomething) {
6300 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006301 }
6302
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006303 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006304}
6305
Avichal Rakesh84147132021-11-11 17:47:11 -08006306// Print all events in vector `events' that came after lastPrintedEvent
6307void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006308 const std::string &cameraId,
6309 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006310 const std::vector<std::string> &events,
6311 const std::string &lastPrintedEvent) {
6312 if (events.empty()) { return; }
6313
6314 // index of lastPrintedEvent in events.
6315 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6316 size_t lastPrintedIdx;
6317 for (lastPrintedIdx = 0;
6318 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6319 lastPrintedIdx++);
6320
6321 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6322
Avichal Rakesh84147132021-11-11 17:47:11 -08006323 // print events in chronological order (latest event last)
6324 size_t idxToPrint = lastPrintedIdx;
6325 do {
6326 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006327 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6328 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006329 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006330}
6331
6332// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6333// command should be interrupted if the user presses the return key, or if user loses any way to
6334// signal interrupt.
6335// If timeoutMs == 0, this function will always return false
6336bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6337 struct timeval startTime;
6338 int startTimeError = gettimeofday(&startTime, nullptr);
6339 if (startTimeError) {
6340 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6341 return true;
6342 }
6343
6344 const nfds_t numFds = 1;
6345 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6346
6347 struct timeval currTime;
6348 char buffer[2];
6349 while(true) {
6350 int currTimeError = gettimeofday(&currTime, nullptr);
6351 if (currTimeError) {
6352 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6353 return true;
6354 }
6355
6356 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6357 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6358 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6359
6360 if (remainingTimeMs <= 0) {
6361 // No user interrupt within timeoutMs, don't interrupt watch command
6362 return false;
6363 }
6364
6365 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6366 if (numFdsUpdated < 0) {
6367 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6368 return true;
6369 }
6370
6371 if (numFdsUpdated == 0) {
6372 // No user input within timeoutMs, don't interrupt watch command
6373 return false;
6374 }
6375
6376 if (!(pollFd.revents & POLLIN)) {
6377 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6378 return true;
6379 }
6380
6381 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6382 if (sizeRead < 0) {
6383 dprintf(outFd, "Error reading user input. Exiting.\n");
6384 return true;
6385 }
6386
6387 if (sizeRead == 0) {
6388 // Reached end of input fd (can happen if input is piped)
6389 // User has no way to signal an interrupt, so interrupt here
6390 return true;
6391 }
6392
6393 if (buffer[0] == '\n') {
6394 // User pressed return, interrupt watch command.
6395 return true;
6396 }
6397 }
6398}
6399
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006400status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6401 int inFd, int outFd) {
6402 // Figure out refresh interval, if present in args
6403 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006404 if (args.size() > 2) {
6405 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006406 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006407 intervalIdx++);
6408
6409 size_t intervalValIdx = intervalIdx + 1;
6410 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006411 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006412 if (errno) { return BAD_VALUE; }
6413 }
6414 }
6415
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006416 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6417 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006418
Avichal Rakesh84147132021-11-11 17:47:11 -08006419 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006420 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006421
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006422 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006423 bool serviceLock = tryLock(mServiceLock);
6424 auto cameraClients = mActiveClientManager.getAll();
6425 if (serviceLock) { mServiceLock.unlock(); }
6426
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006427 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006428 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006429 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006430
6431 sp<BasicClient> client = clientDescriptor->getValue();
6432 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006433 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006434
Austin Borgered99f642023-06-01 16:51:35 -07006435 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006436 // This also initializes the map entries with an empty string
6437 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6438
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006439 std::vector<std::string> latestEvents;
6440 client->dumpWatchedEventsToVector(latestEvents);
6441
6442 if (!latestEvents.empty()) {
6443 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006444 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006445 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006446 latestEvents,
6447 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006448 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006449 }
6450 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006451 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006452 break;
6453 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006454 }
6455 return OK;
6456}
6457
Austin Borgered99f642023-06-01 16:51:35 -07006458void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006459 mWatchedClientPackages.clear();
6460
Austin Borgered99f642023-06-01 16:51:35 -07006461 std::istringstream iss(clients);
6462 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006463
Austin Borgered99f642023-06-01 16:51:35 -07006464 while (std::getline(iss, nextClient, ',')) {
6465 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006466 // Don't need to track any other package if 'all' is present
6467 mWatchedClientPackages.clear();
6468 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6469 break;
6470 }
6471
6472 // track package names
6473 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006474 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006475}
6476
Svet Ganova453d0d2018-01-11 15:37:58 -08006477status_t CameraService::printHelp(int out) {
6478 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006479 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6480 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6481 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006482 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6483 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6484 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006485 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6486 " Valid values 0=false, 1=true, 2=auto\n"
6487 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006488 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6489 " Valid values 0=OFF, 1=ON for JPEG\n"
6490 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006491 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006492 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6493 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6494 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6495 " on. In case the number of usecases is smaller than the number of streams, the\n"
6496 " last use case is assigned to all the remaining streams. In case of multiple\n"
6497 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6498 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6499 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6500 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006501 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6502 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006503 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6504 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006505 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006506 " help print this message\n");
6507}
6508
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006509bool CameraService::isClientWatched(const BasicClient *client) {
6510 Mutex::Autolock lock(mLogLock);
6511 return isClientWatchedLocked(client);
6512}
6513
6514bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6515 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6516 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6517}
6518
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006519int32_t CameraService::updateAudioRestriction() {
6520 Mutex::Autolock lock(mServiceLock);
6521 return updateAudioRestrictionLocked();
6522}
6523
6524int32_t CameraService::updateAudioRestrictionLocked() {
6525 int32_t mode = 0;
6526 // iterate through all active client
6527 for (const auto& i : mActiveClientManager.getAll()) {
6528 const auto clientSp = i->getValue();
6529 mode |= clientSp->getAudioRestriction();
6530 }
6531
6532 bool modeChanged = (mAudioRestriction != mode);
6533 mAudioRestriction = mode;
6534 if (modeChanged) {
6535 mAppOps.setCameraAudioRestriction(mode);
6536 }
6537 return mode;
6538}
6539
Austin Borgered99f642023-06-01 16:51:35 -07006540status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006541 sp<BasicClient> clientSp) {
6542 std::unique_ptr<AutoConditionLock> lock =
6543 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6544 status_t res = NO_ERROR;
6545 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006546 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006547 mInjectionStatusListener->notifyInjectionError(
6548 externalCamId, UNKNOWN_TRANSACTION);
6549 clientSp->notifyError(
6550 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6551 CaptureResultExtras());
6552
6553 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6554 // other clients from connecting in mServiceLockWrapper if held
6555 mServiceLock.unlock();
6556
6557 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006558 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006559 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006560 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006561
6562 // Reacquire mServiceLock
6563 mServiceLock.lock();
6564 }
6565
6566 return res;
6567}
6568
Cliff Wud3a05312021-04-26 23:07:31 +08006569void CameraService::clearInjectionParameters() {
6570 {
6571 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006572 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006573 mInjectionInternalCamId = "";
6574 }
6575 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006576 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006577}
6578
Biswarup Pal37a75182024-01-16 15:53:35 +00006579} // namespace android