blob: 22f196198bef83b3377cf41a7851f130f57a909d [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 {
92 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080093 const char* kActivityServiceName = "activity";
94 const char* kSensorPrivacyServiceName = "sensor_privacy";
95 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070096 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000097 const char* kVirtualDeviceBackCameraId = "0";
98 const char* kVirtualDeviceFrontCameraId = "1";
99
100 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
101 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
102 return android::kDefaultDeviceId;
103 }
104
105 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
106 return deviceIdEntry.data.i32[0];
107 }
108} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110namespace android {
111
Austin Borgerea931242021-12-13 23:10:41 +0000112using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700113using namespace camera3::SessionConfigurationUtils;
114
115using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000116using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700117using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700118using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800119using hardware::ICamera;
120using hardware::ICameraClient;
121using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800122using hardware::camera2::ICameraInjectionCallback;
123using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800124using hardware::camera2::utils::CameraIdAndSessionConfiguration;
125using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000126
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700127namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000128namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131// Logging support -- this is for debugging only
132// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700133volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Steve Blockb8a80522011-12-20 16:23:08 +0000135#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
136#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137
138static void setLogLevel(int level) {
139 android_atomic_write(level, &gLogLevel);
140}
141
Henri Chataingbcb99452023-11-01 17:40:30 +0000142int32_t format_as(CameraService::StatusInternal s) {
143 return fmt::underlying(s);
144}
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
Austin Borger249e6592024-03-10 22:28:11 -0700148// Permission strings (references to AttributionAndPermissionUtils for brevity)
149static const std::string &sDumpPermission =
150 AttributionAndPermissionUtils::sDumpPermission;
151static const std::string &sManageCameraPermission =
152 AttributionAndPermissionUtils::sManageCameraPermission;
153static const std::string &sCameraSendSystemEventsPermission =
154 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
155static const std::string &sCameraInjectExternalCameraPermission =
156 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
157
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000158// Constant integer for FGS Logging, used to denote the API type for logger
159static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700160const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800161static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
162static constexpr int32_t kSystemNativeClientState =
163 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700164static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700165
Austin Borgered99f642023-06-01 16:51:35 -0700166const std::string CameraService::kOfflineDevice("offline-");
167const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700168
Biswarup Pal7d072862024-04-17 15:24:47 +0000169constexpr int32_t kInvalidDeviceId = -1;
170
Rucha Katakward9ea6452021-05-06 11:57:16 -0700171// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700172static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700173
Austin Borger74fca042022-05-23 12:41:21 -0700174CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700175 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
176 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
177 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
178 std::make_shared<AttributionAndPermissionUtils>()\
179 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700180 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
181 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800182 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700184 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700185 mSoundRef(0), mInitialized(false),
186 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700188 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800189 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700190 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
191 if (mMemFd == -1) {
192 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
193 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700194}
195
Charles Chena7b613c2023-01-24 21:57:33 +0000196// Enable processes with isolated AID to request the binder
197void CameraService::instantiate() {
198 CameraService::publish(true);
199}
200
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800201void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700202 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800203 return;
204 }
205
206 ALOGV("appops service registered. setting camera audio restriction");
207 mAppOps.setCameraAudioRestriction(mAudioRestriction);
208}
209
Iliyan Malchev8951a972011-04-14 16:55:59 -0700210void CameraService::onFirstRef()
211{
Ruben Brunkcc776712015-02-17 20:18:47 -0800212 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800213
Iliyan Malchev8951a972011-04-14 16:55:59 -0700214 BnCameraService::onFirstRef();
215
Ruben Brunk99e69712015-05-26 17:25:07 -0700216 // Update battery life tracking if service is restarting
217 BatteryNotifier& notifier(BatteryNotifier::getInstance());
218 notifier.noteResetCamera();
219 notifier.noteResetFlashlight();
220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800222
Emilian Peevf53f66e2017-04-11 14:29:43 +0100223 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800224 if (res == OK) {
225 mInitialized = true;
226 }
227
Svet Ganova453d0d2018-01-11 15:37:58 -0800228 mUidPolicy = new UidPolicy(this);
229 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700230 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800231 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800232 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800233
234 // appops function setCamerAudioRestriction uses getService which
235 // is blocking till the appops service is ready. To enable early
236 // boot availability for cameraservice, use checkService which is
237 // non blocking and register for notifications
238 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700239 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800240 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700241 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800242 } else {
243 mAppOps.setCameraAudioRestriction(mAudioRestriction);
244 }
245
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700246 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
247 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000248 // Deprecated, so it will fail to register on newer devices
249 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700250 __FUNCTION__);
251 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700252
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700253 if (!AidlCameraService::registerService(this)) {
254 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
255 }
256
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 // This needs to be last call in this function, so that it's as close to
258 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700259 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700260 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261}
262
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800264 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100265
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000267 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 {
269 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271 if (nullptr == mCameraProviderManager.get()) {
272 mCameraProviderManager = new CameraProviderManager();
273 res = mCameraProviderManager->initialize(this);
274 if (res != OK) {
275 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
276 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700277 logServiceError("Unable to initialize camera provider manager",
278 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800279 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100280 }
281 }
282
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800283 // Setup vendor tags before we call get_camera_info the first time
284 // because HAL might need to setup static vendor keys in get_camera_info
285 // TODO: maybe put this into CameraProviderManager::initialize()?
286 mCameraProviderManager->setUpVendorTags();
287
288 if (nullptr == mFlashlight.get()) {
289 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700290 }
291
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292 res = mFlashlight->findFlashUnits();
293 if (res != OK) {
294 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
295 }
296
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800298 }
299
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800300 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700301 if (getCameraState(cameraId) == nullptr) {
302 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800303 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 if (unavailPhysicalIds.count(cameraId) > 0) {
305 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700306 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000307 }
308 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800309 }
310
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Derive primary rear/front cameras, and filter their charactierstics.
312 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700313 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700314 // Assume internal cameras are advertised from the same
315 // provider. If multiple providers are registered at different time,
316 // and each provider contains multiple internal color cameras, the current
317 // logic may filter the characteristics of more than one front/rear color
318 // cameras.
319 Mutex::Autolock l(mServiceLock);
320 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700321 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700322
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800323 return OK;
324}
325
Austin Borgered99f642023-06-01 16:51:35 -0700326void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700327 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000328 // Get the device id and app-visible camera id for the given HAL-visible camera id.
329 auto [deviceId, mappedCameraId] =
330 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
331
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800333 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700334 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
335 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000336 ALOGV("%s: Skipping torch callback for system-only camera device %s",
337 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700338 continue;
339 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000340
Austin Borgere8e2c422022-05-12 13:45:24 -0700341 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000342 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700343 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
344 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800345 }
346}
347
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800349 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800350 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800351 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800352 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700353}
354
Emilian Peevaee727d2017-05-04 16:35:48 +0100355void CameraService::onNewProviderRegistered() {
356 enumerateProviders();
357}
358
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700359void CameraService::filterAPI1SystemCameraLocked(
360 const std::vector<std::string> &normalDeviceIds) {
361 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000362 for (auto &cameraId : normalDeviceIds) {
363 if (vd_flags::camera_device_awareness()) {
364 CameraMetadata cameraInfo;
365 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000366 cameraId, false, &cameraInfo,
367 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000368 int32_t deviceId = kDefaultDeviceId;
369 if (res != OK) {
370 ALOGW("%s: Not able to get camera characteristics for camera id %s",
371 __FUNCTION__, cameraId.c_str());
372 } else {
373 deviceId = getDeviceId(cameraInfo);
374 }
375 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
376 // system cameras, so skip for non-default device id's.
377 if (deviceId != kDefaultDeviceId) {
378 continue;
379 }
380 }
381
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000383 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
384 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700385 continue;
386 }
387 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700388 // All system camera ids will necessarily come after public camera
389 // device ids as per the HAL interface contract.
390 break;
391 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000392 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 }
394 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
395 mNormalDeviceIdsWithoutSystemCamera.size());
396}
397
Austin Borgered99f642023-06-01 16:51:35 -0700398status_t CameraService::getSystemCameraKind(const std::string& cameraId,
399 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 auto state = getCameraState(cameraId);
401 if (state != nullptr) {
402 *kind = state->getSystemCameraKind();
403 return OK;
404 }
405 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700406 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700407}
408
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800409void CameraService::updateCameraNumAndIds() {
410 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700411 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
412 // Excludes hidden secure cameras
413 mNumberOfCameras =
414 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
415 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800416 mNormalDeviceIds =
417 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700418 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800419}
420
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700421void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422 // To claim to be S Performance primary cameras, the cameras must be
423 // backward compatible. So performance class primary camera Ids must be API1
424 // compatible.
425 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
426 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
427 int facing = -1;
428 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800429 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000430 getDeviceVersion(cameraId,
431 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
432 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700433 if (facing == -1) {
434 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
435 return;
436 }
437
438 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
439 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700440 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
441 if (res == OK) {
442 mPerfClassPrimaryCameraIds.insert(cameraId);
443 } else {
444 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
445 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
446 break;
447 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700448
449 if (facing == hardware::CAMERA_FACING_BACK) {
450 firstRearCameraSeen = true;
451 }
452 if (facing == hardware::CAMERA_FACING_FRONT) {
453 firstFrontCameraSeen = true;
454 }
455 }
456
457 if (firstRearCameraSeen && firstFrontCameraSeen) {
458 break;
459 }
460 }
461}
462
Austin Borgered99f642023-06-01 16:51:35 -0700463void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700464 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100465 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
466 if (res != OK) {
467 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
468 return;
469 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000470 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700471 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
472 if (res != OK) {
473 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
474 return;
475 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000476 std::vector<std::string> physicalCameraIds;
477 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700478 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700480 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100481 }
482
483 {
484 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700485 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000486 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100487 }
488
Austin Borgered99f642023-06-01 16:51:35 -0700489 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100490 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700491 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800492
Austin Borgered99f642023-06-01 16:51:35 -0700493 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100494 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800495
496 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700497 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498}
499
Austin Borgered99f642023-06-01 16:51:35 -0700500void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800501 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700502 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100503 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700504 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100505 }
506
507 {
508 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700509 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100510 }
511}
512
Austin Borgered99f642023-06-01 16:51:35 -0700513void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 CameraDeviceStatus newHalStatus) {
515 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700516 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 StatusInternal newStatus = mapToInternal(newHalStatus);
519
Austin Borgered99f642023-06-01 16:51:35 -0700520 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800521
522 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700523 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100524 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700525 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100526
527 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700528 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100529
Austin Borgered99f642023-06-01 16:51:35 -0700530 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700531 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700532 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700533 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700534 return;
535 }
536
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800539 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800540 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, 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",
Austin Borgered99f642023-06-01 16:51:35 -0700583 __FUNCTION__, id.c_str(), physicalId.c_str(), 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",
Austin Borgered99f642023-06-01 16:51:35 -0700599 __FUNCTION__, physicalId.c_str(), newHalStatus, 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",
Austin Borgered99f642023-06-01 16:51:35 -0700691 __FUNCTION__, cameraId.c_str(), 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
830 if (!flags::feature_combination_query()) {
831 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
832 "Camera subsystem doesn't support this method!");
833 }
834 if (!mInitialized) {
835 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
836 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
837 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
838 }
839
Austin Borger65e64642024-06-11 15:58:23 -0700840 std::optional<std::string> cameraIdOptional =
841 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000842 if (!cameraIdOptional.has_value()) {
843 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700844 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000845 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
846 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
847 }
848 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700849
850 binder::Status res;
851 if (request == nullptr) {
852 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
853 "Camera %s: Error creating default request", cameraId.c_str());
854 return res;
855 }
856 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
857 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
858 cameraId, templateId, &tempId);
859 if (!res.isOk()) {
860 ALOGE("%s: Camera %s: failed to map request Template %d",
861 __FUNCTION__, cameraId.c_str(), templateId);
862 return res;
863 }
864
865 if (shouldRejectSystemCameraConnection(cameraId)) {
866 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
867 "request for system only device %s: ", cameraId.c_str());
868 }
869
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700870 CameraMetadata metadata;
871 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
872 if (err == OK) {
873 request->swap(metadata);
874 } else if (err == BAD_VALUE) {
875 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
876 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
877 cameraId.c_str(), templateId, strerror(-err), err);
878 } else {
879 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
880 "Camera %s: Error creating default request for template %d: %s (%d)",
881 cameraId.c_str(), templateId, strerror(-err), err);
882 }
883 return res;
884}
885
886Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700887 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700888 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700889 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700890 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700891 ATRACE_CALL();
892
893 if (!flags::feature_combination_query()) {
894 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
895 "Camera subsystem doesn't support this method!");
896 }
897 if (!mInitialized) {
898 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
899 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
900 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
901 }
902
Austin Borger65e64642024-06-11 15:58:23 -0700903 std::optional<std::string> cameraIdOptional =
904 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000905 if (!cameraIdOptional.has_value()) {
906 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700907 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000908 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
909 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
910 }
911 std::string cameraId = cameraIdOptional.value();
912
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700913 if (supported == nullptr) {
914 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
915 unresolvedCameraId.c_str());
916 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
917 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
918 }
919
920 if (shouldRejectSystemCameraConnection(cameraId)) {
921 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
922 "session configuration with parameters support for system only device %s: ",
923 cameraId.c_str());
924 }
925
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700926 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
927 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
928 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
929
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700930 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
931 sessionConfiguration, overrideForPerfClass, supported);
932 if (flags::analytics_24q3()) {
933 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
934 getCallingUid(), sessionConfiguration, ret);
935 }
936 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700937}
938
939Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
940 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
941 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700942 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700943 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
944 cameraId, sessionConfiguration, overrideForPerfClass,
945 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700946 binder::Status res;
947 switch (ret) {
948 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700949 // Expected. Do Nothing.
950 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700951 case INVALID_OPERATION: {
952 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700953 "Camera %s: Session configuration with parameters supported query not "
954 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700955 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700956 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
957 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
958 *supported = false;
959 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700960 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700961 break;
962 case NAME_NOT_FOUND: {
963 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
964 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
965 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
966 *supported = false;
967 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
968 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700969 break;
970 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700971 std::string msg = fmt::sprintf(
972 "Unable to retrieve session configuration support for camera "
973 "device %s: Error: %s (%d)",
974 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700975 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700976 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
977 *supported = false;
978 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700979 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700980 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700981 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700982}
983
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800984Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000985 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700986 const SessionConfiguration& sessionConfiguration,
987 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000988 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800989 ATRACE_CALL();
990
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800991 if (outMetadata == nullptr) {
992 std::string msg =
993 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
994 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
995 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
996 }
997
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700998 if (!mInitialized) {
999 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1000 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1001 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1002 }
1003
Austin Borger65e64642024-06-11 15:58:23 -07001004 std::optional<std::string> cameraIdOptional =
1005 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001006 if (!cameraIdOptional.has_value()) {
1007 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001008 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001009 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1010 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1011 }
1012 std::string cameraId = cameraIdOptional.value();
1013
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001014 if (shouldRejectSystemCameraConnection(cameraId)) {
1015 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1016 "Unable to retrieve camera"
1017 "characteristics for system only device %s: ",
1018 cameraId.c_str());
1019 }
1020
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001021 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1022 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001023 if (flags::check_session_support_before_session_char()) {
1024 bool sessionConfigSupported;
1025 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1026 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1027 if (!res.isOk()) {
1028 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1029 // report the correct Status to send to the client. Simply forward the error to
1030 // the client.
1031 outMetadata->clear();
1032 return res;
1033 }
1034 if (!sessionConfigSupported) {
1035 std::string msg = fmt::sprintf(
1036 "Session configuration not supported for camera device %s.", cameraId.c_str());
1037 outMetadata->clear();
1038 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1039 }
1040 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001041
1042 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001043 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001044
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001045 switch (ret) {
1046 case OK:
1047 // Expected, no handling needed.
1048 break;
1049 case INVALID_OPERATION: {
1050 std::string msg = fmt::sprintf(
1051 "Camera %s: Session characteristics query not supported!",
1052 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001053 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001054 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1055 outMetadata->clear();
1056 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1057 }
1058 break;
1059 case NAME_NOT_FOUND: {
1060 std::string msg = fmt::sprintf(
1061 "Camera %s: Unknown camera ID.",
1062 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001063 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001064 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1065 outMetadata->clear();
1066 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001067 }
1068 break;
1069 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001070 std::string msg = fmt::sprintf(
1071 "Unable to retrieve session characteristics for camera device %s: "
1072 "Error: %s (%d)",
1073 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001074 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001075 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1076 outMetadata->clear();
1077 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001078 }
1079 }
1080
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001081 Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1082 if (flags::analytics_24q3()) {
1083 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1084 getCallingUid(), sessionConfiguration, res);
1085 }
1086 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001087}
1088
1089Status CameraService::filterSensitiveMetadataIfNeeded(
1090 const std::string& cameraId, CameraMetadata* metadata) {
1091 int callingPid = getCallingPid();
1092 int callingUid = getCallingUid();
1093
1094 if (callingPid == getpid()) {
1095 // Caller is cameraserver; no need to remove keys
1096 return Status::ok();
1097 }
1098
1099 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1100 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1101 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1102 metadata->clear();
1103 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1104 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1105 }
1106 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1107 // Attempting to query system only camera without system camera permission would have
1108 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1109 // for a system only camera, then the caller has the required permission.
1110 // No need to remove keys
1111 return Status::ok();
1112 }
1113
1114 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001115 // Get the device id that owns this camera.
1116 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1117 cameraId);
1118 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1119 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001120 if (hasCameraPermission) {
1121 // Caller has camera permission; no need to remove keys
1122 return Status::ok();
1123 }
1124
1125 status_t ret = metadata->removePermissionEntries(
1126 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1127 if (ret != OK) {
1128 metadata->clear();
1129 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1130 "Failed to remove camera characteristics needing camera permission "
1131 "for device %s:%s (%d)",
1132 cameraId.c_str(), strerror(-ret), ret);
1133 }
1134
1135 if (!tagsRemoved.empty()) {
1136 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1137 tagsRemoved.data(), tagsRemoved.size());
1138 if (ret != OK) {
1139 metadata->clear();
1140 return STATUS_ERROR_FMT(
1141 ERROR_INVALID_OPERATION,
1142 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1143 cameraId.c_str(), strerror(-ret), ret);
1144 }
1145 }
1146 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001147}
1148
malikakash22af94c2023-12-04 18:13:14 +00001149Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001150 const std::string& cameraId,
1151 const CameraMetadata& sessionParams) {
1152 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001153 const int pid = getCallingPid();
1154 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001155 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1156 __FUNCTION__, pid, uid);
1157 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1158 "Permission Denial: no permission to inject session params");
1159 }
1160
Biswarup Pal37a75182024-01-16 15:53:35 +00001161 // Do not allow session params injection for a virtual camera.
1162 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1163 if (deviceId != kDefaultDeviceId) {
1164 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1165 "Cannot inject session params for a virtual camera");
1166 }
1167
malikakash22af94c2023-12-04 18:13:14 +00001168 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1169 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1170
1171 auto clientDescriptor = mActiveClientManager.get(cameraId);
1172 if (clientDescriptor == nullptr) {
1173 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1174 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1175 "No active client for camera id %s", cameraId.c_str());
1176 }
1177
1178 sp<BasicClient> clientSp = clientDescriptor->getValue();
1179 status_t res = clientSp->injectSessionParams(sessionParams);
1180
1181 if (res != OK) {
1182 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1183 "Error injecting session params into camera \"%s\": %s (%d)",
1184 cameraId.c_str(), strerror(-res), res);
1185 }
1186 return Status::ok();
1187}
1188
Biswarup Pal37a75182024-01-16 15:53:35 +00001189std::optional<std::string> CameraService::resolveCameraId(
1190 const std::string& inputCameraId,
1191 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001192 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001193 if ((deviceId == kDefaultDeviceId)
1194 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1195 auto [storedDeviceId, _] =
1196 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1197 if (storedDeviceId != kDefaultDeviceId) {
1198 // Trying to access a virtual camera from default-policy device context, we should fail.
1199 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1200 inputCameraId.c_str(), deviceId);
1201 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1202 return std::nullopt;
1203 }
malikakash98260df2024-05-10 23:33:57 +00001204 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001205 }
1206
1207 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1208}
1209
Austin Borger65e64642024-06-11 15:58:23 -07001210Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1211 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1212 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001213 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001214 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001215 std::string cameraIdStr =
1216 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001217 if (cameraIdStr.empty()) {
1218 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001219 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001220 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1221 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1222 }
malikakashedb38962023-09-06 00:03:35 +00001223
Austin Borgered99f642023-06-01 16:51:35 -07001224 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001225 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1226 "characteristics for system only device %s: ", cameraIdStr.c_str());
1227 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001228
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001229 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001230 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001231 return STATUS_ERROR(ERROR_DISCONNECTED,
1232 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001233 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001234 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001235 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001236 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1237 if (hasSystemCameraPermissions) {
1238 cameraIdBound = mNumberOfCameras;
1239 }
1240 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001241 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1242 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001243 }
1244
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001245 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001246 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001247 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001248 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001249 if (err != OK) {
1250 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1251 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1252 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001253 logServiceError(std::string("Error retrieving camera info from device ")
1254 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001255 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001256
Ruben Brunkcc776712015-02-17 20:18:47 -08001257 return ret;
1258}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001259
Biswarup Pal37a75182024-01-16 15:53:35 +00001260std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1261 int32_t deviceId, int32_t devicePolicy) {
1262 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1263 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1264 std::optional<std::string> cameraIdOptional =
1265 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1266 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1267 }
1268
1269 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001270 auto callingPid = getCallingPid();
1271 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001272 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1273 callingPid, callingUid, /* checkCameraPermissions= */ false);
1274 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001275 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001276 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001277 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1278 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1279 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001280 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001281 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001282
malikakash98260df2024-05-10 23:33:57 +00001283 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001284}
1285
Biswarup Pal37a75182024-01-16 15:53:35 +00001286std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1287 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001288 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001289 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001290}
1291
Austin Borgered99f642023-06-01 16:51:35 -07001292Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001293 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1294 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001295 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001296
Zhijun He2b59be82013-09-25 10:14:30 -07001297 if (!cameraInfo) {
1298 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001299 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001300 }
1301
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001302 if (!mInitialized) {
1303 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001304 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001305 return STATUS_ERROR(ERROR_DISCONNECTED,
1306 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001307 }
1308
Austin Borger65e64642024-06-11 15:58:23 -07001309 std::optional<std::string> cameraIdOptional =
1310 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001311 if (!cameraIdOptional.has_value()) {
1312 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001313 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001314 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1315 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1316 }
1317 std::string cameraId = cameraIdOptional.value();
1318
Austin Borgered99f642023-06-01 16:51:35 -07001319 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001320 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001321 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001322 }
1323
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001324 bool overrideForPerfClass =
1325 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001326 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001327 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001328 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001329 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001330 if (res == NAME_NOT_FOUND) {
1331 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001332 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001333 strerror(-res), res);
1334 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001335 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1336 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001337 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001338 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001339 strerror(-res), res);
1340 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001341 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001342
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001343 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001344}
1345
Austin Borger65e64642024-06-11 15:58:23 -07001346Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1347 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001348 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001349 ATRACE_CALL();
1350 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001351
Austin Borger65e64642024-06-11 15:58:23 -07001352 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1353 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001354 if (!cameraIdOptional.has_value()) {
1355 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001356 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001357 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1358 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1359 }
1360 std::string cameraId = cameraIdOptional.value();
1361
Rucha Katakwar38284522021-11-10 11:25:21 -08001362 if (!mInitialized) {
1363 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1364 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1365 }
1366
Biswarup Pal37a75182024-01-16 15:53:35 +00001367 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001368 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1369 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1370 }
1371
Austin Borgered99f642023-06-01 16:51:35 -07001372 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001373 if (res != OK) {
1374 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001375 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001376 strerror(-res), res);
1377 }
1378 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1379 return Status::ok();
1380}
1381
Austin Borgered99f642023-06-01 16:51:35 -07001382std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001383 time_t now = time(nullptr);
1384 char formattedTime[64];
1385 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001386 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001387}
1388
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001389Status CameraService::getCameraVendorTagDescriptor(
1390 /*out*/
1391 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001392 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001393 if (!mInitialized) {
1394 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001395 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001396 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001397 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1398 if (globalDescriptor != nullptr) {
1399 *desc = *(globalDescriptor.get());
1400 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001401 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001402}
1403
Emilian Peev71c73a22017-03-21 16:35:51 +00001404Status CameraService::getCameraVendorTagCache(
1405 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1406 ATRACE_CALL();
1407 if (!mInitialized) {
1408 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1409 return STATUS_ERROR(ERROR_DISCONNECTED,
1410 "Camera subsystem not available");
1411 }
1412 sp<VendorTagDescriptorCache> globalCache =
1413 VendorTagDescriptorCache::getGlobalVendorTagCache();
1414 if (globalCache != nullptr) {
1415 *cache = *(globalCache.get());
1416 }
1417 return Status::ok();
1418}
1419
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001420void CameraService::clearCachedVariables() {
1421 BasicClient::BasicClient::sCameraService = nullptr;
1422}
1423
Austin Borgered99f642023-06-01 16:51:35 -07001424std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001425 int rotationOverride, int* portraitRotation, int* facing,
1426 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001427 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001428
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001429 int deviceVersion = 0;
1430
Emilian Peevf53f66e2017-04-11 14:29:43 +01001431 status_t res;
1432 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001433 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001434 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001435 if (res != OK || transport == IPCTransport::INVALID) {
1436 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001437 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001438 return std::make_pair(-1, IPCTransport::INVALID) ;
1439 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001440 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001441
Emilian Peevf53f66e2017-04-11 14:29:43 +01001442 hardware::CameraInfo info;
1443 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001444 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001445 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001446 if (res != OK) {
1447 return std::make_pair(-1, IPCTransport::INVALID);
1448 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001449 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001450 if (orientation) {
1451 *orientation = info.orientation;
1452 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001453 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001454
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001455 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001456}
1457
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001458Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001459 switch(err) {
1460 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001461 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001462 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001463 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1464 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001465 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001466 return STATUS_ERROR(ERROR_DISCONNECTED,
1467 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001468 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001469 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1470 "Camera HAL encountered error %d: %s",
1471 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001472 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001473}
1474
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001475Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001476 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1477 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001478 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001479 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001480 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001481 bool forceSlowJpegMode, const std::string& originalCameraId,
1482 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001483 // For HIDL devices
1484 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1485 // Create CameraClient based on device version reported by the HAL.
1486 int deviceVersion = deviceVersionAndTransport.first;
1487 switch(deviceVersion) {
1488 case CAMERA_DEVICE_API_VERSION_1_0:
1489 ALOGE("Camera using old HAL version: %d", deviceVersion);
1490 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1491 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001492 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001493 break;
1494 case CAMERA_DEVICE_API_VERSION_3_0:
1495 case CAMERA_DEVICE_API_VERSION_3_1:
1496 case CAMERA_DEVICE_API_VERSION_3_2:
1497 case CAMERA_DEVICE_API_VERSION_3_3:
1498 case CAMERA_DEVICE_API_VERSION_3_4:
1499 case CAMERA_DEVICE_API_VERSION_3_5:
1500 case CAMERA_DEVICE_API_VERSION_3_6:
1501 case CAMERA_DEVICE_API_VERSION_3_7:
1502 break;
1503 default:
1504 // Should not be reachable
1505 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1506 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1507 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001508 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001509 }
1510 }
1511 if (effectiveApiLevel == API_1) { // Camera1 API route
1512 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001513 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001514 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001515 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001516 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001517 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001518 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1519 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001520 } else { // Camera2 API route
1521 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1522 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001523 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001524 cameraService->mCameraServiceProxyWrapper,
1525 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001526 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001527 overrideForPerfClass, rotationOverride, originalCameraId);
1528 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001529 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001530 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001531}
1532
Austin Borgered99f642023-06-01 16:51:35 -07001533std::string CameraService::toString(std::set<userid_t> intSet) {
1534 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001535 bool first = true;
1536 for (userid_t i : intSet) {
1537 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001538 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001539 first = false;
1540 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001541 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001542 }
1543 }
Austin Borgered99f642023-06-01 16:51:35 -07001544 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001545}
1546
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001547int32_t CameraService::mapToInterface(TorchModeStatus status) {
1548 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1549 switch (status) {
1550 case TorchModeStatus::NOT_AVAILABLE:
1551 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1552 break;
1553 case TorchModeStatus::AVAILABLE_OFF:
1554 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1555 break;
1556 case TorchModeStatus::AVAILABLE_ON:
1557 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1558 break;
1559 default:
1560 ALOGW("Unknown new flash status: %d", status);
1561 }
1562 return serviceStatus;
1563}
1564
1565CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1566 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1567 switch (status) {
1568 case CameraDeviceStatus::NOT_PRESENT:
1569 serviceStatus = StatusInternal::NOT_PRESENT;
1570 break;
1571 case CameraDeviceStatus::PRESENT:
1572 serviceStatus = StatusInternal::PRESENT;
1573 break;
1574 case CameraDeviceStatus::ENUMERATING:
1575 serviceStatus = StatusInternal::ENUMERATING;
1576 break;
1577 default:
1578 ALOGW("Unknown new HAL device status: %d", status);
1579 }
1580 return serviceStatus;
1581}
1582
1583int32_t CameraService::mapToInterface(StatusInternal status) {
1584 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1585 switch (status) {
1586 case StatusInternal::NOT_PRESENT:
1587 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1588 break;
1589 case StatusInternal::PRESENT:
1590 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1591 break;
1592 case StatusInternal::ENUMERATING:
1593 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1594 break;
1595 case StatusInternal::NOT_AVAILABLE:
1596 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1597 break;
1598 case StatusInternal::UNKNOWN:
1599 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1600 break;
1601 default:
1602 ALOGW("Unknown new internal device status: %d", status);
1603 }
1604 return serviceStatus;
1605}
1606
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001607Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001608 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001609
Austin Borgered99f642023-06-01 16:51:35 -07001610 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001611 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001612 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001613 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001614 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1615 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001616 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001617 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1618 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borgered99f642023-06-01 16:51:35 -07001619 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001620 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001621 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001622 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001623 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001624}
1625
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001626Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001627 /*out*/
1628 CameraParameters* parameters) {
1629
1630 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1631
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001632 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001633
1634 if (parameters == NULL) {
1635 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001636 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001637 }
1638
malikakash98260df2024-05-10 23:33:57 +00001639 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001640
1641 // Check if we already have parameters
1642 {
1643 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001644 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001645 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001646 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001647 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001648 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001649 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001650 }
1651 CameraParameters p = cameraState->getShimParams();
1652 if (!p.isEmpty()) {
1653 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001655 }
1656 }
1657
Austin Borger22c5c852024-03-08 13:31:36 -08001658 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001659 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001660 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001661 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001662 // Error already logged by callee
1663 return ret;
1664 }
1665
1666 // Check for parameters again
1667 {
1668 // Scope for service lock
1669 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001670 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001672 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001673 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001674 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001675 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001676 CameraParameters p = cameraState->getShimParams();
1677 if (!p.isEmpty()) {
1678 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001679 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001680 }
1681 }
1682
Ruben Brunkcc776712015-02-17 20:18:47 -08001683 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1684 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001685 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001686}
1687
Austin Borgered99f642023-06-01 16:51:35 -07001688Status CameraService::validateConnectLocked(const std::string& cameraId,
1689 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001690 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001691
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001692#ifdef __BRILLO__
1693 UNUSED(clientName8);
1694 UNUSED(clientUid);
1695 UNUSED(clientPid);
1696 UNUSED(originalClientPid);
1697#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001698 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1699 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001700 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001701 return allowed;
1702 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001703#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001704
Austin Borger22c5c852024-03-08 13:31:36 -08001705 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001706
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001707 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001708 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1709 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001710 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001711 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001712 }
1713
Ruben Brunkcc776712015-02-17 20:18:47 -08001714 if (getCameraState(cameraId) == nullptr) {
1715 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001716 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001717 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001718 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001719 }
1720
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001721 status_t err = checkIfDeviceIsUsable(cameraId);
1722 if (err != NO_ERROR) {
1723 switch(err) {
1724 case -ENODEV:
1725 case -EBUSY:
1726 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001727 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001728 default:
1729 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001730 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001731 }
1732 }
1733 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001734}
1735
Austin Borgered99f642023-06-01 16:51:35 -07001736Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1737 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001738 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001739 int callingPid = getCallingPid();
1740 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001742 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001743 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001744 clientUid = callingUid;
1745 } else if (!isTrustedCallingUid(callingUid)) {
1746 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1747 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001748 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1749 "Untrusted caller (calling PID %d, UID %d) trying to "
1750 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001751 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001752 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001753 }
1754
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001755 // Check if we can trust clientPid
1756 if (clientPid == USE_CALLING_PID) {
1757 clientPid = callingPid;
1758 } else if (!isTrustedCallingUid(callingUid)) {
1759 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1760 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001761 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1762 "Untrusted caller (calling PID %d, UID %d) trying to "
1763 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001764 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001765 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001766 }
1767
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001768 if (shouldRejectSystemCameraConnection(cameraId)) {
1769 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1770 cameraId.c_str());
1771 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001772 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001773 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001774 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1775 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001776 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001777 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001778 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001779 }
1780
Biswarup Pale506e732024-03-27 13:46:20 +00001781 // Get the device id that owns this camera.
1782 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1783
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001784 // If it's not calling from cameraserver, check the permission if the
1785 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1786 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001787 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001788 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001789 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001790 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001791 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1793 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001794 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001795 }
1796
Svet Ganova453d0d2018-01-11 15:37:58 -08001797 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001798 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001799 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001800 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1801 clientPid, clientUid);
1802 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001803 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1804 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001805 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001806 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001807 }
1808
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001809 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1810 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1811 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1812 if ((!isAutomotivePrivilegedClient(callingUid) ||
1813 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1814 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001815 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1816 return STATUS_ERROR_FMT(ERROR_DISABLED,
1817 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001818 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001819 }
1820
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001821 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1822 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001823 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001824 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001825
Ruben Brunk6267b532015-04-30 17:44:07 -07001826 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08001827
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001828 // For non-system clients : Only allow clients who are being used by the current foreground
1829 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001830 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001831 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001832 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1833 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001834 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001835 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1836 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001837 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001838 }
1839
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001840 if (flags::camera_hsum_permission()) {
1841 // If the System User tries to access the camera when the device is running in
1842 // headless system user mode, ensure that client has the required permission
1843 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001844 if (isHeadlessSystemUserMode()
1845 && (clientUserId == USER_SYSTEM)
1846 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001847 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
1848 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1849 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1850 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07001851 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001852 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001853 }
1854
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001855 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001856}
1857
Austin Borgered99f642023-06-01 16:51:35 -07001858status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001859 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001860 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001861 if (cameraState == nullptr) {
1862 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001863 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001864 return -ENODEV;
1865 }
1866
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001867 StatusInternal currentStatus = cameraState->getStatus();
1868 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001869 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001870 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001871 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001872 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001874 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001875 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001876 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001877
Ruben Brunkcc776712015-02-17 20:18:47 -08001878 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001879}
1880
Ruben Brunkcc776712015-02-17 20:18:47 -08001881void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001882 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001883
Ruben Brunkcc776712015-02-17 20:18:47 -08001884 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001885 auto clientDescriptor =
1886 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001887 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001888 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1889
1890 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001891 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001892
1893 if (evicted.size() > 0) {
1894 // This should never happen - clients should already have been removed in disconnect
1895 for (auto& i : evicted) {
1896 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001897 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001898 }
1899
1900 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1901 __FUNCTION__);
1902 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001903
1904 // And register a death notification for the client callback. Do
1905 // this last to avoid Binder policy where a nested Binder
1906 // transaction might be pre-empted to service the client death
1907 // notification if the client process dies before linkToDeath is
1908 // invoked.
1909 sp<IBinder> remoteCallback = client->getRemote();
1910 if (remoteCallback != nullptr) {
1911 remoteCallback->linkToDeath(this);
1912 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001913}
1914
Austin Borgered99f642023-06-01 16:51:35 -07001915status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1916 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1917 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001918 /*out*/
1919 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001920 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001921 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001922 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001923 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001924 DescriptorPtr clientDescriptor;
1925 {
1926 if (effectiveApiLevel == API_1) {
1927 // If we are using API1, any existing client for this camera ID with the same remote
1928 // should be returned rather than evicted to allow MediaRecorder to work properly.
1929
1930 auto current = mActiveClientManager.get(cameraId);
1931 if (current != nullptr) {
1932 auto clientSp = current->getValue();
1933 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001934 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001935 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001936 " API level, evicting prior client...");
1937 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001938 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001939 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001940 *client = clientSp;
1941 return NO_ERROR;
1942 }
1943 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001944 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001945 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001946
Ruben Brunkcc776712015-02-17 20:18:47 -08001947 // Get state for the given cameraId
1948 auto state = getCameraState(cameraId);
1949 if (state == nullptr) {
1950 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001951 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001952 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001953 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001954 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001955
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001956 sp<IServiceManager> sm = defaultServiceManager();
1957 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001958 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001959 // If processinfo service is not available and the client is automotive privileged
1960 // client used for safety critical uses cases such as rear-view and surround-view which
1961 // needs to be available before android boot completes, then use the hardcoded values
1962 // for the process state and priority score. As this scenario is before android system
1963 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1964 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1965 // visible on the top.
1966 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1967 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1968 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1969 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1970 } else {
1971 // Get current active client PIDs
1972 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1973 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001974
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001975 std::vector<int> priorityScores(ownerPids.size());
1976 std::vector<int> states(ownerPids.size());
1977
1978 // Get priority scores of all active PIDs
1979 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1980 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1981 if (err != OK) {
1982 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1983 return err;
1984 }
1985
1986 // Update all active clients' priorities
1987 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1988 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1989 pidToPriorityMap.emplace(ownerPids[i],
1990 resource_policy::ClientPriority(priorityScores[i], states[i],
1991 /* isVendorClient won't get copied over*/ false,
1992 /* oomScoreOffset won't get copied over*/ 0));
1993 }
1994 mActiveClientManager.updatePriorities(pidToPriorityMap);
1995
1996 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1997 int32_t actualState = states[states.size() - 1];
1998
1999 // Make descriptor for incoming client. We store the oomScoreOffset
2000 // since we might need it later on new handleEvictionsLocked and
2001 // ProcessInfoService would not take that into account.
2002 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2003 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2004 state->getConflicting(), actualScore, clientPid, actualState,
2005 oomScoreOffset, systemNativeClient);
2006 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002007
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002008 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2009
Ruben Brunkcc776712015-02-17 20:18:47 -08002010 // Find clients that would be evicted
2011 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2012
2013 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2014 // background, so we cannot do evictions
2015 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2016 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2017 " priority).", clientPid);
2018
2019 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002020 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002021 auto incompatibleClients =
2022 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2023
Austin Borgered99f642023-06-01 16:51:35 -07002024 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2025 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2026 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002027 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002028
2029 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002030 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002031 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002032 i->getKey().c_str(),
2033 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002034 i->getOwnerId(), i->getPriority().getScore(),
2035 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002036 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002037 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2038 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002039 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002040 }
2041
2042 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002043 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002044 mEventLog.add(msg);
2045
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002046 auto current = mActiveClientManager.get(cameraId);
2047 if (current != nullptr) {
2048 return -EBUSY; // CAMERA_IN_USE
2049 } else {
2050 return -EUSERS; // MAX_CAMERAS_IN_USE
2051 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002052 }
2053
2054 for (auto& i : evicted) {
2055 sp<BasicClient> clientSp = i->getValue();
2056 if (clientSp.get() == nullptr) {
2057 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2058
2059 // TODO: Remove this
2060 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2061 __FUNCTION__);
2062 mActiveClientManager.remove(i);
2063 continue;
2064 }
2065
2066 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002067 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002068 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002069
Ruben Brunkcc776712015-02-17 20:18:47 -08002070 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002071 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002072 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2073 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002074 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002075 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002076 i->getPriority().getState(), cameraId.c_str(),
2077 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002078 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002079
2080 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002081 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002082 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002083 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002084 }
2085
Ruben Brunkcc776712015-02-17 20:18:47 -08002086 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2087 // other clients from connecting in mServiceLockWrapper if held
2088 mServiceLock.unlock();
2089
2090 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002091 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002092
2093 // Destroy evicted clients
2094 for (auto& i : evictedClients) {
2095 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002096 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002097 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002098
Austin Borger22c5c852024-03-08 13:31:36 -08002099 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002100
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002101 for (const auto& i : evictedClients) {
2102 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002103 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002104 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2105 if (ret == TIMED_OUT) {
2106 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002107 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2108 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002109 return -EBUSY;
2110 }
2111 if (ret != NO_ERROR) {
2112 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002113 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2114 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002115 return ret;
2116 }
2117 }
2118
2119 evictedClients.clear();
2120
Ruben Brunkcc776712015-02-17 20:18:47 -08002121 // Once clients have been disconnected, relock
2122 mServiceLock.lock();
2123
2124 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2125 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2126 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002127 }
2128
Ruben Brunkcc776712015-02-17 20:18:47 -08002129 *partial = clientDescriptor;
2130 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002131}
2132
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002133Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002134 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002135 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002136 const std::string& clientPackageName,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002137 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002138 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002139 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002140 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002141 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002142 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002143 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002144 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002145 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002146
Austin Borger65e64642024-06-11 15:58:23 -07002147 std::string cameraIdStr =
2148 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002149 if (cameraIdStr.empty()) {
2150 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002151 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002152 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2153 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2154 }
malikakashedb38962023-09-06 00:03:35 +00002155
Ruben Brunkcc776712015-02-17 20:18:47 -08002156 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002157 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002158 clientPackageName, /*systemNativeClient*/ false, {}, clientAttribution.uid,
2159 clientAttribution.pid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002160 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002161 rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002162
Biswarup Pal37a75182024-01-16 15:53:35 +00002163 if (!ret.isOk()) {
2164 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002165 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002166 }
2167
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002168 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002169
2170 const sp<IServiceManager> sm(defaultServiceManager());
2171 const auto& mActivityManager = getActivityManager();
2172 if (mActivityManager) {
2173 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002174 getCallingUid(),
2175 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002176 }
2177
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002178 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002179}
2180
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002181bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2182 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002183 // If the client is not a vendor client, don't add listener if
2184 // a) the camera is a publicly hidden secure camera OR
2185 // b) the camera is a system only camera and the client doesn't
2186 // have android.permission.SYSTEM_CAMERA permissions.
2187 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2188 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002189 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002190 return true;
2191 }
2192 return false;
2193}
2194
Austin Borgered99f642023-06-01 16:51:35 -07002195bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002196 // Rules for rejection:
2197 // 1) If cameraserver tries to access this camera device, accept the
2198 // connection.
2199 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002200 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002201 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2202 // and the serving thread is a non hwbinder thread, the client must have
2203 // android.permission.SYSTEM_CAMERA permissions to connect.
2204
Austin Borger22c5c852024-03-08 13:31:36 -08002205 int cPid = getCallingPid();
2206 int cUid = getCallingUid();
2207 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002208 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2209 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002210 // This isn't a known camera ID, so it's not a system camera
2211 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2212 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002213 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002214
2215 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002216 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002217 return false;
2218 }
2219 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002220 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002221 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2222 return true;
2223 }
2224 // (3) Here we only check for permissions if it is a system only camera device. This is since
2225 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2226 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2227 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002228 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002229 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002230 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2231 cameraId.c_str());
2232 return true;
2233 }
2234
2235 return false;
2236}
2237
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002238Status CameraService::connectDevice(
2239 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002240 const std::string& unresolvedCameraId,
2241 const std::string& clientPackageName,
2242 const std::optional<std::string>& clientFeatureId,
Austin Borger65e64642024-06-11 15:58:23 -07002243 int oomScoreOffset, int targetSdkVersion,
2244 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002245 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002246 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002247 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002248 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002250 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002251 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002252 int callingPid = getCallingPid();
2253 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002254 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002255 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002256 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002257 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002258 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002259 }
Austin Borger249e6592024-03-10 22:28:11 -07002260
Austin Borger65e64642024-06-11 15:58:23 -07002261 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2262 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002263 if (!cameraIdOptional.has_value()) {
2264 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002265 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002266 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2267 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2268 }
2269 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002270
2271 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002272 std::string msg =
2273 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2274 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2275 cameraId.c_str());
2276 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
Austin Borger65e64642024-06-11 15:58:23 -07002280 userid_t clientUserId = multiuser_get_user_id(clientAttribution.uid);
2281 if (clientAttribution.uid == USE_CALLING_UID) {
Austin Borger9bfa0a72022-08-03 17:50:40 -07002282 clientUserId = multiuser_get_user_id(callingUid);
2283 }
2284
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002285 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2286 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002287 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2288 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002289 std::string msg = "Camera disabled by device policy";
2290 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2291 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002292 }
2293
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002294 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002295 if (oomScoreOffset > 0
2296 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002297 callingUid)
2298 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002299 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002300 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002301 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2302 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2303 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002304 }
2305
Austin Borgered99f642023-06-01 16:51:35 -07002306 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2307 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Austin Borger65e64642024-06-11 15:58:23 -07002308 clientAttribution.uid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false,
2309 oomScoreOffset, targetSdkVersion, rotationOverride, /*forceSlowJpegMode*/false,
2310 unresolvedCameraId, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002311
Biswarup Pal37a75182024-01-16 15:53:35 +00002312 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002313 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002314 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002315 }
2316
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002317 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002318 Mutex::Autolock lock(mServiceLock);
2319
2320 // Clear the previous cached logs and reposition the
2321 // file offset to beginning of the file to log new data.
2322 // If either truncate or lseek fails, close the previous file and create a new one.
2323 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2324 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2325 // Close the previous memfd.
2326 close(mMemFd);
2327 // If failure to wipe the data, then create a new file and
2328 // assign the new value to mMemFd.
2329 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2330 if (mMemFd == -1) {
2331 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2332 }
2333 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002334 const sp<IServiceManager> sm(defaultServiceManager());
2335 const auto& mActivityManager = getActivityManager();
2336 if (mActivityManager) {
2337 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002338 callingUid,
2339 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002340 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002341 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002342}
2343
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002344bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2345 int callingPid, int callingUid) {
2346 if (!isAutomotiveDevice()) {
2347 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2348 }
2349
2350 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2351 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2352 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2353 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2354 "using camera %s", callingUid, cam_id.c_str());
2355 return false;
2356 }
2357
2358 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2359 return true;
2360 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2361 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002362 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2363 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002364 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2365 return false;
2366 } else {
2367 return true;
2368 }
2369 }
2370 return false;
2371}
2372
Austin Borgered99f642023-06-01 16:51:35 -07002373std::string CameraService::getPackageNameFromUid(int clientUid) {
2374 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002375
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002376 sp<IPermissionController> permCtrl;
2377 if (flags::cache_permission_services()) {
2378 permCtrl = getPermissionController();
2379 } else {
2380 sp<IServiceManager> sm = defaultServiceManager();
2381#pragma clang diagnostic push
2382#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2383 // Using deprecated function to preserve functionality until the
2384 // cache_permission_services flag is removed.
2385 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2386#pragma clang diagnostic pop
2387 if (binder == 0) {
2388 ALOGE("Cannot get permission service");
2389 permCtrl = nullptr;
2390 } else {
2391 permCtrl = interface_cast<IPermissionController>(binder);
2392 }
2393 }
2394
2395 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002396 // Return empty package name and the further interaction
2397 // with camera will likely fail
2398 return packageName;
2399 }
2400
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002401 Vector<String16> packages;
2402
2403 permCtrl->getPackagesForUid(clientUid, packages);
2404
2405 if (packages.isEmpty()) {
2406 ALOGE("No packages for calling UID %d", clientUid);
2407 // Return empty package name and the further interaction
2408 // with camera will likely fail
2409 return packageName;
2410 }
2411
2412 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002413 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002414
2415 return packageName;
2416}
2417
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002418template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002419Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2420 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2421 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002422 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002423 int rotationOverride, bool forceSlowJpegMode,
2424 const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002425 binder::Status ret = binder::Status::ok();
2426
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002427 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002428 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002429 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002430 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002431 if (clientPackageNameMaybe.size() <= 0) {
2432 // NDK calls don't come with package names, but we need one for various cases.
2433 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2434 // do exist. For all authentication cases, all packages under the same UID get the
2435 // same permissions, so picking any associated package name is sufficient. For some
2436 // other cases, this may give inaccurate names for clients in logs.
2437 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002438 clientPackageName = getPackageNameFromUid(packageUid);
2439 } else {
2440 clientPackageName = clientPackageNameMaybe;
2441 }
2442
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002443 int originalClientPid = 0;
2444
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002445 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002446 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002447 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002448 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002449 static_cast<int>(effectiveApiLevel));
2450
Shuzhen Wang316781a2020-08-18 18:11:01 -07002451 nsecs_t openTimeNs = systemTime();
2452
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002453 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002454 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002455 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002456
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002457 {
2458 // Acquire mServiceLock and prevent other clients from connecting
2459 std::unique_ptr<AutoConditionLock> lock =
2460 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2461
2462 if (lock == nullptr) {
2463 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2464 , clientPid);
2465 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2466 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002467 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002468 }
2469
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002470 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002471 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002472 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2473 return ret;
2474 }
2475
2476 // Check the shim parameters after acquiring lock, if they have already been updated and
2477 // we were doing a shim update, return immediately
2478 if (shimUpdateOnly) {
2479 auto cameraState = getCameraState(cameraId);
2480 if (cameraState != nullptr) {
2481 if (!cameraState->getShimParams().isEmpty()) return ret;
2482 }
2483 }
2484
2485 status_t err;
2486
2487 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002488 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002489 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002490 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2491 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002492 switch (err) {
2493 case -ENODEV:
2494 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2495 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002496 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002497 case -EBUSY:
2498 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2499 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002500 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002501 case -EUSERS:
2502 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2503 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002504 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002505 default:
2506 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2507 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002508 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002509 }
2510 }
2511
2512 if (clientTmp.get() != nullptr) {
2513 // Handle special case for API1 MediaRecorder where the existing client is returned
2514 device = static_cast<CLIENT*>(clientTmp.get());
2515 return ret;
2516 }
2517
2518 // give flashlight a chance to close devices if necessary.
2519 mFlashlight->prepareDeviceOpen(cameraId);
2520
Austin Borger18b30a72022-10-27 12:20:29 -07002521 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002522 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002523 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002524 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002525 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002526 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002527 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002528 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002529 }
2530
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002531 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002532 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002533 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002534
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002535 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002536 clientFeatureId, cameraId, api1CameraId, facing,
2537 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002538 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002539 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002540 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002541 return ret;
2542 }
2543 client = static_cast<CLIENT*>(tmp.get());
2544
2545 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2546 __FUNCTION__);
2547
Austin Borgered99f642023-06-01 16:51:35 -07002548 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002549 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002550 if (err != OK) {
2551 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002552 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002553 mServiceLock.unlock();
2554 client->disconnect();
2555 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002556 switch(err) {
2557 case BAD_VALUE:
2558 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002559 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002560 case -EBUSY:
2561 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002562 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002563 case -EUSERS:
2564 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2565 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002566 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002567 case PERMISSION_DENIED:
2568 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002569 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002570 case -EACCES:
2571 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002572 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002573 case -ENODEV:
2574 default:
2575 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002576 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002577 strerror(-err), err);
2578 }
2579 }
2580
2581 // Update shim paremeters for legacy clients
2582 if (effectiveApiLevel == API_1) {
2583 // Assume we have always received a Client subclass for API1
2584 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2585 String8 rawParams = shimClient->getParameters();
2586 CameraParameters params(rawParams);
2587
2588 auto cameraState = getCameraState(cameraId);
2589 if (cameraState != nullptr) {
2590 cameraState->setShimParams(params);
2591 } else {
2592 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002593 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002594 }
2595 }
2596
Ravneetaeb20dc2022-03-30 05:33:03 +00002597 // Enable/disable camera service watchdog
2598 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2599
Emilian Peev6d45db82024-01-18 20:11:54 +00002600 CameraMetadata chars;
2601 bool rotateAndCropSupported = true;
2602 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002603 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002604 if (err == OK) {
2605 auto availableRotateCropEntry = chars.find(
2606 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2607 if (availableRotateCropEntry.count <= 1) {
2608 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002609 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002610 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002611 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2612 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002613 }
2614
Emilian Peev6d45db82024-01-18 20:11:54 +00002615 if (rotateAndCropSupported) {
2616 // Set rotate-and-crop override behavior
2617 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2618 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002619 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2620 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002621 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2622 switch (portraitRotation) {
2623 case 90:
2624 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2625 break;
2626 case 180:
2627 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2628 break;
2629 case 270:
2630 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2631 break;
2632 default:
2633 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2634 break;
2635 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002636 // Here we're communicating to the client the chosen rotate
2637 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002638 client->setRotateAndCropOverride(rotateAndCropMode);
2639 } else {
2640 client->setRotateAndCropOverride(
2641 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2642 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2643 }
2644 }
2645
2646 bool autoframingSupported = true;
2647 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2648 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2649 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2650 autoframingSupported = false;
2651 }
2652
2653 if (autoframingSupported) {
2654 // Set autoframing override behaviour
2655 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2656 client->setAutoframingOverride(mOverrideAutoframingMode);
2657 } else {
2658 client->setAutoframingOverride(
2659 mCameraServiceProxyWrapper->getAutoframingOverride(
2660 clientPackageName));
2661 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002662 }
2663
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002664 bool isCameraPrivacyEnabled;
2665 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002666 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002667 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2668 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2669 } else {
2670 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002671 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002672 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002673
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002674 if (client->supportsCameraMute()) {
2675 client->setCameraMute(
2676 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2677 } else if (isCameraPrivacyEnabled) {
2678 // no camera mute supported, but privacy is on! => disconnect
2679 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2680 client->getPackageName().c_str(), cameraId.c_str());
2681 // Do not hold mServiceLock while disconnecting clients, but
2682 // retain the condition blocking other clients from connecting
2683 // in mServiceLockWrapper if held.
2684 mServiceLock.unlock();
2685 // Clear caller identity temporarily so client disconnect PID
2686 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002687 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002688 // Note AppOp to trigger the "Unblock" dialog
2689 client->noteAppOp();
2690 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002691 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002692 // Reacquire mServiceLock
2693 mServiceLock.lock();
2694
2695 return STATUS_ERROR_FMT(ERROR_DISABLED,
2696 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002697 }
2698
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002699 if (shimUpdateOnly) {
2700 // If only updating legacy shim parameters, immediately disconnect client
2701 mServiceLock.unlock();
2702 client->disconnect();
2703 mServiceLock.lock();
2704 } else {
2705 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002706 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002707 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002708
2709 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002710 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002711 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002712 } // lock is destroyed, allow further connect calls
2713
2714 // Important: release the mutex here so the client can call back into the service from its
2715 // destructor (can be at the end of the call)
2716 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002717
2718 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002719 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002720 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002721
Cliff Wud3a05312021-04-26 23:07:31 +08002722 {
2723 Mutex::Autolock lock(mInjectionParametersLock);
2724 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2725 mInjectionInitPending = false;
2726 status_t res = NO_ERROR;
2727 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2728 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002729 sp<BasicClient> clientSp = clientDescriptor->getValue();
2730 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2731 if(res != OK) {
2732 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2733 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002734 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002735 }
2736 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002737 if (res != OK) {
2738 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2739 }
2740 } else {
2741 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002742 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002743 res = NO_INIT;
2744 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2745 }
2746 }
2747 }
2748
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002749 return ret;
2750}
2751
Austin Borgered99f642023-06-01 16:51:35 -07002752status_t CameraService::addOfflineClient(const std::string &cameraId,
2753 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002754 if (offlineClient.get() == nullptr) {
2755 return BAD_VALUE;
2756 }
2757
2758 {
2759 // Acquire mServiceLock and prevent other clients from connecting
2760 std::unique_ptr<AutoConditionLock> lock =
2761 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2762
2763 if (lock == nullptr) {
2764 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2765 , __FUNCTION__, offlineClient->getClientPid());
2766 return TIMED_OUT;
2767 }
2768
2769 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2770 if (onlineClientDesc.get() == nullptr) {
2771 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2772 cameraId.c_str());
2773 return BAD_VALUE;
2774 }
2775
2776 // Offline clients do not evict or conflict with other online devices. Resource sharing
2777 // conflicts are handled by the camera provider which will either succeed or fail before
2778 // reaching this method.
2779 const auto& onlinePriority = onlineClientDesc->getPriority();
2780 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2781 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002782 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002783 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002784 // native clients don't have offline processing support.
2785 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002786 if (offlineClientDesc == nullptr) {
2787 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2788 return BAD_VALUE;
2789 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002790
2791 // Allow only one offline device per camera
2792 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2793 if (!incompatibleClients.empty()) {
2794 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2795 return BAD_VALUE;
2796 }
2797
Austin Borgered99f642023-06-01 16:51:35 -07002798 std::string monitorTags = isClientWatched(offlineClient.get())
2799 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002800 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002801 if (err != OK) {
2802 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2803 return err;
2804 }
2805
2806 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2807 if (evicted.size() > 0) {
2808 for (auto& i : evicted) {
2809 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002810 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002811 }
2812
2813 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2814 "properly", __FUNCTION__);
2815
2816 return BAD_VALUE;
2817 }
2818
2819 logConnectedOffline(offlineClientDesc->getKey(),
2820 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002821 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002822
2823 sp<IBinder> remoteCallback = offlineClient->getRemote();
2824 if (remoteCallback != nullptr) {
2825 remoteCallback->linkToDeath(this);
2826 }
2827 } // lock is destroyed, allow further connect calls
2828
2829 return OK;
2830}
2831
Austin Borgered99f642023-06-01 16:51:35 -07002832Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002833 int32_t torchStrength, const sp<IBinder>& clientBinder,
2834 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002835 Mutex::Autolock lock(mServiceLock);
2836
2837 ATRACE_CALL();
2838 if (clientBinder == nullptr) {
2839 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2840 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2841 "Torch client binder in null.");
2842 }
2843
Austin Borger22c5c852024-03-08 13:31:36 -08002844 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002845 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2846 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002847 if (!cameraIdOptional.has_value()) {
2848 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002849 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002850 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2851 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2852 }
2853 std::string cameraId = cameraIdOptional.value();
2854
Austin Borgered99f642023-06-01 16:51:35 -07002855 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002856 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002857 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002858 }
2859
2860 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002861 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002862 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002863 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002864 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002865 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002866 }
2867
2868 StatusInternal cameraStatus = state->getStatus();
2869 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2870 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002871 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002872 (int)cameraStatus);
2873 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002874 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002875 }
2876
2877 {
2878 Mutex::Autolock al(mTorchStatusMutex);
2879 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002880 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002881 if (err != OK) {
2882 if (err == NAME_NOT_FOUND) {
2883 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002884 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002885 }
2886 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002887 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002888 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2889 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002890 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002891 }
2892
2893 if (status == TorchModeStatus::NOT_AVAILABLE) {
2894 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2895 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002896 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002897 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2898 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002899 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002900 } else {
2901 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002902 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002903 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2904 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002905 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002906 }
2907 }
2908 }
2909
2910 {
2911 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002912 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002913 }
2914 // Check if the current torch strength level is same as the new one.
2915 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002916 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002917
Austin Borgered99f642023-06-01 16:51:35 -07002918 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002919
2920 if (err != OK) {
2921 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002922 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002923 switch (err) {
2924 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002925 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2926 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002927 errorCode = ERROR_ILLEGAL_ARGUMENT;
2928 break;
2929 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002930 msg = fmt::sprintf("Camera \"%s\" is in use",
2931 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002932 errorCode = ERROR_CAMERA_IN_USE;
2933 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002934 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002935 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002936 "valid range.", torchStrength);
2937 errorCode = ERROR_ILLEGAL_ARGUMENT;
2938 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002939 default:
Austin Borgered99f642023-06-01 16:51:35 -07002940 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002941 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002942 }
Austin Borgered99f642023-06-01 16:51:35 -07002943 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2944 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002945 }
2946
2947 {
2948 // update the link to client's death
2949 // Store the last client that turns on each camera's torch mode.
2950 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002951 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002952 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002953 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002954 } else {
2955 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2956 mTorchClientMap.replaceValueAt(index, clientBinder);
2957 }
2958 clientBinder->linkToDeath(this);
2959 }
2960
Austin Borger22c5c852024-03-08 13:31:36 -08002961 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002962 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002963 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002964 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002965 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002966 }
2967 return Status::ok();
2968}
2969
malikakash73125c62023-07-21 22:44:34 +00002970Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002971 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2972 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002973 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002974
2975 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002976 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002977 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002978 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2979 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002980 }
2981
Austin Borger22c5c852024-03-08 13:31:36 -08002982 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002983 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2984 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002985 if (!cameraIdOptional.has_value()) {
2986 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002987 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002988 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2989 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2990 }
2991 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002992
Austin Borgered99f642023-06-01 16:51:35 -07002993 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002994 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002995 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002996 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002997 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002998 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002999 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003000 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003001 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003002 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003003 }
3004
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003005 StatusInternal cameraStatus = state->getStatus();
3006 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003007 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003008 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3009 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003010 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003011 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003012 }
3013
3014 {
3015 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003016 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003017 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003018 if (err != OK) {
3019 if (err == NAME_NOT_FOUND) {
3020 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003021 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003022 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003023 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003024 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003025 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003026 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003027 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003028 }
3029
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003030 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003031 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003032 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003033 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3035 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003036 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003037 } else {
3038 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003039 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003040 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3041 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003042 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003043 }
3044 }
3045 }
3046
Ruben Brunk99e69712015-05-26 17:25:07 -07003047 {
3048 // Update UID map - this is used in the torch status changed callbacks, so must be done
3049 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003050 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003051 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003052 }
3053
Austin Borgered99f642023-06-01 16:51:35 -07003054 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003055
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003056 if (err != OK) {
3057 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003058 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003059 switch (err) {
3060 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003061 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3062 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003063 errorCode = ERROR_ILLEGAL_ARGUMENT;
3064 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003065 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003066 msg = fmt::sprintf("Camera \"%s\" is in use",
3067 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003068 errorCode = ERROR_CAMERA_IN_USE;
3069 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003070 default:
Austin Borgered99f642023-06-01 16:51:35 -07003071 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003072 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003073 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003074 errorCode = ERROR_INVALID_OPERATION;
3075 }
Austin Borgered99f642023-06-01 16:51:35 -07003076 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3077 logServiceError(msg, errorCode);
3078 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003079 }
3080
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003081 {
3082 // update the link to client's death
3083 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003084 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003085 if (enabled) {
3086 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003087 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003088 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003089 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003090 mTorchClientMap.replaceValueAt(index, clientBinder);
3091 }
3092 clientBinder->linkToDeath(this);
3093 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003094 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003095 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003096 }
3097
Austin Borger22c5c852024-03-08 13:31:36 -08003098 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003099 std::string torchState = enabled ? "on" : "off";
3100 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3101 torchState.c_str(), clientPid);
3102 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003103 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003104}
3105
Austin Borgered99f642023-06-01 16:51:35 -07003106void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3107 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3108 mTorchUidMap[cameraId].first = uid;
3109 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003110 } else {
3111 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003112 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003113 }
3114}
3115
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003116Status CameraService::notifySystemEvent(int32_t eventId,
3117 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003118 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003119 const int selfPid = getpid();
3120
3121 // Permission checks
3122 if (pid != selfPid) {
3123 // Ensure we're being called by system_server, or similar process with
3124 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003125 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003126 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003127 ALOGE("Permission Denial: cannot send updates to camera service about system"
3128 " events from pid=%d, uid=%d", pid, uid);
3129 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003130 "No permission to send updates to camera service about system events"
3131 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003132 }
3133 }
3134
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003135 ATRACE_CALL();
3136
Ruben Brunk36597b22015-03-20 22:15:57 -07003137 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003138 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003139 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003140 // from a system server crash
3141 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003142 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003143 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003144 break;
3145 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003146 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3147 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003148 if (args.size() != 1) {
3149 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3150 "USB Device Event requires 1 argument");
3151 }
3152
Valentin Iftime29e2e152021-08-13 15:17:33 +02003153 // Notify CameraProviderManager for lazy HALs
3154 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3155 std::to_string(args[0]));
3156 break;
3157 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003158 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003159 default: {
3160 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3161 eventId);
3162 break;
3163 }
3164 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003165 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003166}
3167
Emilian Peev53722fa2019-02-22 17:47:20 -08003168void CameraService::notifyMonitoredUids() {
3169 Mutex::Autolock lock(mStatusListenerLock);
3170
3171 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003172 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003173 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3174 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003175 }
3176}
3177
Austin Borgerdddb7552023-03-30 17:53:01 -07003178void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3179 Mutex::Autolock lock(mStatusListenerLock);
3180
3181 for (const auto& it : mListenerList) {
3182 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3183 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3184 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3185 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3186 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3187 }
3188 }
3189}
3190
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003191Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003192 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003193 const int selfPid = getpid();
3194
3195 // Permission checks
3196 if (pid != selfPid) {
3197 // Ensure we're being called by system_server, or similar process with
3198 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003199 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003200 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003201 ALOGE("Permission Denial: cannot send updates to camera service about device"
3202 " state changes from pid=%d, uid=%d", pid, uid);
3203 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3204 "No permission to send updates to camera service about device state"
3205 " changes from pid=%d, uid=%d", pid, uid);
3206 }
3207 }
3208
3209 ATRACE_CALL();
3210
Austin Borger18b30a72022-10-27 12:20:29 -07003211 {
3212 Mutex::Autolock lock(mServiceLock);
3213 mDeviceState = newState;
3214 }
3215
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003216 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003217
3218 return Status::ok();
3219}
3220
Emilian Peev8b64f282021-03-25 16:49:57 -07003221Status CameraService::notifyDisplayConfigurationChange() {
3222 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003223 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003224 const int selfPid = getpid();
3225
3226 // Permission checks
3227 if (callingPid != selfPid) {
3228 // Ensure we're being called by system_server, or similar process with
3229 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003230 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003231 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003232 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3233 " changes from pid=%d, uid=%d", callingPid, uid);
3234 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3235 "No permission to send updates to camera service about orientation"
3236 " changes from pid=%d, uid=%d", callingPid, uid);
3237 }
3238 }
3239
3240 Mutex::Autolock lock(mServiceLock);
3241
3242 // Don't do anything if rotate-and-crop override via cmd is active
3243 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3244
3245 const auto clients = mActiveClientManager.getAll();
3246 for (auto& current : clients) {
3247 if (current != nullptr) {
3248 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003249 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3250 basicClient->setRotateAndCropOverride(
3251 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3252 basicClient->getPackageName(),
3253 basicClient->getCameraFacing(),
3254 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003255 }
3256 }
3257 }
3258
3259 return Status::ok();
3260}
3261
3262Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003263 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3264 ATRACE_CALL();
3265 if (!concurrentCameraIds) {
3266 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3267 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3268 }
3269
3270 if (!mInitialized) {
3271 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003272 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003273 return STATUS_ERROR(ERROR_DISCONNECTED,
3274 "Camera subsystem is not available");
3275 }
3276 // First call into the provider and get the set of concurrent camera
3277 // combinations
3278 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003279 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003280 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003281 std::vector<std::pair<std::string, int32_t>> validCombination;
3282 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003283 for (auto &cameraId : combination) {
3284 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003285 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003286 if (state == nullptr) {
3287 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3288 continue;
3289 }
3290 StatusInternal status = state->getStatus();
3291 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3292 continue;
3293 }
Austin Borgered99f642023-06-01 16:51:35 -07003294 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003295 continue;
3296 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003297 auto [cameraOwnerDeviceId, mappedCameraId] =
3298 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3299 if (firstDeviceId == kInvalidDeviceId) {
3300 firstDeviceId = cameraOwnerDeviceId;
3301 } else if (firstDeviceId != cameraOwnerDeviceId) {
3302 // Found an invalid combination which contains cameras with different device id's,
3303 // hence discard it.
3304 validCombination.clear();
3305 break;
3306 }
3307 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003308 }
3309 if (validCombination.size() != 0) {
3310 concurrentCameraIds->push_back(std::move(validCombination));
3311 }
3312 }
3313 return Status::ok();
3314}
3315
3316Status CameraService::isConcurrentSessionConfigurationSupported(
3317 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003318 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003319 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003320 if (!isSupported) {
3321 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3322 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3323 }
3324
3325 if (!mInitialized) {
3326 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3327 return STATUS_ERROR(ERROR_DISCONNECTED,
3328 "Camera subsystem is not available");
3329 }
3330
Biswarup Pal7d072862024-04-17 15:24:47 +00003331 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3332 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003333 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3334 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003335 if (!cameraIdOptional.has_value()) {
3336 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003337 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003338 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3339 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3340 }
3341 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3342 }
3343
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003344 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003345 int callingPid = getCallingPid();
3346 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003347 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003348 hasPermissionsForCamera(callingPid, callingUid,
3349 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003350 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003351 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003352 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3353 "android.permission.CAMERA needed to call"
3354 "isConcurrentSessionConfigurationSupported");
3355 }
3356
3357 status_t res =
3358 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003359 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3360 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003361 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003362 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003363 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003364 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3365 "support %s (%d)", strerror(-res), res);
3366 }
3367 return Status::ok();
3368}
3369
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003370Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3371 /*out*/
3372 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003373 return addListenerHelper(listener, cameraStatuses);
3374}
3375
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003376binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3377 std::vector<hardware::CameraStatus>* cameraStatuses) {
3378 return addListenerHelper(listener, cameraStatuses, false, true);
3379}
3380
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003381Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3382 /*out*/
3383 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003384 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003385 ATRACE_CALL();
3386
Igor Murashkinbfc99152013-02-27 12:55:20 -08003387 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003388
Ruben Brunk3450ba72015-06-16 11:00:37 -07003389 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003390 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003391 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003392 }
3393
Austin Borger22c5c852024-03-08 13:31:36 -08003394 auto clientPid = getCallingPid();
3395 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003396 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003397
Igor Murashkinbfc99152013-02-27 12:55:20 -08003398 Mutex::Autolock lock(mServiceLock);
3399
Ruben Brunkcc776712015-02-17 20:18:47 -08003400 {
3401 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003402 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003403 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003404 ALOGW("%s: Tried to add listener %p which was already subscribed",
3405 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003406 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003407 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003408 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003409
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003410 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003411 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3412 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003413 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003414 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003415 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003416 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003417 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3418 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3419 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003420 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003421 // The listener still needs to be added to the list of listeners, regardless of what
3422 // permissions the listener process has / whether it is a vendor listener. Since it might be
3423 // eligible to listen to other camera ids.
3424 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003425 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003426 }
3427
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003428 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003429 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003430 Mutex::Autolock lock(mCameraStatesLock);
3431 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003432 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3433 auto [deviceId, mappedCameraId] =
3434 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3435
3436 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003437 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003438 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3439 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003440 }
3441 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003442 // Remove the camera statuses that should be hidden from the client, we do
3443 // this after collecting the states in order to avoid holding
3444 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3445 // the same time.
3446 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3447 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003448 std::string cameraId = s.cameraId;
3449 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003450 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003451 if (!cameraIdOptional.has_value()) {
3452 std::string msg =
3453 fmt::sprintf(
3454 "Camera %s: Invalid camera id for device id %d",
3455 s.cameraId.c_str(), s.deviceId);
3456 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3457 return true;
3458 }
3459 cameraId = cameraIdOptional.value();
3460 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3461 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3462 ALOGE("%s: Invalid camera id %s, skipping status update",
3463 __FUNCTION__, s.cameraId.c_str());
3464 return true;
3465 }
3466 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3467 clientUid);
3468 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003469
Biswarup Pal37a75182024-01-16 15:53:35 +00003470 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003471 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003472 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003473 // Add only default device cameras here, as virtual cameras currently don't support torch
3474 // anyway. Note that this is a simplification of the implementation here, and we should
3475 // change this when virtual cameras support torch.
3476 if (s.deviceId == kDefaultDeviceId) {
3477 idsChosenForCallback.insert(s.cameraId);
3478 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003479 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003480
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003481 /*
3482 * Immediately signal current torch status to this listener only
3483 * This may be a subset of all the devices, so don't include it in the response directly
3484 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003485 {
3486 Mutex::Autolock al(mTorchStatusMutex);
3487 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003488 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003489 // The camera id is visible to the client. Fine to send torch
3490 // callback.
3491 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003492 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3493 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003494 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003495 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003496 }
3497
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003498 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003499}
Ruben Brunkcc776712015-02-17 20:18:47 -08003500
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003501Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003502 ATRACE_CALL();
3503
Igor Murashkinbfc99152013-02-27 12:55:20 -08003504 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3505
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003506 if (listener == 0) {
3507 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003508 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003509 }
3510
Igor Murashkinbfc99152013-02-27 12:55:20 -08003511 Mutex::Autolock lock(mServiceLock);
3512
Ruben Brunkcc776712015-02-17 20:18:47 -08003513 {
3514 Mutex::Autolock lock(mStatusListenerLock);
3515 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003516 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003517 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003518 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003519 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003520 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003521 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003522 }
3523 }
3524
3525 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3526 __FUNCTION__, listener.get());
3527
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003528 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003529}
3530
Austin Borgered99f642023-06-01 16:51:35 -07003531Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003532
3533 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003534 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3535
3536 if (parameters == NULL) {
3537 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003538 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003539 }
3540
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003541 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003542
3543 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003544 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003545 // Error logged by caller
3546 return ret;
3547 }
3548
3549 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003550
Austin Borgered99f642023-06-01 16:51:35 -07003551 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003552
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003553 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003554}
3555
malikakash98260df2024-05-10 23:33:57 +00003556Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003557 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003558 ATRACE_CALL();
3559
Austin Borgered99f642023-06-01 16:51:35 -07003560 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003561
3562 switch (apiVersion) {
3563 case API_VERSION_1:
3564 case API_VERSION_2:
3565 break;
3566 default:
Austin Borgered99f642023-06-01 16:51:35 -07003567 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3568 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3569 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003570 }
3571
Austin Borger18b30a72022-10-27 12:20:29 -07003572 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003573 auto deviceVersionAndTransport =
3574 getDeviceVersion(cameraId,
3575 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3576 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003577 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003578 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3579 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3580 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003581 }
3582 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3583 int deviceVersion = deviceVersionAndTransport.first;
3584 switch (deviceVersion) {
3585 case CAMERA_DEVICE_API_VERSION_1_0:
3586 case CAMERA_DEVICE_API_VERSION_3_0:
3587 case CAMERA_DEVICE_API_VERSION_3_1:
3588 if (apiVersion == API_VERSION_2) {
3589 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003590 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003591 *isSupported = false;
3592 } else { // if (apiVersion == API_VERSION_1) {
3593 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003594 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003595 *isSupported = true;
3596 }
3597 break;
3598 case CAMERA_DEVICE_API_VERSION_3_2:
3599 case CAMERA_DEVICE_API_VERSION_3_3:
3600 case CAMERA_DEVICE_API_VERSION_3_4:
3601 case CAMERA_DEVICE_API_VERSION_3_5:
3602 case CAMERA_DEVICE_API_VERSION_3_6:
3603 case CAMERA_DEVICE_API_VERSION_3_7:
3604 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003605 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003606 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003607 break;
3608 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003609 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3610 deviceVersion, cameraId.c_str());
3611 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3612 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003613 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003614 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003615 } else {
3616 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003617 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003618 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003619}
3620
malikakash98260df2024-05-10 23:33:57 +00003621Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003622 /*out*/ bool *isSupported) {
3623 ATRACE_CALL();
3624
Austin Borgered99f642023-06-01 16:51:35 -07003625 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3626 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003627
3628 return Status::ok();
3629}
3630
Cliff Wud8cae102021-03-11 01:37:42 +08003631Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003632 const std::string& packageName, const std::string& internalCamId,
3633 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003634 const sp<ICameraInjectionCallback>& callback,
3635 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003636 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003637 ATRACE_CALL();
3638
Austin Borgered99f642023-06-01 16:51:35 -07003639 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003640 const int pid = getCallingPid();
3641 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003642 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3643 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003644 "Permission Denial: no permission to inject camera");
3645 }
3646
3647 // Do not allow any camera injection that injects or replaces a virtual camera.
3648 auto [deviceIdForInternalCamera, _] =
3649 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3650 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3651 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3652 "Cannot replace a virtual camera");
3653 }
3654 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3655 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3656 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3657 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3658 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003659 }
3660
3661 ALOGV(
3662 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3663 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003664 __FUNCTION__, packageName.c_str(),
3665 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003666
Cliff Wud3a05312021-04-26 23:07:31 +08003667 {
3668 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003669 mInjectionInternalCamId = internalCamId;
3670 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003671 mInjectionStatusListener->addListener(callback);
3672 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003673 status_t res = NO_ERROR;
3674 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3675 // If the client already exists, we can directly connect to the camera device through the
3676 // client's injectCamera(), otherwise we need to wait until the client is established
3677 // (execute connectHelper()) before injecting the camera to the camera device.
3678 if (clientDescriptor != nullptr) {
3679 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003680 sp<BasicClient> clientSp = clientDescriptor->getValue();
3681 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3682 if(res != OK) {
3683 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3684 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003685 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003686 }
3687 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003688 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003689 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3690 }
3691 } else {
3692 mInjectionInitPending = true;
3693 }
3694 }
Cliff Wud8cae102021-03-11 01:37:42 +08003695
Cliff Wud3a05312021-04-26 23:07:31 +08003696 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003697}
3698
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003699Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003700 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003701 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3702 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3703 return Status::ok();
3704}
3705
Ruben Brunkcc776712015-02-17 20:18:47 -08003706void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003707 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003708 for (auto& i : mActiveClientManager.getAll()) {
3709 auto clientSp = i->getValue();
3710 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003711 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003712 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003713 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003714 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003715 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003716}
3717
Ruben Brunkcc776712015-02-17 20:18:47 -08003718bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003719 bool ret = false;
3720 {
3721 // Acquire mServiceLock and prevent other clients from connecting
3722 std::unique_ptr<AutoConditionLock> lock =
3723 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003724
Ruben Brunkcc776712015-02-17 20:18:47 -08003725 std::vector<sp<BasicClient>> evicted;
3726 for (auto& i : mActiveClientManager.getAll()) {
3727 auto clientSp = i->getValue();
3728 if (clientSp.get() == nullptr) {
3729 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3730 mActiveClientManager.remove(i);
3731 continue;
3732 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003733 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003734 mActiveClientManager.remove(i);
3735 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003736
Ruben Brunkcc776712015-02-17 20:18:47 -08003737 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003738 clientSp->notifyError(
3739 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003740 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003741 }
3742 }
3743
Ruben Brunkcc776712015-02-17 20:18:47 -08003744 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3745 // other clients from connecting in mServiceLockWrapper if held
3746 mServiceLock.unlock();
3747
Ruben Brunk36597b22015-03-20 22:15:57 -07003748 // Do not clear caller identity, remote caller should be client proccess
3749
Ruben Brunkcc776712015-02-17 20:18:47 -08003750 for (auto& i : evicted) {
3751 if (i.get() != nullptr) {
3752 i->disconnect();
3753 ret = true;
3754 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003755 }
3756
Ruben Brunkcc776712015-02-17 20:18:47 -08003757 // Reacquire mServiceLock
3758 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003759
Ruben Brunkcc776712015-02-17 20:18:47 -08003760 } // lock is destroyed, allow further connect calls
3761
3762 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003763}
3764
Ruben Brunkcc776712015-02-17 20:18:47 -08003765std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003766 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003767 std::shared_ptr<CameraState> state;
3768 {
3769 Mutex::Autolock lock(mCameraStatesLock);
3770 auto iter = mCameraStates.find(cameraId);
3771 if (iter != mCameraStates.end()) {
3772 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003773 }
3774 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003775 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003776}
3777
Austin Borgered99f642023-06-01 16:51:35 -07003778sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003779 // Remove from active clients list
3780 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3781 if (clientDescriptorPtr == nullptr) {
3782 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003783 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003784 return sp<BasicClient>{nullptr};
3785 }
3786
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003787 sp<BasicClient> client = clientDescriptorPtr->getValue();
3788 if (client.get() != nullptr) {
3789 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3790 }
3791 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003792}
3793
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003794void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003795 // Acquire mServiceLock and prevent other clients from connecting
3796 std::unique_ptr<AutoConditionLock> lock =
3797 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3798
Ruben Brunk6267b532015-04-30 17:44:07 -07003799 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003800 for (size_t i = 0; i < newUserIds.size(); i++) {
3801 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003802 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003803 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003804 return;
3805 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003806 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003807 }
3808
Ruben Brunka8ca9152015-04-07 14:23:40 -07003809
Ruben Brunk6267b532015-04-30 17:44:07 -07003810 if (newAllowedUsers == mAllowedUsers) {
3811 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3812 return;
3813 }
3814
3815 logUserSwitch(mAllowedUsers, newAllowedUsers);
3816
3817 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003818
3819 // Current user has switched, evict all current clients.
3820 std::vector<sp<BasicClient>> evicted;
3821 for (auto& i : mActiveClientManager.getAll()) {
3822 auto clientSp = i->getValue();
3823
3824 if (clientSp.get() == nullptr) {
3825 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3826 continue;
3827 }
3828
Ruben Brunk6267b532015-04-30 17:44:07 -07003829 // Don't evict clients that are still allowed.
3830 uid_t clientUid = clientSp->getClientUid();
3831 userid_t clientUserId = multiuser_get_user_id(clientUid);
3832 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3833 continue;
3834 }
3835
Ruben Brunk36597b22015-03-20 22:15:57 -07003836 evicted.push_back(clientSp);
3837
Ruben Brunk36597b22015-03-20 22:15:57 -07003838 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003839 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003840
Ruben Brunk36597b22015-03-20 22:15:57 -07003841 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003842 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003843 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003844 " to user switch.", i->getKey().c_str(),
3845 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003846 i->getOwnerId(), i->getPriority().getScore(),
3847 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003848
3849 }
3850
3851 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3852 // blocking other clients from connecting in mServiceLockWrapper if held.
3853 mServiceLock.unlock();
3854
3855 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003856 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003857
3858 for (auto& i : evicted) {
3859 i->disconnect();
3860 }
3861
Austin Borger22c5c852024-03-08 13:31:36 -08003862 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003863
3864 // Reacquire mServiceLock
3865 mServiceLock.lock();
3866}
Ruben Brunkcc776712015-02-17 20:18:47 -08003867
Austin Borgered99f642023-06-01 16:51:35 -07003868void CameraService::logEvent(const std::string &event) {
3869 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003870 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003871 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003872 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003873 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003874 mEventLog.add(msg);
3875 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3876 // Error event not added to the dumpsys log before
3877 mEventLog.add(msg);
3878 sServiceErrorEventSet.insert(msg);
3879 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003880}
3881
Austin Borgered99f642023-06-01 16:51:35 -07003882void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3883 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003884 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003885 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3886 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003887}
3888
Austin Borgered99f642023-06-01 16:51:35 -07003889void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3890 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003891 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003892 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3893 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003894}
3895
Austin Borgered99f642023-06-01 16:51:35 -07003896void CameraService::logConnected(const std::string &cameraId, int clientPid,
3897 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003898 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003899 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3900 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003901}
3902
Austin Borgered99f642023-06-01 16:51:35 -07003903void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3904 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003905 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003906 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3907 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003908}
3909
Austin Borgered99f642023-06-01 16:51:35 -07003910void CameraService::logRejected(const std::string &cameraId, int clientPid,
3911 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003912 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003913 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3914 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003915}
3916
Austin Borgered99f642023-06-01 16:51:35 -07003917void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3918 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003919 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003920 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3921 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003922}
3923
Ruben Brunk6267b532015-04-30 17:44:07 -07003924void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3925 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003926 std::string newUsers = toString(newUserIds);
3927 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003928 if (oldUsers.size() == 0) {
3929 oldUsers = "<None>";
3930 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003931 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003932 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3933 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003934}
3935
Austin Borgered99f642023-06-01 16:51:35 -07003936void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003937 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003938 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003939}
3940
Austin Borgered99f642023-06-01 16:51:35 -07003941void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003942 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003943 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003944}
3945
Austin Borgered99f642023-06-01 16:51:35 -07003946void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003947 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003948 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003949}
3950
Austin Borgered99f642023-06-01 16:51:35 -07003951void CameraService::logServiceError(const std::string &msg, int errorCode) {
3952 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3953 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003954}
3955
Ruben Brunk36597b22015-03-20 22:15:57 -07003956status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3957 uint32_t flags) {
3958
Mathias Agopian65ab4712010-07-14 17:59:35 -07003959 // Permission checks
3960 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003961 case SHELL_COMMAND_TRANSACTION: {
3962 int in = data.readFileDescriptor();
3963 int out = data.readFileDescriptor();
3964 int err = data.readFileDescriptor();
3965 int argc = data.readInt32();
3966 Vector<String16> args;
3967 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3968 args.add(data.readString16());
3969 }
3970 sp<IBinder> unusedCallback;
3971 sp<IResultReceiver> resultReceiver;
3972 status_t status;
3973 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3974 return status;
3975 }
3976 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3977 return status;
3978 }
3979 status = shellCommand(in, out, err, args);
3980 if (resultReceiver != nullptr) {
3981 resultReceiver->send(status);
3982 }
3983 return NO_ERROR;
3984 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003985 }
3986
3987 return BnCameraService::onTransact(code, data, reply, flags);
3988}
3989
Mathias Agopian65ab4712010-07-14 17:59:35 -07003990// We share the media players for shutter and recording sound for all clients.
3991// A reference count is kept to determine when we will actually release the
3992// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003993sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3994 sp<MediaPlayer> mp = new MediaPlayer();
3995 status_t error;
3996 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003997 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003998 error = mp->prepare();
3999 }
4000 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004001 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004002 mp->disconnect();
4003 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004004 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004005 }
4006 return mp;
4007}
4008
username5755fea2018-12-27 09:48:08 +08004009void CameraService::increaseSoundRef() {
4010 Mutex::Autolock lock(mSoundLock);
4011 mSoundRef++;
4012}
4013
4014void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004015 ATRACE_CALL();
4016
username5755fea2018-12-27 09:48:08 +08004017 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4018 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4019 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4020 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4021 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4022 }
4023 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4024 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4025 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4026 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004027 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004028 }
4029 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4030 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4031 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4032 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4033 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004034 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004035}
4036
username5755fea2018-12-27 09:48:08 +08004037void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004039 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004040 if (--mSoundRef) return;
4041
4042 for (int i = 0; i < NUM_SOUNDS; i++) {
4043 if (mSoundPlayer[i] != 0) {
4044 mSoundPlayer[i]->disconnect();
4045 mSoundPlayer[i].clear();
4046 }
4047 }
4048}
4049
4050void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004051 ATRACE_CALL();
4052
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004054 if (kind < 0 || kind >= NUM_SOUNDS) {
4055 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4056 return;
4057 }
4058
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004060 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004061 sp<MediaPlayer> player = mSoundPlayer[kind];
4062 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004063 player->seekTo(0);
4064 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004065 }
4066}
4067
4068// ----------------------------------------------------------------------------
4069
4070CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004071 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004072 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004073 const std::string& clientPackageName, bool systemNativeClient,
4074 const std::optional<std::string>& clientFeatureId,
4075 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004076 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004077 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004078 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004079 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004080 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004081 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004082 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004083 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004084 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004085 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004086 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004087{
Austin Borger22c5c852024-03-08 13:31:36 -08004088 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004089 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004091 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092
username5755fea2018-12-27 09:48:08 +08004093 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004094
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004095 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004096}
4097
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098// tear down the client
4099CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004100 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004101 mDestructionStarted = true;
4102
username5755fea2018-12-27 09:48:08 +08004103 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004104 // unconditionally disconnect. function is idempotent
4105 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004106}
4107
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004108sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4109
Igor Murashkin634a5152013-02-20 17:15:11 -08004110CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004111 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004112 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004113 const std::string& clientPackageName, bool nativeClient,
4114 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004115 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004116 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004117 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004118 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004119 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004120 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4121 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004122 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004123 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004124 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004125 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004126 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004127 mRemoteBinder(remoteCallback),
4128 mOpsActive(false),
4129 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004130{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004131 if (sCameraService == nullptr) {
4132 sCameraService = cameraService;
4133 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004134
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004135 // There are 2 scenarios in which a client won't have AppOps operations
4136 // (both scenarios : native clients)
4137 // 1) It's an system native client*, the package name will be empty
4138 // and it will return from this function in the previous if condition
4139 // (This is the same as the previously existing behavior).
4140 // 2) It is a system native client, but its package name has been
4141 // modified for debugging, however it still must not use AppOps since
4142 // the package name is not a real one.
4143 //
4144 // * system native client - native client with UID < AID_APP_START. It
4145 // doesn't exclude clients not on the system partition.
4146 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004147 mAppOpsManager = std::make_unique<AppOpsManager>();
4148 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004149
Charles Chenf075f082024-03-04 23:32:55 +00004150 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004151}
4152
4153CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004154 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004155 mDestructionStarted = true;
4156}
4157
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004158binder::Status CameraService::BasicClient::disconnect() {
4159 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004160 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004161 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004162 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004163 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004164
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004165 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004166 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004167 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004168 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004169
4170 sp<IBinder> remote = getRemote();
4171 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004172 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004173 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004174
4175 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004176 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004177 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004178 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004179 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004180
Igor Murashkincba2c162013-03-20 15:56:31 -07004181 // client shouldn't be able to call into us anymore
4182 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004183
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004184 const auto& mActivityManager = getActivityManager();
4185 if (mActivityManager) {
4186 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004187 getCallingUid(),
4188 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004189 }
4190
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004191 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004192}
4193
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004194status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4195 // No dumping of clients directly over Binder,
4196 // must go through CameraService::dump
4197 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004198 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004199 return OK;
4200}
4201
Austin Borgered99f642023-06-01 16:51:35 -07004202status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004203 // Can't watch tags directly, must go through CameraService::startWatchingTags
4204 return OK;
4205}
4206
4207status_t CameraService::BasicClient::stopWatchingTags(int) {
4208 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4209 return OK;
4210}
4211
4212status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4213 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4214 return OK;
4215}
4216
Austin Borgered99f642023-06-01 16:51:35 -07004217std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004218 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004219}
4220
Emilian Peev8b64f282021-03-25 16:49:57 -07004221int CameraService::BasicClient::getCameraFacing() const {
4222 return mCameraFacing;
4223}
4224
4225int CameraService::BasicClient::getCameraOrientation() const {
4226 return mOrientation;
4227}
Ruben Brunkcc776712015-02-17 20:18:47 -08004228
4229int CameraService::BasicClient::getClientPid() const {
4230 return mClientPid;
4231}
4232
Ruben Brunk6267b532015-04-30 17:44:07 -07004233uid_t CameraService::BasicClient::getClientUid() const {
4234 return mClientUid;
4235}
4236
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004237bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4238 // Defaults to API2.
4239 return level == API_2;
4240}
4241
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004242status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004243 {
4244 Mutex::Autolock l(mAudioRestrictionLock);
4245 mAudioRestriction = mode;
4246 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004247 sCameraService->updateAudioRestriction();
4248 return OK;
4249}
4250
4251int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004252 return sCameraService->updateAudioRestriction();
4253}
4254
4255int32_t CameraService::BasicClient::getAudioRestriction() const {
4256 Mutex::Autolock l(mAudioRestrictionLock);
4257 return mAudioRestriction;
4258}
4259
4260bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4261 switch (mode) {
4262 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4263 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4264 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4265 return true;
4266 default:
4267 return false;
4268 }
4269}
4270
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004271status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4272 if (mode == AppOpsManager::MODE_ERRORED) {
4273 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004274 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004275 return PERMISSION_DENIED;
4276 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4277 // If the calling Uid is trusted (a native service), the AppOpsManager could
4278 // return MODE_IGNORED. Do not treat such case as error.
4279 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4280 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004281
4282 bool isCameraPrivacyEnabled;
4283 if (flags::camera_privacy_allowlist()) {
4284 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4285 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4286 } else {
4287 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004288 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004289 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004290 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4291 // We prefer to successfully open the camera and perform camera muting
4292 // or blocking in connectHelper as handleAppOpMode can be called before the
4293 // connection has been fully established and at that time camera muting
4294 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004295 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004296 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4297 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4298 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4299 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004300 // Return the same error as for device policy manager rejection
4301 return -EACCES;
4302 }
4303 }
4304 return OK;
4305}
4306
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004307status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004308 ATRACE_CALL();
4309
Igor Murashkine6800ce2013-03-04 17:25:57 -08004310 {
4311 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004312 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004313 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004314 if (mAppOpsManager != nullptr) {
4315 // Notify app ops that the camera is not available
4316 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004317
4318 if (flags::watch_foreground_changes()) {
4319 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4320 toString16(mClientPackageName),
4321 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4322 } else {
4323 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004324 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004325 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004326
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004327 // Just check for camera acccess here on open - delay startOp until
4328 // camera frames start streaming in startCameraStreamingOps
4329 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004330 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004331 status_t res = handleAppOpMode(mode);
4332 if (res != OK) {
4333 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004334 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004335 }
4336
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004337 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004338
4339 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004340 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004341
Austin Borgerdddb7552023-03-30 17:53:01 -07004342 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004343
Shuzhen Wang695044d2020-03-06 09:02:23 -08004344 // Notify listeners of camera open/close status
4345 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4346
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004347 return OK;
4348}
4349
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004350status_t CameraService::BasicClient::startCameraStreamingOps() {
4351 ATRACE_CALL();
4352
4353 if (!mOpsActive) {
4354 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4355 return INVALID_OPERATION;
4356 }
4357 if (mOpsStreaming) {
4358 ALOGV("%s: Streaming already active!", __FUNCTION__);
4359 return OK;
4360 }
4361
4362 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004363 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004364
4365 if (mAppOpsManager != nullptr) {
4366 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004367 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4368 toString16(mClientFeatureId),
4369 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004370 status_t res = handleAppOpMode(mode);
4371 if (res != OK) {
4372 return res;
4373 }
4374 }
4375
4376 mOpsStreaming = true;
4377
4378 return OK;
4379}
4380
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004381status_t CameraService::BasicClient::noteAppOp() {
4382 ATRACE_CALL();
4383
4384 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004385 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004386
4387 // noteAppOp is only used for when camera mute is not supported, in order
4388 // to trigger the sensor privacy "Unblock" dialog
4389 if (mAppOpsManager != nullptr) {
4390 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004391 toString16(mClientPackageName), toString16(mClientFeatureId),
4392 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004393 status_t res = handleAppOpMode(mode);
4394 if (res != OK) {
4395 return res;
4396 }
4397 }
4398
4399 return OK;
4400}
4401
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004402status_t CameraService::BasicClient::finishCameraStreamingOps() {
4403 ATRACE_CALL();
4404
4405 if (!mOpsActive) {
4406 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4407 return INVALID_OPERATION;
4408 }
4409 if (!mOpsStreaming) {
4410 ALOGV("%s: Streaming not active!", __FUNCTION__);
4411 return OK;
4412 }
4413
4414 if (mAppOpsManager != nullptr) {
4415 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004416 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004417 mOpsStreaming = false;
4418 }
4419
4420 return OK;
4421}
4422
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004423status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004424 ATRACE_CALL();
4425
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004426 if (mOpsStreaming) {
4427 // Make sure we've notified everyone about camera stopping
4428 finishCameraStreamingOps();
4429 }
4430
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004431 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004432 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004433 mOpsActive = false;
4434
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004435 // This function is called when a client disconnects. This should
4436 // release the camera, but actually only if it was in a proper
4437 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004438 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004439 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004440
Ruben Brunkcc776712015-02-17 20:18:47 -08004441 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004442 sCameraService->updateStatus(StatusInternal::PRESENT,
4443 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004444 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004445 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004446 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4447 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004448 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004449 mOpsCallback.clear();
4450
Austin Borgerdddb7552023-03-30 17:53:01 -07004451 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004452
Shuzhen Wang695044d2020-03-06 09:02:23 -08004453 // Notify listeners of camera open/close status
4454 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4455
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004456 return OK;
4457}
4458
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004459void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004460 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004461 if (mAppOpsManager == nullptr) {
4462 return;
4463 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004464 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004465 if (op != AppOpsManager::OP_CAMERA) {
4466 ALOGW("Unexpected app ops notification received: %d", op);
4467 return;
4468 }
4469
4470 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004471 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004472 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004473 ALOGV("checkOp returns: %d, %s ", res,
4474 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4475 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4476 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4477 "UNKNOWN");
4478
Shuzhen Wang64900852021-02-05 09:03:29 -08004479 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004480 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4481 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004482 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004483 } else if (res == AppOpsManager::MODE_IGNORED) {
4484 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004485
Austin Borgerca1e0062023-06-28 11:32:55 -07004486 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4487 // If not visible, but still active, then we want to block instead of muting the camera.
4488 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4489 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4490
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004491 bool isCameraPrivacyEnabled;
4492 if (flags::camera_privacy_allowlist()) {
4493 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4494 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4495 } else {
4496 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004497 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004498 }
4499
4500 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004501 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4502 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4503 isCameraPrivacyEnabled);
4504 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4505 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4506 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004507 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004508 if (flags::watch_foreground_changes()) {
4509 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4510 setCameraMute(true);
4511 } else {
4512 block();
4513 }
4514 } else {
4515 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4516 setCameraMute(true);
4517 } else if (!isUidActive
4518 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4519 block();
4520 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004521 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004522 }
Evan Severson09ab4002021-02-10 14:15:19 -08004523 } else if (res == AppOpsManager::MODE_ALLOWED) {
4524 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004525 }
4526}
4527
Svet Ganova453d0d2018-01-11 15:37:58 -08004528void CameraService::BasicClient::block() {
4529 ATRACE_CALL();
4530
4531 // Reset the client PID to allow server-initiated disconnect,
4532 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004533 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004534 CaptureResultExtras resultExtras; // a dummy result (invalid)
4535 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4536 disconnect();
4537}
4538
Mathias Agopian65ab4712010-07-14 17:59:35 -07004539// ----------------------------------------------------------------------------
4540
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004541void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004542 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004543 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004544 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4545 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4546 api1ErrorCode = CAMERA_ERROR_DISABLED;
4547 }
4548 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004549 } else {
4550 ALOGE("mRemoteCallback is NULL!!");
4551 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004552}
4553
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004554// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004555binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004556 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004557 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004558}
4559
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004560bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4561 return level == API_1;
4562}
4563
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004564CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4565 mClient(client) {
4566}
4567
4568void CameraService::Client::OpsCallback::opChanged(int32_t op,
4569 const String16& packageName) {
4570 sp<BasicClient> client = mClient.promote();
4571 if (client != NULL) {
4572 client->opChanged(op, packageName);
4573 }
4574}
4575
Mathias Agopian65ab4712010-07-14 17:59:35 -07004576// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004577// UidPolicy
4578// ----------------------------------------------------------------------------
4579
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004580void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004581 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004582 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004583
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004584 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004585 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004586 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004587 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004588 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4589 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004590 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004591 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004592 if (res == OK) {
4593 mRegistered = true;
4594 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004595 } else {
4596 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004597 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004598}
4599
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004600void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004601 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004602 return;
4603 }
4604
4605 registerWithActivityManager();
4606}
4607
4608void CameraService::UidPolicy::registerSelf() {
4609 // Use check service to see if the activity service is available
4610 // If not available then register for notifications, instead of blocking
4611 // till the service is ready
4612 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004613 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004614 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004615 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004616 } else {
4617 registerWithActivityManager();
4618 }
4619}
4620
Svet Ganova453d0d2018-01-11 15:37:58 -08004621void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004622 Mutex::Autolock _l(mUidLock);
4623
Steven Moreland2f348142019-07-02 15:59:07 -07004624 mAm.unregisterUidObserver(this);
4625 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004626 mRegistered = false;
4627 mActiveUids.clear();
4628 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004629}
4630
4631void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4632 onUidIdle(uid, disabled);
4633}
4634
4635void CameraService::UidPolicy::onUidActive(uid_t uid) {
4636 Mutex::Autolock _l(mUidLock);
4637 mActiveUids.insert(uid);
4638}
4639
4640void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4641 bool deleted = false;
4642 {
4643 Mutex::Autolock _l(mUidLock);
4644 if (mActiveUids.erase(uid) > 0) {
4645 deleted = true;
4646 }
4647 }
4648 if (deleted) {
4649 sp<CameraService> service = mService.promote();
4650 if (service != nullptr) {
4651 service->blockClientsForUid(uid);
4652 }
4653 }
4654}
4655
Emilian Peev53722fa2019-02-22 17:47:20 -08004656void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004657 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004658 bool procStateChange = false;
4659 {
4660 Mutex::Autolock _l(mUidLock);
4661 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4662 mMonitoredUids[uid].procState != procState) {
4663 mMonitoredUids[uid].procState = procState;
4664 procStateChange = true;
4665 }
4666 }
4667
4668 if (procStateChange) {
4669 sp<CameraService> service = mService.promote();
4670 if (service != nullptr) {
4671 service->notifyMonitoredUids();
4672 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004673 }
4674}
4675
Austin Borgerdddb7552023-03-30 17:53:01 -07004676/**
4677 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4678 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4679 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4680 * monitoredUids. If it is revised above some other monitoredUid, signal
4681 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4682 * foreground apps in split screen - state changes will capture all other cases.
4683 */
4684void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4685 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004686 {
4687 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004688 auto it = mMonitoredUids.find(uid);
4689
4690 if (it != mMonitoredUids.end()) {
4691 if (it->second.hasCamera) {
4692 for (auto &monitoredUid : mMonitoredUids) {
4693 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004694 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004695 notifyUidSet.emplace(monitoredUid.first);
4696 }
4697 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004698 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004699 notifyUidSet.emplace(uid);
4700 } else {
4701 for (auto &monitoredUid : mMonitoredUids) {
4702 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004703 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004704 notifyUidSet.emplace(uid);
4705 }
4706 }
4707 }
4708 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004709 }
4710 }
4711
Austin Borgerdddb7552023-03-30 17:53:01 -07004712 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004713 sp<CameraService> service = mService.promote();
4714 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004715 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004716 }
4717 }
4718}
4719
Austin Borgerdddb7552023-03-30 17:53:01 -07004720/**
4721 * Register a uid for monitoring, and note whether it owns a camera.
4722 */
4723void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004724 Mutex::Autolock _l(mUidLock);
4725 auto it = mMonitoredUids.find(uid);
4726 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004727 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004728 } else {
Austin Borger65577682022-02-17 00:25:43 +00004729 MonitoredUid monitoredUid;
4730 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004731 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004732 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004733 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004734 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004735 if (res != OK) {
4736 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4737 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004738 }
4739
4740 if (openCamera) {
4741 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004742 }
4743}
4744
Austin Borgerdddb7552023-03-30 17:53:01 -07004745/**
4746 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4747 */
4748void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004749 Mutex::Autolock _l(mUidLock);
4750 auto it = mMonitoredUids.find(uid);
4751 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004752 it->second.refCount--;
4753 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004754 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004755 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004756 if (res != OK) {
4757 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4758 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004759 } else if (closeCamera) {
4760 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004761 }
4762 } else {
4763 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4764 }
4765}
4766
Austin Borgered99f642023-06-01 16:51:35 -07004767bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004768 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004769 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004770}
4771
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004772static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4773static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004774
Austin Borgered99f642023-06-01 16:51:35 -07004775bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004776 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004777 // If activity manager is unreachable, assume everything is active
4778 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004779 return true;
4780 }
4781 auto it = mOverrideUids.find(uid);
4782 if (it != mOverrideUids.end()) {
4783 return it->second;
4784 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004785 bool active = mActiveUids.find(uid) != mActiveUids.end();
4786 if (!active) {
4787 // We want active UIDs to always access camera with their first attempt since
4788 // there is no guarantee the app is robustly written and would retry getting
4789 // the camera on failure. The inverse case is not a problem as we would take
4790 // camera away soon once we get the callback that the uid is no longer active.
4791 ActivityManager am;
4792 // Okay to access with a lock held as UID changes are dispatched without
4793 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004794 int64_t startTimeMillis = 0;
4795 do {
4796 // TODO: Fix this b/109950150!
4797 // Okay this is a hack. There is a race between the UID turning active and
4798 // activity being resumed. The proper fix is very risky, so we temporary add
4799 // some polling which should happen pretty rarely anyway as the race is hard
4800 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004801 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004802 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004803 if (active) {
4804 break;
4805 }
4806 if (startTimeMillis <= 0) {
4807 startTimeMillis = uptimeMillis();
4808 }
4809 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004810 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004811 if (remainingTimeMillis <= 0) {
4812 break;
4813 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004814 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4815
4816 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004817 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004818 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004819 } while (true);
4820
Svet Ganov7b4ab782018-03-25 12:48:10 -07004821 if (active) {
4822 // Now that we found out the UID is actually active, cache that
4823 mActiveUids.insert(uid);
4824 }
4825 }
4826 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004827}
4828
Varun Shahb42f1eb2019-04-16 14:45:13 -07004829int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4830 Mutex::Autolock _l(mUidLock);
4831 return getProcStateLocked(uid);
4832}
4833
4834int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4835 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4836 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004837 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004838 }
4839 return procState;
4840}
4841
Austin Borgered99f642023-06-01 16:51:35 -07004842void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4843 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004844 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004845}
4846
Austin Borgered99f642023-06-01 16:51:35 -07004847void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004848 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004849}
4850
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004851void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4852 Mutex::Autolock _l(mUidLock);
4853 ALOGV("UidPolicy: ActivityManager has died");
4854 mRegistered = false;
4855 mActiveUids.clear();
4856}
4857
Austin Borgered99f642023-06-01 16:51:35 -07004858void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004859 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004860 bool wasActive = false;
4861 bool isActive = false;
4862 {
4863 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004864 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004865 mOverrideUids.erase(uid);
4866 if (insert) {
4867 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4868 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004869 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004870 }
4871 if (wasActive != isActive && !isActive) {
4872 sp<CameraService> service = mService.promote();
4873 if (service != nullptr) {
4874 service->blockClientsForUid(uid);
4875 }
4876 }
4877}
4878
4879// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004880// SensorPrivacyPolicy
4881// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004882
4883void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4884{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004885 Mutex::Autolock _l(mSensorPrivacyLock);
4886 if (mRegistered) {
4887 return;
4888 }
Evan Severson09ab4002021-02-10 14:15:19 -08004889 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004890 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004891 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004892 mSpm.addToggleSensorPrivacyListener(this);
4893 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004894 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004895 if (flags::camera_privacy_allowlist()) {
4896 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4897 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4898 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4899 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004900 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004901 if (res == OK) {
4902 mRegistered = true;
4903 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4904 }
4905}
4906
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004907void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4908 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004909 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004910 return;
4911 }
4912
4913 registerWithSensorPrivacyManager();
4914}
4915
4916void CameraService::SensorPrivacyPolicy::registerSelf() {
4917 // Use checkservice to see if the sensor_privacy service is available
4918 // If service is not available then register for notification
4919 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004920 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004921 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004922 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004923 } else {
4924 registerWithSensorPrivacyManager();
4925 }
4926}
4927
Michael Grooverd1d435a2018-12-18 17:39:42 -08004928void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4929 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004930 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004931 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004932 mSpm.removeToggleSensorPrivacyListener(this);
4933 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004934 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004935 mRegistered = false;
4936 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4937}
4938
4939bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004940 if (!mRegistered) {
4941 registerWithSensorPrivacyManager();
4942 }
4943
Michael Grooverd1d435a2018-12-18 17:39:42 -08004944 Mutex::Autolock _l(mSensorPrivacyLock);
4945 return mSensorPrivacyEnabled;
4946}
4947
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004948int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4949 if (!mRegistered) {
4950 registerWithSensorPrivacyManager();
4951 }
4952
4953 Mutex::Autolock _l(mSensorPrivacyLock);
4954 return mCameraPrivacyState;
4955}
4956
Evan Seversond0b69922022-01-27 10:47:34 -08004957bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004958 if (!hasCameraPrivacyFeature()) {
4959 return false;
4960 }
Evan Seversond0b69922022-01-27 10:47:34 -08004961 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004962}
4963
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004964bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4965 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004966 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004967 }
4968 return mSpm.isCameraPrivacyEnabled(packageName);
4969}
4970
Evan Seversond0b69922022-01-27 10:47:34 -08004971binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004972 int toggleType, int sensor, bool enabled) {
4973 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4974 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4975 {
4976 Mutex::Autolock _l(mSensorPrivacyLock);
4977 mSensorPrivacyEnabled = enabled;
4978 }
4979 // if sensor privacy is enabled then block all clients from accessing the camera
4980 if (enabled) {
4981 sp<CameraService> service = mService.promote();
4982 if (service != nullptr) {
4983 service->blockAllClients();
4984 }
4985 }
4986 }
4987 return binder::Status::ok();
4988}
4989
4990binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4991 int, int sensor, int state) {
4992 if (!flags::camera_privacy_allowlist()
4993 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4994 return binder::Status::ok();
4995 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004996 {
4997 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004998 mCameraPrivacyState = state;
4999 }
5000 sp<CameraService> service = mService.promote();
5001 if (!service) {
5002 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005003 }
5004 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005005 if (state == SensorPrivacyManager::ENABLED) {
5006 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005007 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005008 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005009 }
5010 return binder::Status::ok();
5011}
5012
5013void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5014 Mutex::Autolock _l(mSensorPrivacyLock);
5015 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5016 mRegistered = false;
5017}
5018
Evan Severson09ab4002021-02-10 14:15:19 -08005019bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005020 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5021 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5022 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5023 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5024 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005025}
5026
Michael Grooverd1d435a2018-12-18 17:39:42 -08005027// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005028// CameraState
5029// ----------------------------------------------------------------------------
5030
Austin Borgered99f642023-06-01 16:51:35 -07005031CameraService::CameraState::CameraState(const std::string& id, int cost,
5032 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005033 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005034 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005035 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005036
5037CameraService::CameraState::~CameraState() {}
5038
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005039CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005040 Mutex::Autolock lock(mStatusLock);
5041 return mStatus;
5042}
5043
Austin Borgered99f642023-06-01 16:51:35 -07005044std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005045 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005046 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005047 return res;
5048}
5049
Ruben Brunkcc776712015-02-17 20:18:47 -08005050CameraParameters CameraService::CameraState::getShimParams() const {
5051 return mShimParams;
5052}
5053
5054void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5055 mShimParams = params;
5056}
5057
5058int CameraService::CameraState::getCost() const {
5059 return mCost;
5060}
5061
Austin Borgered99f642023-06-01 16:51:35 -07005062std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005063 return mConflicting;
5064}
5065
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005066SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5067 return mSystemCameraKind;
5068}
5069
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005070bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5071 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5072 != mPhysicalCameras.end();
5073}
5074
Austin Borgered99f642023-06-01 16:51:35 -07005075bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005076 Mutex::Autolock lock(mStatusLock);
5077 auto result = mUnavailablePhysicalIds.insert(physicalId);
5078 return result.second;
5079}
5080
Austin Borgered99f642023-06-01 16:51:35 -07005081bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005082 Mutex::Autolock lock(mStatusLock);
5083 auto count = mUnavailablePhysicalIds.erase(physicalId);
5084 return count > 0;
5085}
5086
Austin Borgered99f642023-06-01 16:51:35 -07005087void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005088 Mutex::Autolock lock(mStatusLock);
5089 mClientPackage = clientPackage;
5090}
5091
Austin Borgered99f642023-06-01 16:51:35 -07005092std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005093 Mutex::Autolock lock(mStatusLock);
5094 return mClientPackage;
5095}
5096
Ruben Brunkcc776712015-02-17 20:18:47 -08005097// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005098// ClientEventListener
5099// ----------------------------------------------------------------------------
5100
5101void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005102 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005103 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005104 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005105 if (basicClient.get() != nullptr) {
5106 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005107 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005108 static_cast<int>(basicClient->getClientUid()));
5109 }
5110}
5111
5112void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005113 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005114 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005115 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005116 if (basicClient.get() != nullptr) {
5117 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005118 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005119 static_cast<int>(basicClient->getClientUid()));
5120 }
5121}
5122
Ruben Brunk99e69712015-05-26 17:25:07 -07005123// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005124// CameraClientManager
5125// ----------------------------------------------------------------------------
5126
Ruben Brunk99e69712015-05-26 17:25:07 -07005127CameraService::CameraClientManager::CameraClientManager() {
5128 setListener(std::make_shared<ClientEventListener>());
5129}
5130
Ruben Brunkcc776712015-02-17 20:18:47 -08005131CameraService::CameraClientManager::~CameraClientManager() {}
5132
5133sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005134 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005135 auto descriptor = get(id);
5136 if (descriptor == nullptr) {
5137 return sp<BasicClient>{nullptr};
5138 }
5139 return descriptor->getValue();
5140}
5141
Austin Borgered99f642023-06-01 16:51:35 -07005142std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005143 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005144 std::ostringstream ret;
5145 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005146 bool hasAny = false;
5147 for (auto& i : all) {
5148 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005149 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005150 int32_t cost = i->getCost();
5151 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005152 int32_t score = i->getPriority().getScore();
5153 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005154 auto conflicting = i->getConflicting();
5155 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005156 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005157 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005158 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005159 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005160 uid_t clientUid = clientSp->getClientUid();
5161 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005162 }
Austin Borgered99f642023-06-01 16:51:35 -07005163 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5164 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005165
Ruben Brunk6267b532015-04-30 17:44:07 -07005166 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005167 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005168 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005169 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005170 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005171 }
5172
Austin Borgered99f642023-06-01 16:51:35 -07005173 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005174 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005175 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005176 }
Austin Borgered99f642023-06-01 16:51:35 -07005177 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005178 }
Austin Borgered99f642023-06-01 16:51:35 -07005179 if (hasAny) ret << "\n";
5180 ret << "]\n";
5181 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005182}
5183
5184CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005185 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5186 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005187 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005188
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005189 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005190 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005191
Austin Borgered99f642023-06-01 16:51:35 -07005192 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005193 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5194 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005195}
5196
5197CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005198 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005199 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005200 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005201 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005202 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5203 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005204}
5205
5206// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005207// InjectionStatusListener
5208// ----------------------------------------------------------------------------
5209
5210void CameraService::InjectionStatusListener::addListener(
5211 const sp<ICameraInjectionCallback>& callback) {
5212 Mutex::Autolock lock(mListenerLock);
5213 if (mCameraInjectionCallback) return;
5214 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5215 if (res == OK) {
5216 mCameraInjectionCallback = callback;
5217 }
5218}
5219
5220void CameraService::InjectionStatusListener::removeListener() {
5221 Mutex::Autolock lock(mListenerLock);
5222 if (mCameraInjectionCallback == nullptr) {
5223 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5224 return;
5225 }
5226 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5227 mCameraInjectionCallback = nullptr;
5228}
5229
5230void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005231 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005232 if (mCameraInjectionCallback == nullptr) {
5233 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5234 return;
5235 }
Cliff Wud3a05312021-04-26 23:07:31 +08005236
5237 switch (err) {
5238 case -ENODEV:
5239 mCameraInjectionCallback->onInjectionError(
5240 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5241 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005242 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005243 break;
5244 case -EBUSY:
5245 mCameraInjectionCallback->onInjectionError(
5246 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5247 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005248 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005249 break;
5250 case DEAD_OBJECT:
5251 mCameraInjectionCallback->onInjectionError(
5252 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5253 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005254 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005255 break;
5256 case INVALID_OPERATION:
5257 mCameraInjectionCallback->onInjectionError(
5258 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5259 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005260 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005261 break;
5262 case UNKNOWN_TRANSACTION:
5263 mCameraInjectionCallback->onInjectionError(
5264 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5265 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005266 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005267 break;
5268 default:
5269 mCameraInjectionCallback->onInjectionError(
5270 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5271 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005272 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005273 }
Cliff Wud8cae102021-03-11 01:37:42 +08005274}
5275
5276void CameraService::InjectionStatusListener::binderDied(
5277 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005278 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5279 auto parent = mParent.promote();
5280 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005281 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5282 if (clientDescriptor != nullptr) {
5283 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5284 baseClientPtr->stopInjection();
5285 }
Cliff Wu3b268182021-07-06 15:44:43 +08005286 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005287 }
5288}
5289
5290// ----------------------------------------------------------------------------
5291// CameraInjectionSession
5292// ----------------------------------------------------------------------------
5293
5294binder::Status CameraService::CameraInjectionSession::stopInjection() {
5295 Mutex::Autolock lock(mInjectionSessionLock);
5296 auto parent = mParent.promote();
5297 if (parent == nullptr) {
5298 ALOGE("CameraInjectionSession: Parent is gone");
5299 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5300 "Camera service encountered error");
5301 }
Cliff Wud3a05312021-04-26 23:07:31 +08005302
5303 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005304 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5305 if (clientDescriptor != nullptr) {
5306 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5307 res = baseClientPtr->stopInjection();
5308 if (res != OK) {
5309 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5310 " ret != NO_ERROR: %d", res);
5311 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5312 "Camera session encountered error");
5313 }
5314 }
Cliff Wu3b268182021-07-06 15:44:43 +08005315 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005316 return binder::Status::ok();
5317}
5318
5319// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005320
5321static const int kDumpLockRetries = 50;
5322static const int kDumpLockSleep = 60000;
5323
5324static bool tryLock(Mutex& mutex)
5325{
5326 bool locked = false;
5327 for (int i = 0; i < kDumpLockRetries; ++i) {
5328 if (mutex.tryLock() == NO_ERROR) {
5329 locked = true;
5330 break;
5331 }
5332 usleep(kDumpLockSleep);
5333 }
5334 return locked;
5335}
5336
Rucha Katakwardf223072021-06-15 10:21:00 -07005337void CameraService::cacheDump() {
5338 if (mMemFd != -1) {
5339 const Vector<String16> args;
5340 ATRACE_CALL();
5341 // Acquiring service lock here will avoid the deadlock since
5342 // cacheDump will not be called during the second disconnect.
5343 Mutex::Autolock lock(mServiceLock);
5344
5345 Mutex::Autolock l(mCameraStatesLock);
5346 // Start collecting the info for open sessions and store it in temp file.
5347 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005348 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005349 auto clientDescriptor = mActiveClientManager.get(cameraId);
5350 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005351 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005352 // Log the current open session info before device is disconnected.
5353 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5354 }
5355 }
5356 }
5357}
5358
Mathias Agopian65ab4712010-07-14 17:59:35 -07005359status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005360 ATRACE_CALL();
5361
Austin Borgered99f642023-06-01 16:51:35 -07005362 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005363 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005364 getCallingPid(),
5365 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005366 return NO_ERROR;
5367 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005368 bool locked = tryLock(mServiceLock);
5369 // failed to lock - CameraService is probably deadlocked
5370 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005371 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005372 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005373
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005374 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005375 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005376
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005377 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005378 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005379
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005380 if (locked) mServiceLock.unlock();
5381 return NO_ERROR;
5382 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005383 dprintf(fd, "\n== Service global info: ==\n\n");
5384 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005385 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005386 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5387 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005388 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5389 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5390 }
Austin Borgered99f642023-06-01 16:51:35 -07005391 std::string activeClientString = mActiveClientManager.toString();
5392 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5393 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005394 if (mStreamUseCaseOverrides.size() > 0) {
5395 dprintf(fd, "Active stream use case overrides:");
5396 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5397 dprintf(fd, " %" PRId64, useCaseOverride);
5398 }
5399 dprintf(fd, "\n");
5400 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005401
5402 dumpEventLog(fd);
5403
5404 bool stateLocked = tryLock(mCameraStatesLock);
5405 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005406 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005407 }
5408
Emilian Peevbd8c5032018-02-14 23:05:40 +00005409 int argSize = args.size();
5410 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005411 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005412 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005413 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005414 }
5415 break;
5416 }
5417 }
5418
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005419 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005420 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005421
Austin Borgered99f642023-06-01 16:51:35 -07005422 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005423
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005424 CameraParameters p = state.second->getShimParams();
5425 if (!p.isEmpty()) {
5426 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5427 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005428 }
5429
5430 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005431 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005432 // log the current open session info
5433 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005434 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005435 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005436 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005437
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005438 }
5439
5440 if (stateLocked) mCameraStatesLock.unlock();
5441
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005442 if (locked) mServiceLock.unlock();
5443
Emilian Peevf53f66e2017-04-11 14:29:43 +01005444 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005445
5446 dprintf(fd, "\n== Vendor tags: ==\n\n");
5447
5448 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5449 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005450 sp<VendorTagDescriptorCache> cache =
5451 VendorTagDescriptorCache::getGlobalVendorTagCache();
5452 if (cache == NULL) {
5453 dprintf(fd, "No vendor tags.\n");
5454 } else {
5455 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5456 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005457 } else {
5458 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5459 }
5460
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005461 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005462 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005463 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005464
5465 // Process dump arguments, if any
5466 int n = args.size();
5467 String16 verboseOption("-v");
5468 String16 unreachableOption("--unreachable");
5469 for (int i = 0; i < n; i++) {
5470 if (args[i] == verboseOption) {
5471 // change logging level
5472 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005473 std::string levelStr = toStdString(args[i+1]);
5474 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005475 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005476 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005477 } else if (args[i] == unreachableOption) {
5478 // Dump memory analysis
5479 // TODO - should limit be an argument parameter?
5480 UnreachableMemoryInfo info;
5481 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5482 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005483 dprintf(fd, "\n== Unable to dump unreachable memory. "
5484 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005485 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005486 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005487 std::string s = info.ToString(/*log_contents*/ true);
5488 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005489 }
5490 }
5491 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005492
5493 bool serviceLocked = tryLock(mServiceLock);
5494
5495 // Dump info from previous open sessions.
5496 // Reposition the offset to beginning of the file before reading
5497
5498 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5499 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5500 ssize_t size_read;
5501 char buf[4096];
5502 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5503 // Read data from file to a small buffer and write it to fd.
5504 write(fd, buf, size_read);
5505 if (size_read == -1) {
5506 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5507 break;
5508 }
5509 }
5510 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5511 } else {
5512 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5513 }
5514
5515 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005516 return NO_ERROR;
5517}
5518
Rucha Katakwardf223072021-06-15 10:21:00 -07005519void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005520 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005521 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005522 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005523 getFormattedCurrentTime().c_str(),
5524 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005525 dprintf(fd, " Client priority score: %d state: %d\n",
5526 clientDescriptor->getPriority().getScore(),
5527 clientDescriptor->getPriority().getState());
5528 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5529
5530 auto client = clientDescriptor->getValue();
5531 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005532 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005533
5534 client->dumpClient(fd, args);
5535}
5536
Austin Borgered99f642023-06-01 16:51:35 -07005537void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005538 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005539 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005540}
5541
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005542void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005543 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005544
5545 Mutex::Autolock l(mLogLock);
5546 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005547 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005548 }
5549
5550 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005551 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005552 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005553 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005554 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005555 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005556}
5557
Austin Borgered99f642023-06-01 16:51:35 -07005558void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005559 Mutex::Autolock lock(mLogLock);
5560 if (!isClientWatchedLocked(client)) { return; }
5561
5562 std::vector<std::string> dumpVector;
5563 client->dumpWatchedEventsToVector(dumpVector);
5564
5565 if (dumpVector.empty()) { return; }
5566
Austin Borgered99f642023-06-01 16:51:35 -07005567 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005568
Austin Borgered99f642023-06-01 16:51:35 -07005569 std::string currentTime = getFormattedCurrentTime();
5570 dumpString << "Cached @ ";
5571 dumpString << currentTime;
5572 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005573
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005574 size_t i = dumpVector.size();
5575
5576 // Store the string in reverse order (latest last)
5577 while (i > 0) {
5578 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005579 dumpString << cameraId;
5580 dumpString << ":";
5581 dumpString << client->getPackageName();
5582 dumpString << " ";
5583 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005584 }
5585
Austin Borgered99f642023-06-01 16:51:35 -07005586 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005587}
5588
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005589void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005590 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005591 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5592 if (mTorchClientMap[i] == who) {
5593 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005594 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005595 status_t res = mFlashlight->setTorchMode(cameraId, false);
5596 if (res) {
5597 ALOGE("%s: torch client died but couldn't turn off torch: "
5598 "%s (%d)", __FUNCTION__, strerror(-res), res);
5599 return;
5600 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005601 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005602 break;
5603 }
5604 }
5605}
5606
Ruben Brunkcc776712015-02-17 20:18:47 -08005607/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005608
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005609 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005610 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5611 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005612 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005613 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005614 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005615
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005616 // check torch client
5617 handleTorchClientBinderDied(who);
5618
5619 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005620 if(!evictClientIdByRemote(who)) {
5621 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005622 return;
5623 }
5624
Ruben Brunkcc776712015-02-17 20:18:47 -08005625 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5626 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005627}
5628
Austin Borgered99f642023-06-01 16:51:35 -07005629void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005630 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005631}
5632
Austin Borgered99f642023-06-01 16:51:35 -07005633void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005634 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005635 // Do not lock mServiceLock here or can get into a deadlock from
5636 // connect() -> disconnect -> updateStatus
5637
5638 auto state = getCameraState(cameraId);
5639
5640 if (state == nullptr) {
5641 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005642 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005643 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005644 }
5645
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005646 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5647 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5648 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005649 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005650 return;
5651 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005652
Biswarup Pal37a75182024-01-16 15:53:35 +00005653 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5654 CameraMetadata cameraInfo;
5655 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005656 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005657 if (res != OK) {
5658 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5659 __FUNCTION__, cameraId.c_str());
5660 } else {
5661 int32_t deviceId = getDeviceId(cameraInfo);
5662 if (deviceId != kDefaultDeviceId) {
5663 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5664 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5665 static_cast<camera_metadata_enum_android_lens_facing_t>(
5666 lensFacingEntry.data.u8[0]);
5667 std::string mappedCameraId;
5668 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5669 mappedCameraId = kVirtualDeviceBackCameraId;
5670 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5671 mappedCameraId = kVirtualDeviceFrontCameraId;
5672 } else {
5673 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5674 __func__);
5675 }
5676 if (!mappedCameraId.empty()) {
5677 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5678 }
5679 }
5680 }
5681 }
5682
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005683 // Collect the logical cameras without holding mStatusLock in updateStatus
5684 // as that can lead to a deadlock(b/162192331).
5685 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005686 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005687 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005688 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005689 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005690 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005691 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5692 auto [deviceId, mappedCameraId] =
5693 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005694
Biswarup Pal37a75182024-01-16 15:53:35 +00005695 if (status != StatusInternal::ENUMERATING) {
5696 // Update torch status if it has a flash unit.
5697 Mutex::Autolock al(mTorchStatusMutex);
5698 TorchModeStatus torchStatus;
5699 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5700 NAME_NOT_FOUND) {
5701 TorchModeStatus newTorchStatus =
5702 status == StatusInternal::PRESENT ?
5703 TorchModeStatus::AVAILABLE_OFF :
5704 TorchModeStatus::NOT_AVAILABLE;
5705 if (torchStatus != newTorchStatus) {
5706 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5707 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005708 }
5709 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005710
Biswarup Pal37a75182024-01-16 15:53:35 +00005711 Mutex::Autolock lock(mStatusListenerLock);
5712 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5713 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005714
Biswarup Pal37a75182024-01-16 15:53:35 +00005715 for (auto& listener : mListenerList) {
5716 bool isVendorListener = listener->isVendorListener();
5717 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5718 listener->getListenerPid(), listener->getListenerUid())) {
5719 ALOGV("Skipping discovery callback for system-only camera device %s",
5720 cameraId.c_str());
5721 continue;
5722 }
5723
5724 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5725 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005726 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005727 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005728 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5729 ret.exceptionCode());
5730 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005731 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005732}
5733
Austin Borgered99f642023-06-01 16:51:35 -07005734void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5735 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005736 auto state = getCameraState(cameraId);
5737 if (state == nullptr) {
5738 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005739 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005740 return;
5741 }
5742 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005743 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005744 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005745 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005746 }
5747
Biswarup Pal37a75182024-01-16 15:53:35 +00005748 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5749 auto [deviceId, mappedCameraId] =
5750 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5751
Shuzhen Wang695044d2020-03-06 09:02:23 -08005752 Mutex::Autolock lock(mStatusListenerLock);
5753
5754 for (const auto& it : mListenerList) {
5755 if (!it->isOpenCloseCallbackAllowed()) {
5756 continue;
5757 }
5758
5759 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005760 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005761 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5762 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005763 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005764 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005765 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005766
5767 it->handleBinderStatus(ret,
5768 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5769 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005770 }
5771}
5772
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005773template<class Func>
5774void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005775 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005776 std::initializer_list<StatusInternal> rejectSourceStates,
5777 Func onStatusUpdatedLocked) {
5778 Mutex::Autolock lock(mStatusLock);
5779 StatusInternal oldStatus = mStatus;
5780 mStatus = status;
5781
5782 if (oldStatus == status) {
5783 return;
5784 }
5785
5786 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005787 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005788
5789 if (oldStatus == StatusInternal::NOT_PRESENT &&
5790 (status != StatusInternal::PRESENT &&
5791 status != StatusInternal::ENUMERATING)) {
5792
5793 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5794 __FUNCTION__);
5795 mStatus = oldStatus;
5796 return;
5797 }
5798
5799 /**
5800 * Sometimes we want to conditionally do a transition.
5801 * For example if a client disconnects, we want to go to PRESENT
5802 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5803 */
5804 for (auto& rejectStatus : rejectSourceStates) {
5805 if (oldStatus == rejectStatus) {
5806 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005807 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005808 mStatus = oldStatus;
5809 return;
5810 }
5811 }
5812
5813 onStatusUpdatedLocked(cameraId, status);
5814}
5815
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005816status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005817 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005818 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005819 if (!status) {
5820 return BAD_VALUE;
5821 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005822 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5823 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005824 // invalid camera ID or the camera doesn't have a flash unit
5825 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005826 }
5827
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005828 *status = mTorchStatusMap.valueAt(index);
5829 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005830}
5831
Austin Borgered99f642023-06-01 16:51:35 -07005832status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005833 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005834 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5835 if (index == NAME_NOT_FOUND) {
5836 return BAD_VALUE;
5837 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005838 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005839
5840 return OK;
5841}
5842
Austin Borgered99f642023-06-01 16:51:35 -07005843std::list<std::string> CameraService::getLogicalCameras(
5844 const std::string& physicalCameraId) {
5845 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005846 Mutex::Autolock lock(mCameraStatesLock);
5847 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005848 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5849 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005850 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005851 }
5852 return retList;
5853}
5854
5855void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005856 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005857 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005858 // mStatusListenerLock is expected to be locked
5859 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005860 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005861 // Note: we check only the deviceKind of the physical camera id
5862 // since, logical camera ids and their physical camera ids are
5863 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005864 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5865 listener->getListenerPid(), listener->getListenerUid())) {
5866 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005867 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005868 continue;
5869 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005870 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005871 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005872 listener->handleBinderStatus(ret,
5873 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5874 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5875 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005876 }
5877 }
5878}
5879
Svet Ganova453d0d2018-01-11 15:37:58 -08005880void CameraService::blockClientsForUid(uid_t uid) {
5881 const auto clients = mActiveClientManager.getAll();
5882 for (auto& current : clients) {
5883 if (current != nullptr) {
5884 const auto basicClient = current->getValue();
5885 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5886 basicClient->block();
5887 }
5888 }
5889 }
5890}
5891
Michael Grooverd1d435a2018-12-18 17:39:42 -08005892void CameraService::blockAllClients() {
5893 const auto clients = mActiveClientManager.getAll();
5894 for (auto& current : clients) {
5895 if (current != nullptr) {
5896 const auto basicClient = current->getValue();
5897 if (basicClient.get() != nullptr) {
5898 basicClient->block();
5899 }
5900 }
5901 }
5902}
5903
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005904void CameraService::blockPrivacyEnabledClients() {
5905 const auto clients = mActiveClientManager.getAll();
5906 for (auto& current : clients) {
5907 if (current != nullptr) {
5908 const auto basicClient = current->getValue();
5909 if (basicClient.get() != nullptr) {
5910 std::string pkgName = basicClient->getPackageName();
5911 bool cameraPrivacyEnabled =
5912 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5913 if (cameraPrivacyEnabled) {
5914 basicClient->block();
5915 }
5916 }
5917 }
5918 }
5919}
5920
Svet Ganova453d0d2018-01-11 15:37:58 -08005921// NOTE: This is a remote API - make sure all args are validated
5922status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005923 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005924 return PERMISSION_DENIED;
5925 }
5926 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5927 return BAD_VALUE;
5928 }
Austin Borgered99f642023-06-01 16:51:35 -07005929 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005930 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005931 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005932 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005933 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005934 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005935 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005936 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005937 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005938 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005939 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005940 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005941 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005942 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005943 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005944 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005945 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005946 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005947 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005948 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005949 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005950 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005951 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005952 handleClearStreamUseCaseOverrides();
5953 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005954 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005955 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005956 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005957 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005958 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005959 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005960 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005961 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005962 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005963 }
5964 printHelp(err);
5965 return BAD_VALUE;
5966}
5967
5968status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005969 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005970
Svet Ganova453d0d2018-01-11 15:37:58 -08005971 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005972 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005973 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005974 } else if ((args[2] != toString16("idle"))) {
5975 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005976 return BAD_VALUE;
5977 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005978
5979 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005980 if (args.size() >= 5 && args[3] == toString16("--user")) {
5981 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005982 }
5983
5984 uid_t uid;
5985 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5986 return BAD_VALUE;
5987 }
5988
5989 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005990 return NO_ERROR;
5991}
5992
5993status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005994 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005995
5996 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005997 if (args.size() >= 4 && args[2] == toString16("--user")) {
5998 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005999 }
6000
6001 uid_t uid;
6002 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006003 return BAD_VALUE;
6004 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006005
6006 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006007 return NO_ERROR;
6008}
6009
6010status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006011 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006012
6013 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006014 if (args.size() >= 4 && args[2] == toString16("--user")) {
6015 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006016 }
6017
6018 uid_t uid;
6019 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006020 return BAD_VALUE;
6021 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006022
6023 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006024 return dprintf(out, "active\n");
6025 } else {
6026 return dprintf(out, "idle\n");
6027 }
6028}
6029
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006030status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006031 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006032 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6033 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6034 Mutex::Autolock lock(mServiceLock);
6035
6036 mOverrideRotateAndCropMode = rotateValue;
6037
6038 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6039
6040 const auto clients = mActiveClientManager.getAll();
6041 for (auto& current : clients) {
6042 if (current != nullptr) {
6043 const auto basicClient = current->getValue();
6044 if (basicClient.get() != nullptr) {
6045 basicClient->setRotateAndCropOverride(rotateValue);
6046 }
6047 }
6048 }
6049
6050 return OK;
6051}
6052
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006053status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6054 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006055 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006056 if ((*end != '\0') ||
6057 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6058 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6059 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6060 return BAD_VALUE;
6061 }
6062
6063 Mutex::Autolock lock(mServiceLock);
6064 mOverrideAutoframingMode = autoframingValue;
6065
6066 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6067
6068 const auto clients = mActiveClientManager.getAll();
6069 for (auto& current : clients) {
6070 if (current != nullptr) {
6071 const auto basicClient = current->getValue();
6072 if (basicClient.get() != nullptr) {
6073 basicClient->setAutoframingOverride(autoframingValue);
6074 }
6075 }
6076 }
6077
6078 return OK;
6079}
6080
Ravneetaeb20dc2022-03-30 05:33:03 +00006081status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006082 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006083
6084 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6085
6086 Mutex::Autolock lock(mServiceLock);
6087
6088 mCameraServiceWatchdogEnabled = enableWatchdog;
6089
6090 const auto clients = mActiveClientManager.getAll();
6091 for (auto& current : clients) {
6092 if (current != nullptr) {
6093 const auto basicClient = current->getValue();
6094 if (basicClient.get() != nullptr) {
6095 basicClient->setCameraServiceWatchdog(enableWatchdog);
6096 }
6097 }
6098 }
6099
6100 return OK;
6101}
6102
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006103status_t CameraService::handleGetRotateAndCrop(int out) {
6104 Mutex::Autolock lock(mServiceLock);
6105
6106 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6107}
6108
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006109status_t CameraService::handleGetAutoframing(int out) {
6110 Mutex::Autolock lock(mServiceLock);
6111
6112 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6113}
6114
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006115status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6116 char *endPtr;
6117 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006118 std::string maskString = toStdString(args[1]);
6119 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006120
6121 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006122 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006123 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6124
6125 Mutex::Autolock lock(mServiceLock);
6126
6127 mImageDumpMask = maskValue;
6128
6129 return OK;
6130}
6131
6132status_t CameraService::handleGetImageDumpMask(int out) {
6133 Mutex::Autolock lock(mServiceLock);
6134
6135 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6136}
6137
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006138status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006139 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006140 if (errno != 0) return BAD_VALUE;
6141
6142 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6143 Mutex::Autolock lock(mServiceLock);
6144
6145 mOverrideCameraMuteMode = (muteValue == 1);
6146
6147 const auto clients = mActiveClientManager.getAll();
6148 for (auto& current : clients) {
6149 if (current != nullptr) {
6150 const auto basicClient = current->getValue();
6151 if (basicClient.get() != nullptr) {
6152 if (basicClient->supportsCameraMute()) {
6153 basicClient->setCameraMute(mOverrideCameraMuteMode);
6154 }
6155 }
6156 }
6157 }
6158
6159 return OK;
6160}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006161
Shuzhen Wang16610a62022-12-15 22:38:07 -08006162status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6163 std::vector<int64_t> useCasesOverride;
6164 for (size_t i = 1; i < args.size(); i++) {
6165 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006166 std::string arg = toStdString(args[i]);
6167 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006168 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006169 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006170 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006171 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006172 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006173 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006174 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006175 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006176 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006177 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006178 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006179 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006180 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6181 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006182 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006183 return BAD_VALUE;
6184 }
6185 useCasesOverride.push_back(useCase);
6186 }
6187
6188 Mutex::Autolock lock(mServiceLock);
6189 mStreamUseCaseOverrides = std::move(useCasesOverride);
6190
6191 return OK;
6192}
6193
6194void CameraService::handleClearStreamUseCaseOverrides() {
6195 Mutex::Autolock lock(mServiceLock);
6196 mStreamUseCaseOverrides.clear();
6197}
6198
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006199status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6200 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006201 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006202 if ((*end != '\0') ||
6203 (zoomOverrideValue != -1 &&
6204 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6205 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6206 return BAD_VALUE;
6207 }
6208
6209 Mutex::Autolock lock(mServiceLock);
6210 mZoomOverrideValue = zoomOverrideValue;
6211
6212 const auto clients = mActiveClientManager.getAll();
6213 for (auto& current : clients) {
6214 if (current != nullptr) {
6215 const auto basicClient = current->getValue();
6216 if (basicClient.get() != nullptr) {
6217 if (basicClient->supportsZoomOverride()) {
6218 basicClient->setZoomOverride(mZoomOverrideValue);
6219 }
6220 }
6221 }
6222 }
6223
6224 return OK;
6225}
6226
Avichal Rakesh84147132021-11-11 17:47:11 -08006227status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006228 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006229 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006230 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006231 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006232 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006233 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006234 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006235 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006236 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006237 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006238 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006239 dprintf(outFd, "Camera service watch commands:\n"
6240 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6241 " starts watching the provided tags for clients with provided package\n"
6242 " recognizes tag shorthands like '3a'\n"
6243 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006244 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006245 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006246 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006247 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006248 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006249 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006250 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006251}
6252
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006253status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6254 Mutex::Autolock lock(mLogLock);
6255 size_t tagsIdx; // index of '-m'
6256 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006257 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006258 if (tagsIdx < args.size() - 1) {
6259 tags = args[tagsIdx + 1];
6260 } else {
6261 dprintf(outFd, "No tags provided.\n");
6262 return BAD_VALUE;
6263 }
6264
6265 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006266 // watch all clients if no clients are provided
6267 String16 clients = toString16(kWatchAllClientsFlag);
6268 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006269 clientsIdx++);
6270 if (clientsIdx < args.size() - 1) {
6271 clients = args[clientsIdx + 1];
6272 }
Austin Borgered99f642023-06-01 16:51:35 -07006273 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006274
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006275 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006276 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006277
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006278 bool serviceLock = tryLock(mServiceLock);
6279 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006280 auto cameraClients = mActiveClientManager.getAll();
6281 for (const auto &clientDescriptor: cameraClients) {
6282 if (clientDescriptor == nullptr) { continue; }
6283 sp<BasicClient> client = clientDescriptor->getValue();
6284 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006285
6286 if (isClientWatchedLocked(client.get())) {
6287 client->startWatchingTags(mMonitorTags, outFd);
6288 numWatchedClients++;
6289 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006290 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006291 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6292
6293 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006294 return OK;
6295}
6296
6297status_t CameraService::stopWatchingTags(int outFd) {
6298 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006299 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006300 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006301
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006302 mWatchedClientPackages.clear();
6303 mWatchedClientsDumpCache.clear();
6304
6305 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006306 auto cameraClients = mActiveClientManager.getAll();
6307 for (const auto &clientDescriptor : cameraClients) {
6308 if (clientDescriptor == nullptr) { continue; }
6309 sp<BasicClient> client = clientDescriptor->getValue();
6310 if (client.get() == nullptr) { continue; }
6311 client->stopWatchingTags(outFd);
6312 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006313 dprintf(outFd, "Stopped watching all clients.\n");
6314 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006315 return OK;
6316}
6317
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006318status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6319 Mutex::Autolock lock(mLogLock);
6320 size_t clearedSize = mWatchedClientsDumpCache.size();
6321 mWatchedClientsDumpCache.clear();
6322 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6323 return OK;
6324}
6325
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006326status_t CameraService::printWatchedTags(int outFd) {
6327 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006328 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006329
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006330 bool printedSomething = false; // tracks if any monitoring information was printed
6331 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006332
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006333 bool serviceLock = tryLock(mServiceLock);
6334 // get all watched clients that are currently connected
6335 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6336 if (clientDescriptor == nullptr) { continue; }
6337
6338 sp<BasicClient> client = clientDescriptor->getValue();
6339 if (client.get() == nullptr) { continue; }
6340 if (!isClientWatchedLocked(client.get())) { continue; }
6341
6342 std::vector<std::string> dumpVector;
6343 client->dumpWatchedEventsToVector(dumpVector);
6344
6345 size_t printIdx = dumpVector.size();
6346 if (printIdx == 0) {
6347 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006348 }
6349
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006350 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006351 const std::string &cameraId = clientDescriptor->getKey();
6352 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006353 while(printIdx > 0) {
6354 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006355 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006356 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006357 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006358 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006359 printedSomething = true;
6360
6361 connectedMonitoredClients.emplace(client->getPackageName());
6362 }
6363 if (serviceLock) { mServiceLock.unlock(); }
6364
6365 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6366 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006367 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006368 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6369 continue;
6370 }
6371
Austin Borgered99f642023-06-01 16:51:35 -07006372 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006373 dprintf(outFd, "%s\n", kv.second.c_str());
6374 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006375 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006376
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006377 if (!printedSomething) {
6378 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006379 }
6380
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006381 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006382}
6383
Avichal Rakesh84147132021-11-11 17:47:11 -08006384// Print all events in vector `events' that came after lastPrintedEvent
6385void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006386 const std::string &cameraId,
6387 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006388 const std::vector<std::string> &events,
6389 const std::string &lastPrintedEvent) {
6390 if (events.empty()) { return; }
6391
6392 // index of lastPrintedEvent in events.
6393 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6394 size_t lastPrintedIdx;
6395 for (lastPrintedIdx = 0;
6396 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6397 lastPrintedIdx++);
6398
6399 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6400
Avichal Rakesh84147132021-11-11 17:47:11 -08006401 // print events in chronological order (latest event last)
6402 size_t idxToPrint = lastPrintedIdx;
6403 do {
6404 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006405 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6406 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006407 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006408}
6409
6410// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6411// command should be interrupted if the user presses the return key, or if user loses any way to
6412// signal interrupt.
6413// If timeoutMs == 0, this function will always return false
6414bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6415 struct timeval startTime;
6416 int startTimeError = gettimeofday(&startTime, nullptr);
6417 if (startTimeError) {
6418 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6419 return true;
6420 }
6421
6422 const nfds_t numFds = 1;
6423 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6424
6425 struct timeval currTime;
6426 char buffer[2];
6427 while(true) {
6428 int currTimeError = gettimeofday(&currTime, nullptr);
6429 if (currTimeError) {
6430 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6431 return true;
6432 }
6433
6434 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6435 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6436 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6437
6438 if (remainingTimeMs <= 0) {
6439 // No user interrupt within timeoutMs, don't interrupt watch command
6440 return false;
6441 }
6442
6443 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6444 if (numFdsUpdated < 0) {
6445 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6446 return true;
6447 }
6448
6449 if (numFdsUpdated == 0) {
6450 // No user input within timeoutMs, don't interrupt watch command
6451 return false;
6452 }
6453
6454 if (!(pollFd.revents & POLLIN)) {
6455 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6456 return true;
6457 }
6458
6459 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6460 if (sizeRead < 0) {
6461 dprintf(outFd, "Error reading user input. Exiting.\n");
6462 return true;
6463 }
6464
6465 if (sizeRead == 0) {
6466 // Reached end of input fd (can happen if input is piped)
6467 // User has no way to signal an interrupt, so interrupt here
6468 return true;
6469 }
6470
6471 if (buffer[0] == '\n') {
6472 // User pressed return, interrupt watch command.
6473 return true;
6474 }
6475 }
6476}
6477
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006478status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6479 int inFd, int outFd) {
6480 // Figure out refresh interval, if present in args
6481 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006482 if (args.size() > 2) {
6483 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006484 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006485 intervalIdx++);
6486
6487 size_t intervalValIdx = intervalIdx + 1;
6488 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006489 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006490 if (errno) { return BAD_VALUE; }
6491 }
6492 }
6493
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006494 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6495 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006496
Avichal Rakesh84147132021-11-11 17:47:11 -08006497 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006498 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006499
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006500 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006501 bool serviceLock = tryLock(mServiceLock);
6502 auto cameraClients = mActiveClientManager.getAll();
6503 if (serviceLock) { mServiceLock.unlock(); }
6504
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006505 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006506 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006507 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006508
6509 sp<BasicClient> client = clientDescriptor->getValue();
6510 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006511 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006512
Austin Borgered99f642023-06-01 16:51:35 -07006513 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006514 // This also initializes the map entries with an empty string
6515 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6516
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006517 std::vector<std::string> latestEvents;
6518 client->dumpWatchedEventsToVector(latestEvents);
6519
6520 if (!latestEvents.empty()) {
6521 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006522 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006523 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006524 latestEvents,
6525 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006526 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006527 }
6528 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006529 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006530 break;
6531 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006532 }
6533 return OK;
6534}
6535
Austin Borgered99f642023-06-01 16:51:35 -07006536void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006537 mWatchedClientPackages.clear();
6538
Austin Borgered99f642023-06-01 16:51:35 -07006539 std::istringstream iss(clients);
6540 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006541
Austin Borgered99f642023-06-01 16:51:35 -07006542 while (std::getline(iss, nextClient, ',')) {
6543 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006544 // Don't need to track any other package if 'all' is present
6545 mWatchedClientPackages.clear();
6546 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6547 break;
6548 }
6549
6550 // track package names
6551 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006552 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006553}
6554
Svet Ganova453d0d2018-01-11 15:37:58 -08006555status_t CameraService::printHelp(int out) {
6556 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006557 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6558 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6559 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006560 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6561 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6562 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006563 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6564 " Valid values 0=false, 1=true, 2=auto\n"
6565 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006566 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6567 " Valid values 0=OFF, 1=ON for JPEG\n"
6568 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006569 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006570 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6571 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6572 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6573 " on. In case the number of usecases is smaller than the number of streams, the\n"
6574 " last use case is assigned to all the remaining streams. In case of multiple\n"
6575 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6576 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6577 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6578 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006579 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6580 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006581 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6582 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006583 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006584 " help print this message\n");
6585}
6586
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006587bool CameraService::isClientWatched(const BasicClient *client) {
6588 Mutex::Autolock lock(mLogLock);
6589 return isClientWatchedLocked(client);
6590}
6591
6592bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6593 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6594 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6595}
6596
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006597int32_t CameraService::updateAudioRestriction() {
6598 Mutex::Autolock lock(mServiceLock);
6599 return updateAudioRestrictionLocked();
6600}
6601
6602int32_t CameraService::updateAudioRestrictionLocked() {
6603 int32_t mode = 0;
6604 // iterate through all active client
6605 for (const auto& i : mActiveClientManager.getAll()) {
6606 const auto clientSp = i->getValue();
6607 mode |= clientSp->getAudioRestriction();
6608 }
6609
6610 bool modeChanged = (mAudioRestriction != mode);
6611 mAudioRestriction = mode;
6612 if (modeChanged) {
6613 mAppOps.setCameraAudioRestriction(mode);
6614 }
6615 return mode;
6616}
6617
Austin Borgered99f642023-06-01 16:51:35 -07006618status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006619 sp<BasicClient> clientSp) {
6620 std::unique_ptr<AutoConditionLock> lock =
6621 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6622 status_t res = NO_ERROR;
6623 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006624 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006625 mInjectionStatusListener->notifyInjectionError(
6626 externalCamId, UNKNOWN_TRANSACTION);
6627 clientSp->notifyError(
6628 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6629 CaptureResultExtras());
6630
6631 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6632 // other clients from connecting in mServiceLockWrapper if held
6633 mServiceLock.unlock();
6634
6635 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006636 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006637 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006638 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006639
6640 // Reacquire mServiceLock
6641 mServiceLock.lock();
6642 }
6643
6644 return res;
6645}
6646
Cliff Wud3a05312021-04-26 23:07:31 +08006647void CameraService::clearInjectionParameters() {
6648 {
6649 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006650 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006651 mInjectionInternalCamId = "";
6652 }
6653 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006654 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006655}
6656
Biswarup Pal37a75182024-01-16 15:53:35 +00006657} // namespace android