blob: 6a5d5e08d683f89dec7ea1da79faf8436ea15e52 [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000086#include "utils/CameraTraces.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000088#include "utils/TagMonitor.h"
89#include "utils/Utils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080091namespace {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080092 const char* kActivityServiceName = "activity";
93 const char* kSensorPrivacyServiceName = "sensor_privacy";
94 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070095 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000096 const char* kVirtualDeviceBackCameraId = "0";
97 const char* kVirtualDeviceFrontCameraId = "1";
98
99 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
100 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
101 return android::kDefaultDeviceId;
102 }
103
104 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
105 return deviceIdEntry.data.i32[0];
106 }
107} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Austin Borgerea931242021-12-13 23:10:41 +0000111using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700112using namespace camera3::SessionConfigurationUtils;
113
114using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000115using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700116using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700117using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800118using hardware::ICamera;
119using hardware::ICameraClient;
120using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800121using hardware::camera2::ICameraInjectionCallback;
122using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800123using hardware::camera2::utils::CameraIdAndSessionConfiguration;
124using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000125
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700126namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000127namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130// Logging support -- this is for debugging only
131// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700132volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Steve Blockb8a80522011-12-20 16:23:08 +0000134#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
135#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
137static void setLogLevel(int level) {
138 android_atomic_write(level, &gLogLevel);
139}
140
Henri Chataingbcb99452023-11-01 17:40:30 +0000141int32_t format_as(CameraService::StatusInternal s) {
142 return fmt::underlying(s);
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Austin Borger249e6592024-03-10 22:28:11 -0700147// Permission strings (references to AttributionAndPermissionUtils for brevity)
148static const std::string &sDumpPermission =
149 AttributionAndPermissionUtils::sDumpPermission;
150static const std::string &sManageCameraPermission =
151 AttributionAndPermissionUtils::sManageCameraPermission;
152static const std::string &sCameraSendSystemEventsPermission =
153 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
154static const std::string &sCameraInjectExternalCameraPermission =
155 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
156
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000157// Constant integer for FGS Logging, used to denote the API type for logger
158static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700159const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800160static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
161static constexpr int32_t kSystemNativeClientState =
162 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700163static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700164
Austin Borgered99f642023-06-01 16:51:35 -0700165const std::string CameraService::kOfflineDevice("offline-");
166const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700167
Biswarup Pal7d072862024-04-17 15:24:47 +0000168constexpr int32_t kInvalidDeviceId = -1;
169
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700171static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700172
Austin Borger74fca042022-05-23 12:41:21 -0700173CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700174 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
175 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
176 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
177 std::make_shared<AttributionAndPermissionUtils>()\
178 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700179 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
180 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800181 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800182 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700183 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mSoundRef(0), mInitialized(false),
185 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000186 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700187 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800188 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700189 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
190 if (mMemFd == -1) {
191 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193}
194
Charles Chena7b613c2023-01-24 21:57:33 +0000195// Enable processes with isolated AID to request the binder
196void CameraService::instantiate() {
197 CameraService::publish(true);
198}
199
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700201 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800202 return;
203 }
204
205 ALOGV("appops service registered. setting camera audio restriction");
206 mAppOps.setCameraAudioRestriction(mAudioRestriction);
207}
208
Iliyan Malchev8951a972011-04-14 16:55:59 -0700209void CameraService::onFirstRef()
210{
Ruben Brunkcc776712015-02-17 20:18:47 -0800211 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800212
Iliyan Malchev8951a972011-04-14 16:55:59 -0700213 BnCameraService::onFirstRef();
214
Ruben Brunk99e69712015-05-26 17:25:07 -0700215 // Update battery life tracking if service is restarting
216 BatteryNotifier& notifier(BatteryNotifier::getInstance());
217 notifier.noteResetCamera();
218 notifier.noteResetFlashlight();
219
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800220 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800221
Emilian Peevf53f66e2017-04-11 14:29:43 +0100222 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223 if (res == OK) {
224 mInitialized = true;
225 }
226
Svet Ganova453d0d2018-01-11 15:37:58 -0800227 mUidPolicy = new UidPolicy(this);
228 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700229 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800230 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800231 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800232
233 // appops function setCamerAudioRestriction uses getService which
234 // is blocking till the appops service is ready. To enable early
235 // boot availability for cameraservice, use checkService which is
236 // non blocking and register for notifications
237 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700238 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700240 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800241 } else {
242 mAppOps.setCameraAudioRestriction(mAudioRestriction);
243 }
244
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700245 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
246 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000247 // Deprecated, so it will fail to register on newer devices
248 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700249 __FUNCTION__);
250 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700251
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700252 if (!AidlCameraService::registerService(this)) {
253 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
254 }
255
Shuzhen Wang24b44152019-09-20 10:38:11 -0700256 // This needs to be last call in this function, so that it's as close to
257 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700258 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700259 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260}
261
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800262status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100264
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000266 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 {
268 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800269
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800270 if (nullptr == mCameraProviderManager.get()) {
271 mCameraProviderManager = new CameraProviderManager();
272 res = mCameraProviderManager->initialize(this);
273 if (res != OK) {
274 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
275 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700276 logServiceError("Unable to initialize camera provider manager",
277 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800278 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100279 }
280 }
281
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 // Setup vendor tags before we call get_camera_info the first time
283 // because HAL might need to setup static vendor keys in get_camera_info
284 // TODO: maybe put this into CameraProviderManager::initialize()?
285 mCameraProviderManager->setUpVendorTags();
286
287 if (nullptr == mFlashlight.get()) {
288 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700289 }
290
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800291 res = mFlashlight->findFlashUnits();
292 if (res != OK) {
293 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
294 }
295
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000296 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 }
298
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800299 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700300 if (getCameraState(cameraId) == nullptr) {
301 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800302 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000303 if (unavailPhysicalIds.count(cameraId) > 0) {
304 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700305 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000306 }
307 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800308 }
309
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700310 // Derive primary rear/front cameras, and filter their charactierstics.
311 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700312 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700313 // Assume internal cameras are advertised from the same
314 // provider. If multiple providers are registered at different time,
315 // and each provider contains multiple internal color cameras, the current
316 // logic may filter the characteristics of more than one front/rear color
317 // cameras.
318 Mutex::Autolock l(mServiceLock);
319 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700320 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700321
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800322 return OK;
323}
324
Austin Borgered99f642023-06-01 16:51:35 -0700325void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700326 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000327 // Get the device id and app-visible camera id for the given HAL-visible camera id.
328 auto [deviceId, mappedCameraId] =
329 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
330
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800331 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700333 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
334 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000335 ALOGV("%s: Skipping torch callback for system-only camera device %s",
336 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700337 continue;
338 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000339
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000341 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700342 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
343 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800344 }
345}
346
Mathias Agopian65ab4712010-07-14 17:59:35 -0700347CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800348 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800349 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800350 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800351 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700352}
353
Emilian Peevaee727d2017-05-04 16:35:48 +0100354void CameraService::onNewProviderRegistered() {
355 enumerateProviders();
356}
357
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700358void CameraService::filterAPI1SystemCameraLocked(
359 const std::vector<std::string> &normalDeviceIds) {
360 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000361 for (auto &cameraId : normalDeviceIds) {
362 if (vd_flags::camera_device_awareness()) {
363 CameraMetadata cameraInfo;
364 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000365 cameraId, false, &cameraInfo,
366 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000367 int32_t deviceId = kDefaultDeviceId;
368 if (res != OK) {
369 ALOGW("%s: Not able to get camera characteristics for camera id %s",
370 __FUNCTION__, cameraId.c_str());
371 } else {
372 deviceId = getDeviceId(cameraInfo);
373 }
374 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
375 // system cameras, so skip for non-default device id's.
376 if (deviceId != kDefaultDeviceId) {
377 continue;
378 }
379 }
380
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700381 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000382 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
383 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700384 continue;
385 }
386 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700387 // All system camera ids will necessarily come after public camera
388 // device ids as per the HAL interface contract.
389 break;
390 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000391 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700392 }
393 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
394 mNormalDeviceIdsWithoutSystemCamera.size());
395}
396
Austin Borgered99f642023-06-01 16:51:35 -0700397status_t CameraService::getSystemCameraKind(const std::string& cameraId,
398 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700399 auto state = getCameraState(cameraId);
400 if (state != nullptr) {
401 *kind = state->getSystemCameraKind();
402 return OK;
403 }
404 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700405 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700406}
407
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800408void CameraService::updateCameraNumAndIds() {
409 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700410 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
411 // Excludes hidden secure cameras
412 mNumberOfCameras =
413 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
414 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800415 mNormalDeviceIds =
416 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700417 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800418}
419
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700420void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700421 // To claim to be S Performance primary cameras, the cameras must be
422 // backward compatible. So performance class primary camera Ids must be API1
423 // compatible.
424 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
425 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
426 int facing = -1;
427 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800428 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000429 getDeviceVersion(cameraId,
430 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
431 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700432 if (facing == -1) {
433 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
434 return;
435 }
436
437 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
438 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700439 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
440 if (res == OK) {
441 mPerfClassPrimaryCameraIds.insert(cameraId);
442 } else {
443 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
444 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
445 break;
446 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700447
448 if (facing == hardware::CAMERA_FACING_BACK) {
449 firstRearCameraSeen = true;
450 }
451 if (facing == hardware::CAMERA_FACING_FRONT) {
452 firstFrontCameraSeen = true;
453 }
454 }
455
456 if (firstRearCameraSeen && firstFrontCameraSeen) {
457 break;
458 }
459 }
460}
461
Austin Borgered99f642023-06-01 16:51:35 -0700462void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700463 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100464 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
465 if (res != OK) {
466 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
467 return;
468 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000469 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700470 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
471 if (res != OK) {
472 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
473 return;
474 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000475 std::vector<std::string> physicalCameraIds;
476 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700477 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100478 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700479 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100480 }
481
482 {
483 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700484 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000485 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100486 }
487
Austin Borgered99f642023-06-01 16:51:35 -0700488 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100489 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700490 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800491
Austin Borgered99f642023-06-01 16:51:35 -0700492 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100493 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800494
495 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700496 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497}
498
Austin Borgered99f642023-06-01 16:51:35 -0700499void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800500 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700501 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100502 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700503 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100504 }
505
506 {
507 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700508 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100509 }
510}
511
Austin Borgered99f642023-06-01 16:51:35 -0700512void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800513 CameraDeviceStatus newHalStatus) {
514 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700515 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700516
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800517 StatusInternal newStatus = mapToInternal(newHalStatus);
518
Austin Borgered99f642023-06-01 16:51:35 -0700519 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800520
521 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700522 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100523 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700524 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100525
526 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700527 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100528
Austin Borgered99f642023-06-01 16:51:35 -0700529 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700530 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700531 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700532 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700533 return;
534 }
535
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800536 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800538 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700539 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
540 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700541 return;
542 }
543
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800544 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000545 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
546 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800547 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
548 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700549 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000550 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800551
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800552 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700553 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 // Don't do this in updateStatus to avoid deadlock over mServiceLock
555 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700556
Ruben Brunkcc776712015-02-17 20:18:47 -0800557 // Remove cached shim parameters
558 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700559
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800560 // Remove online as well as offline client from the list of active clients,
561 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700562 clientToDisconnectOnline = removeClientLocked(cameraId);
563 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700564 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800565
Austin Borgered99f642023-06-01 16:51:35 -0700566 disconnectClient(cameraId, clientToDisconnectOnline);
567 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700568
Austin Borgered99f642023-06-01 16:51:35 -0700569 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800570 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800571 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000572 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
573 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700574 }
Austin Borgered99f642023-06-01 16:51:35 -0700575 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700576 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800577}
Igor Murashkincba2c162013-03-20 15:56:31 -0700578
Austin Borgered99f642023-06-01 16:51:35 -0700579void CameraService::onDeviceStatusChanged(const std::string& id,
580 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800581 CameraDeviceStatus newHalStatus) {
582 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700583 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800584
585 StatusInternal newStatus = mapToInternal(newHalStatus);
586
587 std::shared_ptr<CameraState> state = getCameraState(id);
588
589 if (state == nullptr) {
590 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700591 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800592 return;
593 }
594
595 StatusInternal logicalCameraStatus = state->getStatus();
596 if (logicalCameraStatus != StatusInternal::PRESENT &&
597 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
598 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700599 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800600 return;
601 }
602
603 bool updated = false;
604 if (newStatus == StatusInternal::PRESENT) {
605 updated = state->removeUnavailablePhysicalId(physicalId);
606 } else {
607 updated = state->addUnavailablePhysicalId(physicalId);
608 }
609
610 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700611 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800612 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000613 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800614 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000615 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800616 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700617 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
618 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
619 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700620 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700621 return;
622 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800623 Mutex::Autolock lock(mStatusListenerLock);
624 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700625 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
626 listener->getListenerPid(), listener->getListenerUid())) {
627 ALOGV("Skipping discovery callback for system-only camera device %s",
628 id.c_str());
629 continue;
630 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700631 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000632 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700633 listener->handleBinderStatus(ret,
634 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
635 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
636 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800637 }
638 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700639}
640
Austin Borgered99f642023-06-01 16:51:35 -0700641void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800642 if (clientToDisconnect.get() != nullptr) {
643 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700644 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800645 // Notify the client of disconnection
646 clientToDisconnect->notifyError(
647 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
648 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800649 clientToDisconnect->disconnect();
650 }
651}
652
Austin Borgered99f642023-06-01 16:51:35 -0700653void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800654 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700655 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
656 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
657 if (res != OK) {
658 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700659 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700660 return;
661 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800662 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700663 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800664}
665
Austin Borgered99f642023-06-01 16:51:35 -0700666void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700667 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
668 Mutex::Autolock al(mTorchStatusMutex);
669 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
670}
671
Austin Borgered99f642023-06-01 16:51:35 -0700672void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800673 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000674 // Get the device id and app-visible camera id for the given HAL-visible camera id.
675 auto [deviceId, mappedCameraId] =
676 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
677
Rucha Katakwar38284522021-11-10 11:25:21 -0800678 Mutex::Autolock lock(mStatusListenerLock);
679 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000680 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
681 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700682 i->handleBinderStatus(ret,
683 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
684 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800685 }
686}
687
Austin Borgered99f642023-06-01 16:51:35 -0700688void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700689 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800690 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700691 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800692
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800693 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800694 status_t res = getTorchStatusLocked(cameraId, &status);
695 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700696 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700697 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800698 return;
699 }
700 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800701 return;
702 }
703
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800704 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800705 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800706 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
707 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800708 return;
709 }
710
Ruben Brunkcc776712015-02-17 20:18:47 -0800711 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700712 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700713 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700714 auto iter = mTorchUidMap.find(cameraId);
715 if (iter != mTorchUidMap.end()) {
716 int oldUid = iter->second.second;
717 int newUid = iter->second.first;
718 BatteryNotifier& notifier(BatteryNotifier::getInstance());
719 if (oldUid != newUid) {
720 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800721 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700722 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700723 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800724 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700725 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700726 }
727 iter->second.second = newUid;
728 } else {
729 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800730 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700731 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700732 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700733 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700734 }
735 }
736 }
737 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700738 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800739}
740
Austin Borger249e6592024-03-10 22:28:11 -0700741bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700742 // Returns false if this is not an automotive device type.
743 if (!isAutomotiveDevice())
744 return false;
745
746 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700747 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700748 return false;
749
750 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
751 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
752 // This isn't a known camera ID, so it's not a system camera.
753 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
754 return false;
755 }
756
757 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
758 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
759 return false;
760 }
761
762 CameraMetadata cameraInfo;
763 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000764 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700765 if (res != OK){
766 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
767 cam_id.c_str());
768 return false;
769 }
770
771 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
772 if (auto_location.count != 1)
773 return false;
774
775 uint8_t location = auto_location.data.u8[0];
776 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
777 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
778 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
779 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
780 return false;
781 }
782
783 return true;
784}
785
Austin Borger65e64642024-06-11 15:58:23 -0700786Status CameraService::getNumberOfCameras(int32_t type,
787 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000788 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700789 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700790 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000791 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700792 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000793 return Status::ok();
794 }
795
Emilian Peevaee727d2017-05-04 16:35:48 +0100796 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700797 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800798 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
799 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700800 switch (type) {
801 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700802 if (hasSystemCameraPermissions) {
803 *numCameras = static_cast<int>(mNormalDeviceIds.size());
804 } else {
805 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
806 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800807 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700808 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700809 if (hasSystemCameraPermissions) {
810 *numCameras = mNumberOfCameras;
811 } else {
812 *numCameras = mNumberOfCamerasWithoutSystemCamera;
813 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800814 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800816 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700817 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800818 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
819 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700822}
823
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700824Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700825 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700826 /* out */
827 hardware::camera2::impl::CameraMetadataNative* request) {
828 ATRACE_CALL();
829
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700830 if (!mInitialized) {
831 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
832 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
833 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
834 }
835
Austin Borger65e64642024-06-11 15:58:23 -0700836 std::optional<std::string> cameraIdOptional =
837 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000838 if (!cameraIdOptional.has_value()) {
839 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700840 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000841 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
842 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
843 }
844 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700845
846 binder::Status res;
847 if (request == nullptr) {
848 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
849 "Camera %s: Error creating default request", cameraId.c_str());
850 return res;
851 }
852 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
853 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
854 cameraId, templateId, &tempId);
855 if (!res.isOk()) {
856 ALOGE("%s: Camera %s: failed to map request Template %d",
857 __FUNCTION__, cameraId.c_str(), templateId);
858 return res;
859 }
860
861 if (shouldRejectSystemCameraConnection(cameraId)) {
862 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
863 "request for system only device %s: ", cameraId.c_str());
864 }
865
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700866 CameraMetadata metadata;
867 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
868 if (err == OK) {
869 request->swap(metadata);
870 } else if (err == BAD_VALUE) {
871 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
872 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
873 cameraId.c_str(), templateId, strerror(-err), err);
874 } else {
875 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
876 "Camera %s: Error creating default request for template %d: %s (%d)",
877 cameraId.c_str(), templateId, strerror(-err), err);
878 }
879 return res;
880}
881
882Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700883 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700884 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700885 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700886 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700887 ATRACE_CALL();
888
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700889 if (!mInitialized) {
890 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
891 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
892 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
893 }
894
Austin Borger65e64642024-06-11 15:58:23 -0700895 std::optional<std::string> cameraIdOptional =
896 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000897 if (!cameraIdOptional.has_value()) {
898 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700899 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000900 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
901 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
902 }
903 std::string cameraId = cameraIdOptional.value();
904
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700905 if (supported == nullptr) {
906 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
907 unresolvedCameraId.c_str());
908 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
909 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
910 }
911
912 if (shouldRejectSystemCameraConnection(cameraId)) {
913 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
914 "session configuration with parameters support for system only device %s: ",
915 cameraId.c_str());
916 }
917
Avichal Rakeshe005df52024-09-25 17:13:27 -0700918 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700919 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
920
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700921 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
922 sessionConfiguration, overrideForPerfClass, supported);
923 if (flags::analytics_24q3()) {
924 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
925 getCallingUid(), sessionConfiguration, ret);
926 }
927 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700928}
929
930Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
931 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
932 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700933 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700934 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
935 cameraId, sessionConfiguration, overrideForPerfClass,
936 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700937 binder::Status res;
938 switch (ret) {
939 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700940 // Expected. Do Nothing.
941 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700942 case INVALID_OPERATION: {
943 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700944 "Camera %s: Session configuration with parameters supported query not "
945 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700946 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700947 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
948 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
949 *supported = false;
950 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700951 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700952 break;
953 case NAME_NOT_FOUND: {
954 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
955 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
956 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
957 *supported = false;
958 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
959 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700960 break;
961 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700962 std::string msg = fmt::sprintf(
963 "Unable to retrieve session configuration support for camera "
964 "device %s: Error: %s (%d)",
965 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700966 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700967 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
968 *supported = false;
969 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700971 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700972 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973}
974
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800975Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000976 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700977 const SessionConfiguration& sessionConfiguration,
978 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000979 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800980 ATRACE_CALL();
981
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800982 if (outMetadata == nullptr) {
983 std::string msg =
984 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
985 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
986 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
987 }
988
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700989 if (!mInitialized) {
990 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
991 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
992 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
993 }
994
Austin Borger65e64642024-06-11 15:58:23 -0700995 std::optional<std::string> cameraIdOptional =
996 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000997 if (!cameraIdOptional.has_value()) {
998 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700999 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001000 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1001 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1002 }
1003 std::string cameraId = cameraIdOptional.value();
1004
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001005 if (shouldRejectSystemCameraConnection(cameraId)) {
1006 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1007 "Unable to retrieve camera"
1008 "characteristics for system only device %s: ",
1009 cameraId.c_str());
1010 }
1011
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001012 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1013 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesheb961c72024-09-25 17:26:26 -07001014
1015 bool sessionConfigSupported;
1016 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1017 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1018 if (!res.isOk()) {
1019 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1020 // report the correct Status to send to the client. Simply forward the error to
1021 // the client.
1022 outMetadata->clear();
1023 return res;
1024 }
1025
1026 if (!sessionConfigSupported) {
1027 std::string msg = fmt::sprintf("Session configuration not supported for camera device %s.",
1028 cameraId.c_str());
1029 outMetadata->clear();
1030 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001031 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001032
1033 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001034 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001035
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001036 switch (ret) {
1037 case OK:
1038 // Expected, no handling needed.
1039 break;
1040 case INVALID_OPERATION: {
1041 std::string msg = fmt::sprintf(
1042 "Camera %s: Session characteristics query not supported!",
1043 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001044 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001045 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1046 outMetadata->clear();
1047 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1048 }
1049 break;
1050 case NAME_NOT_FOUND: {
1051 std::string msg = fmt::sprintf(
1052 "Camera %s: Unknown camera ID.",
1053 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001054 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001055 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1056 outMetadata->clear();
1057 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001058 }
1059 break;
1060 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001061 std::string msg = fmt::sprintf(
1062 "Unable to retrieve session characteristics for camera device %s: "
1063 "Error: %s (%d)",
1064 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001065 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001066 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1067 outMetadata->clear();
1068 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001069 }
1070 }
1071
Avichal Rakesheb961c72024-09-25 17:26:26 -07001072 res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001073 if (flags::analytics_24q3()) {
1074 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1075 getCallingUid(), sessionConfiguration, res);
1076 }
1077 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001078}
1079
1080Status CameraService::filterSensitiveMetadataIfNeeded(
1081 const std::string& cameraId, CameraMetadata* metadata) {
1082 int callingPid = getCallingPid();
1083 int callingUid = getCallingUid();
1084
1085 if (callingPid == getpid()) {
1086 // Caller is cameraserver; no need to remove keys
1087 return Status::ok();
1088 }
1089
1090 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1091 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1092 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1093 metadata->clear();
1094 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1095 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1096 }
1097 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1098 // Attempting to query system only camera without system camera permission would have
1099 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1100 // for a system only camera, then the caller has the required permission.
1101 // No need to remove keys
1102 return Status::ok();
1103 }
1104
1105 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001106 // Get the device id that owns this camera.
1107 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1108 cameraId);
1109 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1110 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001111 if (hasCameraPermission) {
1112 // Caller has camera permission; no need to remove keys
1113 return Status::ok();
1114 }
1115
1116 status_t ret = metadata->removePermissionEntries(
1117 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1118 if (ret != OK) {
1119 metadata->clear();
1120 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1121 "Failed to remove camera characteristics needing camera permission "
1122 "for device %s:%s (%d)",
1123 cameraId.c_str(), strerror(-ret), ret);
1124 }
1125
1126 if (!tagsRemoved.empty()) {
1127 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1128 tagsRemoved.data(), tagsRemoved.size());
1129 if (ret != OK) {
1130 metadata->clear();
1131 return STATUS_ERROR_FMT(
1132 ERROR_INVALID_OPERATION,
1133 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1134 cameraId.c_str(), strerror(-ret), ret);
1135 }
1136 }
1137 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001138}
1139
malikakash22af94c2023-12-04 18:13:14 +00001140Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001141 const std::string& cameraId,
1142 const CameraMetadata& sessionParams) {
1143 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001144 const int pid = getCallingPid();
1145 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001146 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1147 __FUNCTION__, pid, uid);
1148 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1149 "Permission Denial: no permission to inject session params");
1150 }
1151
Biswarup Pal37a75182024-01-16 15:53:35 +00001152 // Do not allow session params injection for a virtual camera.
1153 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1154 if (deviceId != kDefaultDeviceId) {
1155 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1156 "Cannot inject session params for a virtual camera");
1157 }
1158
malikakash22af94c2023-12-04 18:13:14 +00001159 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1160 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1161
1162 auto clientDescriptor = mActiveClientManager.get(cameraId);
1163 if (clientDescriptor == nullptr) {
1164 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1165 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1166 "No active client for camera id %s", cameraId.c_str());
1167 }
1168
1169 sp<BasicClient> clientSp = clientDescriptor->getValue();
1170 status_t res = clientSp->injectSessionParams(sessionParams);
1171
1172 if (res != OK) {
1173 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1174 "Error injecting session params into camera \"%s\": %s (%d)",
1175 cameraId.c_str(), strerror(-res), res);
1176 }
1177 return Status::ok();
1178}
1179
Biswarup Pal37a75182024-01-16 15:53:35 +00001180std::optional<std::string> CameraService::resolveCameraId(
1181 const std::string& inputCameraId,
1182 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001183 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001184 if ((deviceId == kDefaultDeviceId)
1185 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1186 auto [storedDeviceId, _] =
1187 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1188 if (storedDeviceId != kDefaultDeviceId) {
1189 // Trying to access a virtual camera from default-policy device context, we should fail.
1190 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1191 inputCameraId.c_str(), deviceId);
1192 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1193 return std::nullopt;
1194 }
malikakash98260df2024-05-10 23:33:57 +00001195 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001196 }
1197
1198 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1199}
1200
Austin Borger65e64642024-06-11 15:58:23 -07001201Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1202 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1203 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001204 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001205 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001206 std::string cameraIdStr =
1207 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001208 if (cameraIdStr.empty()) {
1209 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001210 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001211 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1212 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1213 }
malikakashedb38962023-09-06 00:03:35 +00001214
Austin Borgered99f642023-06-01 16:51:35 -07001215 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001216 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1217 "characteristics for system only device %s: ", cameraIdStr.c_str());
1218 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001219
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001220 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001221 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001222 return STATUS_ERROR(ERROR_DISCONNECTED,
1223 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001224 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001225 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001226 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001227 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1228 if (hasSystemCameraPermissions) {
1229 cameraIdBound = mNumberOfCameras;
1230 }
1231 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001232 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1233 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001234 }
1235
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001236 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001237 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001238 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001239 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001240 if (err != OK) {
1241 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1242 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1243 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001244 logServiceError(std::string("Error retrieving camera info from device ")
1245 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001246 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001247
Ruben Brunkcc776712015-02-17 20:18:47 -08001248 return ret;
1249}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001250
Biswarup Pal37a75182024-01-16 15:53:35 +00001251std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1252 int32_t deviceId, int32_t devicePolicy) {
1253 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1254 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1255 std::optional<std::string> cameraIdOptional =
1256 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1257 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1258 }
1259
1260 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001261 auto callingPid = getCallingPid();
1262 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001263 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1264 callingPid, callingUid, /* checkCameraPermissions= */ false);
1265 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001266 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001267 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001268 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1269 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1270 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001271 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001272 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001273
malikakash98260df2024-05-10 23:33:57 +00001274 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001275}
1276
Biswarup Pal37a75182024-01-16 15:53:35 +00001277std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1278 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001279 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001280 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001281}
1282
Austin Borgered99f642023-06-01 16:51:35 -07001283Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001284 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1285 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001286 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001287
Zhijun He2b59be82013-09-25 10:14:30 -07001288 if (!cameraInfo) {
1289 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001290 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001291 }
1292
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001293 if (!mInitialized) {
1294 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001295 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001296 return STATUS_ERROR(ERROR_DISCONNECTED,
1297 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001298 }
1299
Austin Borger65e64642024-06-11 15:58:23 -07001300 std::optional<std::string> cameraIdOptional =
1301 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001302 if (!cameraIdOptional.has_value()) {
1303 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001304 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001305 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1306 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1307 }
1308 std::string cameraId = cameraIdOptional.value();
1309
Austin Borgered99f642023-06-01 16:51:35 -07001310 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001311 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001312 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001313 }
1314
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001315 bool overrideForPerfClass =
1316 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001317 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001318 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001319 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001320 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001321 if (res == NAME_NOT_FOUND) {
1322 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001323 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001324 strerror(-res), res);
1325 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001326 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1327 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001328 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001329 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001330 strerror(-res), res);
1331 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001332 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001333
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001334 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001335}
1336
Austin Borger65e64642024-06-11 15:58:23 -07001337Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1338 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001339 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001340 ATRACE_CALL();
1341 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001342
Austin Borger65e64642024-06-11 15:58:23 -07001343 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1344 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001345 if (!cameraIdOptional.has_value()) {
1346 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001347 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001348 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1349 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1350 }
1351 std::string cameraId = cameraIdOptional.value();
1352
Rucha Katakwar38284522021-11-10 11:25:21 -08001353 if (!mInitialized) {
1354 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1355 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1356 }
1357
Biswarup Pal37a75182024-01-16 15:53:35 +00001358 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001359 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1360 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1361 }
1362
Austin Borgered99f642023-06-01 16:51:35 -07001363 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001364 if (res != OK) {
1365 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001366 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001367 strerror(-res), res);
1368 }
1369 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1370 return Status::ok();
1371}
1372
Austin Borgered99f642023-06-01 16:51:35 -07001373std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001374 time_t now = time(nullptr);
1375 char formattedTime[64];
1376 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001377 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001378}
1379
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001380Status CameraService::getCameraVendorTagDescriptor(
1381 /*out*/
1382 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001383 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001384 if (!mInitialized) {
1385 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001386 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001387 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001388 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1389 if (globalDescriptor != nullptr) {
1390 *desc = *(globalDescriptor.get());
1391 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001392 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001393}
1394
Emilian Peev71c73a22017-03-21 16:35:51 +00001395Status CameraService::getCameraVendorTagCache(
1396 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1397 ATRACE_CALL();
1398 if (!mInitialized) {
1399 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1400 return STATUS_ERROR(ERROR_DISCONNECTED,
1401 "Camera subsystem not available");
1402 }
1403 sp<VendorTagDescriptorCache> globalCache =
1404 VendorTagDescriptorCache::getGlobalVendorTagCache();
1405 if (globalCache != nullptr) {
1406 *cache = *(globalCache.get());
1407 }
1408 return Status::ok();
1409}
1410
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001411void CameraService::clearCachedVariables() {
1412 BasicClient::BasicClient::sCameraService = nullptr;
1413}
1414
Austin Borgered99f642023-06-01 16:51:35 -07001415std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001416 int rotationOverride, int* portraitRotation, int* facing,
1417 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001418 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001419
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001420 int deviceVersion = 0;
1421
Emilian Peevf53f66e2017-04-11 14:29:43 +01001422 status_t res;
1423 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001424 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001425 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001426 if (res != OK || transport == IPCTransport::INVALID) {
1427 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001428 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001429 return std::make_pair(-1, IPCTransport::INVALID) ;
1430 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001431 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001432
Emilian Peevf53f66e2017-04-11 14:29:43 +01001433 hardware::CameraInfo info;
1434 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001435 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001436 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001437 if (res != OK) {
1438 return std::make_pair(-1, IPCTransport::INVALID);
1439 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001440 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001441 if (orientation) {
1442 *orientation = info.orientation;
1443 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001444 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001445
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001446 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001447}
1448
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001449Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001450 switch(err) {
1451 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001452 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001453 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001454 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1455 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001456 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001457 return STATUS_ERROR(ERROR_DISCONNECTED,
1458 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001459 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001460 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1461 "Camera HAL encountered error %d: %s",
1462 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001463 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001464}
1465
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001466Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001467 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1468 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001469 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001470 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001471 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001472 bool forceSlowJpegMode, const std::string& originalCameraId,
1473 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001474 // For HIDL devices
1475 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1476 // Create CameraClient based on device version reported by the HAL.
1477 int deviceVersion = deviceVersionAndTransport.first;
1478 switch(deviceVersion) {
1479 case CAMERA_DEVICE_API_VERSION_1_0:
1480 ALOGE("Camera using old HAL version: %d", deviceVersion);
1481 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1482 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001483 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001484 break;
1485 case CAMERA_DEVICE_API_VERSION_3_0:
1486 case CAMERA_DEVICE_API_VERSION_3_1:
1487 case CAMERA_DEVICE_API_VERSION_3_2:
1488 case CAMERA_DEVICE_API_VERSION_3_3:
1489 case CAMERA_DEVICE_API_VERSION_3_4:
1490 case CAMERA_DEVICE_API_VERSION_3_5:
1491 case CAMERA_DEVICE_API_VERSION_3_6:
1492 case CAMERA_DEVICE_API_VERSION_3_7:
1493 break;
1494 default:
1495 // Should not be reachable
1496 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1497 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1498 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001499 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001500 }
1501 }
1502 if (effectiveApiLevel == API_1) { // Camera1 API route
1503 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001504 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001505 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001506 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001507 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001508 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001509 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1510 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001511 } else { // Camera2 API route
1512 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1513 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001514 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001515 cameraService->mCameraServiceProxyWrapper,
1516 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001517 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001518 overrideForPerfClass, rotationOverride, originalCameraId);
1519 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001520 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001521 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001522}
1523
Austin Borgered99f642023-06-01 16:51:35 -07001524std::string CameraService::toString(std::set<userid_t> intSet) {
1525 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001526 bool first = true;
1527 for (userid_t i : intSet) {
1528 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001529 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001530 first = false;
1531 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001532 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001533 }
1534 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001535 return s.str();
Ruben Brunk6267b532015-04-30 17:44:07 -07001536}
1537
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001538int32_t CameraService::mapToInterface(TorchModeStatus status) {
1539 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1540 switch (status) {
1541 case TorchModeStatus::NOT_AVAILABLE:
1542 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1543 break;
1544 case TorchModeStatus::AVAILABLE_OFF:
1545 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1546 break;
1547 case TorchModeStatus::AVAILABLE_ON:
1548 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1549 break;
1550 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001551 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001552 }
1553 return serviceStatus;
1554}
1555
1556CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1557 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1558 switch (status) {
1559 case CameraDeviceStatus::NOT_PRESENT:
1560 serviceStatus = StatusInternal::NOT_PRESENT;
1561 break;
1562 case CameraDeviceStatus::PRESENT:
1563 serviceStatus = StatusInternal::PRESENT;
1564 break;
1565 case CameraDeviceStatus::ENUMERATING:
1566 serviceStatus = StatusInternal::ENUMERATING;
1567 break;
1568 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001569 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001570 }
1571 return serviceStatus;
1572}
1573
1574int32_t CameraService::mapToInterface(StatusInternal status) {
1575 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1576 switch (status) {
1577 case StatusInternal::NOT_PRESENT:
1578 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1579 break;
1580 case StatusInternal::PRESENT:
1581 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1582 break;
1583 case StatusInternal::ENUMERATING:
1584 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1585 break;
1586 case StatusInternal::NOT_AVAILABLE:
1587 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1588 break;
1589 case StatusInternal::UNKNOWN:
1590 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1591 break;
1592 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001593 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001594 }
1595 return serviceStatus;
1596}
1597
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001598Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001599 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001600
Austin Borgered99f642023-06-01 16:51:35 -07001601 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001602 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001603 sp<Client> tmp = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07001604
Austin Borgerb01a8702024-07-22 16:20:34 -07001605 int callingPid = getCallingPid();
1606 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001607
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001609 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001610 kServiceName, /*systemNativeClient*/ false, {}, uid, callingPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001611 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001612 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1613 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borger7d2b9232024-07-22 14:17:14 -07001614 /*forceSlowJpegMode*/false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001615 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001616 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001617 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001618 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001619}
1620
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001621Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001622 /*out*/
1623 CameraParameters* parameters) {
1624
1625 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1626
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001628
1629 if (parameters == NULL) {
1630 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001632 }
1633
malikakash98260df2024-05-10 23:33:57 +00001634 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001635
1636 // Check if we already have parameters
1637 {
1638 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001639 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001640 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001641 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001642 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001643 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001644 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001645 }
1646 CameraParameters p = cameraState->getShimParams();
1647 if (!p.isEmpty()) {
1648 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001649 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001650 }
1651 }
1652
Austin Borger22c5c852024-03-08 13:31:36 -08001653 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001654 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001655 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001656 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001657 // Error already logged by callee
1658 return ret;
1659 }
1660
1661 // Check for parameters again
1662 {
1663 // Scope for service lock
1664 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001665 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001666 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001667 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001668 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001669 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001670 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001671 CameraParameters p = cameraState->getShimParams();
1672 if (!p.isEmpty()) {
1673 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001674 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001675 }
1676 }
1677
Ruben Brunkcc776712015-02-17 20:18:47 -08001678 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1679 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001680 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001681}
1682
Austin Borgered99f642023-06-01 16:51:35 -07001683Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001684 const std::string& clientName8, int clientUid, int clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001685
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001686#ifdef __BRILLO__
1687 UNUSED(clientName8);
1688 UNUSED(clientUid);
1689 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001690#else
Austin Borger6e831c42024-07-22 13:07:56 -07001691 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001692 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001693 return allowed;
1694 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001695#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001696
Austin Borger22c5c852024-03-08 13:31:36 -08001697 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001698
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001699 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001700 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1701 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001702 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001703 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001704 }
1705
Ruben Brunkcc776712015-02-17 20:18:47 -08001706 if (getCameraState(cameraId) == nullptr) {
1707 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001708 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001709 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001710 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001711 }
1712
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001713 status_t err = checkIfDeviceIsUsable(cameraId);
1714 if (err != NO_ERROR) {
1715 switch(err) {
1716 case -ENODEV:
1717 case -EBUSY:
1718 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001719 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001720 default:
1721 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001722 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001723 }
1724 }
1725 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001726}
1727
Austin Borgerb01a8702024-07-22 16:20:34 -07001728Status CameraService::errorNotTrusted(int clientPid, int clientUid, const std::string& cameraId,
1729 const std::string& clientName, bool isPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001730 int callingPid = getCallingPid();
1731 int callingUid = getCallingUid();
Austin Borgerb01a8702024-07-22 16:20:34 -07001732 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1733 "(don't trust %s %d)", callingPid, callingUid, isPid ? "clientPid" : "clientUid",
1734 isPid ? clientPid : clientUid);
1735 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1736 "Untrusted caller (calling PID %d, UID %d) trying to "
1737 "forward camera access to camera %s for client %s (PID %d, UID %d)",
1738 getCallingPid(), getCallingUid(), cameraId.c_str(),
1739 clientName.c_str(), clientPid, clientUid);
1740}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001741
Austin Borgerb01a8702024-07-22 16:20:34 -07001742Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1743 const std::string& clientName, int clientUid, int clientPid) const {
1744 int callingPid = getCallingPid();
1745 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001746
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001747 if (shouldRejectSystemCameraConnection(cameraId)) {
1748 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1749 cameraId.c_str());
1750 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001751 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001752 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001753 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1754 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001755 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001756 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001757 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001758 }
1759
Biswarup Pale506e732024-03-27 13:46:20 +00001760 // Get the device id that owns this camera.
1761 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1762
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001763 // If it's not calling from cameraserver, check the permission if the
1764 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1765 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001766 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001767 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001768 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001769 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001770 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001771 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1772 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001773 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001774 }
1775
Svet Ganova453d0d2018-01-11 15:37:58 -08001776 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001777 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001778 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001779 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1780 clientPid, clientUid);
1781 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001782 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1783 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001784 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001785 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001786 }
1787
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001788 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1789 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1790 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1791 if ((!isAutomotivePrivilegedClient(callingUid) ||
1792 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1793 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001794 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1795 return STATUS_ERROR_FMT(ERROR_DISABLED,
1796 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001797 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001798 }
1799
Austin Borger6e831c42024-07-22 13:07:56 -07001800 userid_t clientUserId = multiuser_get_user_id(clientUid);
1801
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001802 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1803 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001804
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001805 // For non-system clients : Only allow clients who are being used by the current foreground
1806 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001807 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001808 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001809 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1810 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001811 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001812 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1813 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001814 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001815 }
1816
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001817 if (flags::camera_hsum_permission()) {
1818 // If the System User tries to access the camera when the device is running in
1819 // headless system user mode, ensure that client has the required permission
1820 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001821 if (isHeadlessSystemUserMode()
1822 && (clientUserId == USER_SYSTEM)
1823 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001824 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001825 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1826 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1827 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001828 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001829 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001830 }
1831
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001832 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001833}
1834
Austin Borgered99f642023-06-01 16:51:35 -07001835status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001836 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001837 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001838 if (cameraState == nullptr) {
1839 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001840 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001841 return -ENODEV;
1842 }
1843
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001844 StatusInternal currentStatus = cameraState->getStatus();
1845 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001846 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001847 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001848 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001849 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001850 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001851 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001852 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001853 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001854
Ruben Brunkcc776712015-02-17 20:18:47 -08001855 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001856}
1857
Ruben Brunkcc776712015-02-17 20:18:47 -08001858void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001859 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001860
Ruben Brunkcc776712015-02-17 20:18:47 -08001861 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001862 auto clientDescriptor =
1863 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001864 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001865 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1866
1867 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001868 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001869
1870 if (evicted.size() > 0) {
1871 // This should never happen - clients should already have been removed in disconnect
1872 for (auto& i : evicted) {
1873 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001874 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001875 }
1876
1877 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1878 __FUNCTION__);
1879 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001880
1881 // And register a death notification for the client callback. Do
1882 // this last to avoid Binder policy where a nested Binder
1883 // transaction might be pre-empted to service the client death
1884 // notification if the client process dies before linkToDeath is
1885 // invoked.
1886 sp<IBinder> remoteCallback = client->getRemote();
1887 if (remoteCallback != nullptr) {
1888 remoteCallback->linkToDeath(this);
1889 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001890}
1891
Austin Borgered99f642023-06-01 16:51:35 -07001892status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1893 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1894 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001895 /*out*/
1896 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001897 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001898 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001899 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001900 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001901 DescriptorPtr clientDescriptor;
1902 {
1903 if (effectiveApiLevel == API_1) {
1904 // If we are using API1, any existing client for this camera ID with the same remote
1905 // should be returned rather than evicted to allow MediaRecorder to work properly.
1906
1907 auto current = mActiveClientManager.get(cameraId);
1908 if (current != nullptr) {
1909 auto clientSp = current->getValue();
1910 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001911 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001912 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001913 " API level, evicting prior client...");
1914 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001915 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001916 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001917 *client = clientSp;
1918 return NO_ERROR;
1919 }
1920 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001921 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001922 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001923
Ruben Brunkcc776712015-02-17 20:18:47 -08001924 // Get state for the given cameraId
1925 auto state = getCameraState(cameraId);
1926 if (state == nullptr) {
1927 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001928 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001929 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001930 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001931 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001932
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001933 sp<IServiceManager> sm = defaultServiceManager();
1934 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001935 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001936 // If processinfo service is not available and the client is automotive privileged
1937 // client used for safety critical uses cases such as rear-view and surround-view which
1938 // needs to be available before android boot completes, then use the hardcoded values
1939 // for the process state and priority score. As this scenario is before android system
1940 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1941 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1942 // visible on the top.
1943 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1944 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1945 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1946 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1947 } else {
1948 // Get current active client PIDs
1949 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1950 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001951
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001952 std::vector<int> priorityScores(ownerPids.size());
1953 std::vector<int> states(ownerPids.size());
1954
1955 // Get priority scores of all active PIDs
1956 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1957 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1958 if (err != OK) {
1959 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1960 return err;
1961 }
1962
1963 // Update all active clients' priorities
1964 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1965 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1966 pidToPriorityMap.emplace(ownerPids[i],
1967 resource_policy::ClientPriority(priorityScores[i], states[i],
1968 /* isVendorClient won't get copied over*/ false,
1969 /* oomScoreOffset won't get copied over*/ 0));
1970 }
1971 mActiveClientManager.updatePriorities(pidToPriorityMap);
1972
1973 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1974 int32_t actualState = states[states.size() - 1];
1975
1976 // Make descriptor for incoming client. We store the oomScoreOffset
1977 // since we might need it later on new handleEvictionsLocked and
1978 // ProcessInfoService would not take that into account.
1979 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1980 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1981 state->getConflicting(), actualScore, clientPid, actualState,
1982 oomScoreOffset, systemNativeClient);
1983 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001984
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001985 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1986
Ruben Brunkcc776712015-02-17 20:18:47 -08001987 // Find clients that would be evicted
1988 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1989
1990 // If the incoming client was 'evicted,' higher priority clients have the camera in the
1991 // background, so we cannot do evictions
1992 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
1993 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
1994 " priority).", clientPid);
1995
1996 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07001997 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08001998 auto incompatibleClients =
1999 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2000
Austin Borgered99f642023-06-01 16:51:35 -07002001 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2002 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2003 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002004 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002005
2006 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002007 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002008 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002009 i->getKey().c_str(),
2010 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002011 i->getOwnerId(), i->getPriority().getScore(),
2012 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002013 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002014 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2015 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002016 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002017 }
2018
2019 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002020 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002021 mEventLog.add(msg);
2022
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002023 auto current = mActiveClientManager.get(cameraId);
2024 if (current != nullptr) {
2025 return -EBUSY; // CAMERA_IN_USE
2026 } else {
2027 return -EUSERS; // MAX_CAMERAS_IN_USE
2028 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002029 }
2030
2031 for (auto& i : evicted) {
2032 sp<BasicClient> clientSp = i->getValue();
2033 if (clientSp.get() == nullptr) {
2034 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2035
2036 // TODO: Remove this
2037 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2038 __FUNCTION__);
2039 mActiveClientManager.remove(i);
2040 continue;
2041 }
2042
2043 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002044 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002045 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002046
Ruben Brunkcc776712015-02-17 20:18:47 -08002047 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002048 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002049 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2050 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002051 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002052 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002053 i->getPriority().getState(), cameraId.c_str(),
2054 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002055 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002056
2057 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002058 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002059 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002060 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002061 }
2062
Ruben Brunkcc776712015-02-17 20:18:47 -08002063 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2064 // other clients from connecting in mServiceLockWrapper if held
2065 mServiceLock.unlock();
2066
2067 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002068 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002069
2070 // Destroy evicted clients
2071 for (auto& i : evictedClients) {
2072 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002073 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002074 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002075
Austin Borger22c5c852024-03-08 13:31:36 -08002076 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002077
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002078 for (const auto& i : evictedClients) {
2079 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002080 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002081 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2082 if (ret == TIMED_OUT) {
2083 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002084 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2085 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002086 return -EBUSY;
2087 }
2088 if (ret != NO_ERROR) {
2089 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002090 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2091 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002092 return ret;
2093 }
2094 }
2095
2096 evictedClients.clear();
2097
Ruben Brunkcc776712015-02-17 20:18:47 -08002098 // Once clients have been disconnected, relock
2099 mServiceLock.lock();
2100
2101 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2102 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2103 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002104 }
2105
Ruben Brunkcc776712015-02-17 20:18:47 -08002106 *partial = clientDescriptor;
2107 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002108}
2109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002110Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002111 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002112 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002113 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002114 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002115 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002116 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002117 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002118 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002119 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002120 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002121 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002122
Austin Borger65e64642024-06-11 15:58:23 -07002123 std::string cameraIdStr =
2124 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002125 if (cameraIdStr.empty()) {
2126 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002127 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002128 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2129 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2130 }
malikakashedb38962023-09-06 00:03:35 +00002131
Austin Borger7d2b9232024-07-22 14:17:14 -07002132 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2133 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2134 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2135 clientPackageNameMaybe);
2136 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraIdStr, API_1);
2137
Austin Borgerb01a8702024-07-22 16:20:34 -07002138 int clientUid = clientAttribution.uid;
2139 int clientPid = clientAttribution.pid;
2140
2141 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2142 // need a way to guarantee the caller identity early.
2143
2144 // Check if we can trust clientUid
2145 if (!resolveClientUid(clientUid)) {
2146 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2147 /* isPid=*/ false);
2148 }
2149
2150 // Check if we can trust clientUid
2151 if (!resolveClientPid(clientPid)) {
2152 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2153 /* isPid= */ true);
2154 }
2155
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 Borger7d2b9232024-07-22 14:17:14 -07002158 clientPackageName, /*systemNativeClient*/ false, {},
Austin Borgerb01a8702024-07-22 16:20:34 -07002159 clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002160 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borger7d2b9232024-07-22 14:17:14 -07002161 rotationOverride, forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002162
Biswarup Pal37a75182024-01-16 15:53:35 +00002163 if (!ret.isOk()) {
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002164 logRejected(cameraIdStr, getCallingPid(), clientAttribution.packageName.value_or(""),
2165 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002166 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002167 }
2168
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002169 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002170
2171 const sp<IServiceManager> sm(defaultServiceManager());
2172 const auto& mActivityManager = getActivityManager();
2173 if (mActivityManager) {
2174 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002175 getCallingUid(),
2176 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002177 }
2178
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002179 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002180}
2181
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002182bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2183 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002184 // If the client is not a vendor client, don't add listener if
2185 // a) the camera is a publicly hidden secure camera OR
2186 // b) the camera is a system only camera and the client doesn't
2187 // have android.permission.SYSTEM_CAMERA permissions.
2188 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2189 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002190 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002191 return true;
2192 }
2193 return false;
2194}
2195
Austin Borgered99f642023-06-01 16:51:35 -07002196bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002197 // Rules for rejection:
2198 // 1) If cameraserver tries to access this camera device, accept the
2199 // connection.
2200 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002201 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002202 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2203 // and the serving thread is a non hwbinder thread, the client must have
2204 // android.permission.SYSTEM_CAMERA permissions to connect.
2205
Austin Borger22c5c852024-03-08 13:31:36 -08002206 int cPid = getCallingPid();
2207 int cUid = getCallingUid();
2208 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002209 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2210 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002211 // This isn't a known camera ID, so it's not a system camera
2212 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2213 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002214 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002215
2216 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002217 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002218 return false;
2219 }
2220 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002221 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002222 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2223 return true;
2224 }
2225 // (3) Here we only check for permissions if it is a system only camera device. This is since
2226 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2227 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2228 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002229 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002230 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002231 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2232 cameraId.c_str());
2233 return true;
2234 }
2235
2236 return false;
2237}
2238
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239Status CameraService::connectDevice(
2240 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002241 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002242 int oomScoreOffset, int targetSdkVersion,
2243 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002244 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002245 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002246 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002247 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002248 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002249 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002250 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002251 int callingPid = getCallingPid();
2252 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002253 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002254 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002255 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002256 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002257 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002258 }
Austin Borger249e6592024-03-10 22:28:11 -07002259
Austin Borger65e64642024-06-11 15:58:23 -07002260 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2261 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002262 if (!cameraIdOptional.has_value()) {
2263 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002264 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002265 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2266 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2267 }
2268 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002269
Austin Borger7d2b9232024-07-22 14:17:14 -07002270 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2271 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2272 clientPackageNameMaybe);
2273 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraId, API_2);
2274
Austin Borgerb01a8702024-07-22 16:20:34 -07002275 userid_t clientUserId = multiuser_get_user_id(clientAttribution.uid);
2276 if (clientAttribution.uid == USE_CALLING_UID) {
2277 clientUserId = multiuser_get_user_id(callingUid);
2278 }
2279
2280 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2281 // need a way to guarantee the caller identity early.
2282
2283 int clientUid = clientAttribution.uid;
2284 int clientPid = callingPid;
2285 // Check if we can trust clientUid
2286 if (!resolveClientUid(clientUid)) {
2287 return errorNotTrusted(clientPid, clientUid, cameraId, clientPackageName,
2288 /* isPid= */ false);
2289 }
2290
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002291 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002292 std::string msg =
2293 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
Austin Borger7d2b9232024-07-22 14:17:14 -07002294 "camera id %s", clientPackageName.c_str(), callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002295 cameraId.c_str());
2296 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2297 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002298 }
2299
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002300 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2301 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002302 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2303 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002304 std::string msg = "Camera disabled by device policy";
2305 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2306 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002307 }
2308
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002309 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002310 if (oomScoreOffset > 0
2311 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002312 callingUid)
2313 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002314 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002315 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borger7d2b9232024-07-22 14:17:14 -07002316 clientPackageName.c_str(), callingPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002317 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2318 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002319 }
2320
Austin Borgered99f642023-06-01 16:51:35 -07002321 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
Austin Borger7d2b9232024-07-22 14:17:14 -07002322 cameraId, /*api1CameraId*/-1, clientPackageName, systemNativeClient,
Austin Borgerb01a8702024-07-22 16:20:34 -07002323 clientAttribution.attributionTag, clientUid, clientPid, API_2,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002324 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger7d2b9232024-07-22 14:17:14 -07002325 /*forceSlowJpegMode*/false, unresolvedCameraId, isNonSystemNdk, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002326
Biswarup Pal37a75182024-01-16 15:53:35 +00002327 if (!ret.isOk()) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002328 logRejected(cameraId, callingPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002329 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002330 }
2331
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002332 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002333 Mutex::Autolock lock(mServiceLock);
2334
2335 // Clear the previous cached logs and reposition the
2336 // file offset to beginning of the file to log new data.
2337 // If either truncate or lseek fails, close the previous file and create a new one.
2338 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2339 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2340 // Close the previous memfd.
2341 close(mMemFd);
2342 // If failure to wipe the data, then create a new file and
2343 // assign the new value to mMemFd.
2344 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2345 if (mMemFd == -1) {
2346 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2347 }
2348 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002349 const sp<IServiceManager> sm(defaultServiceManager());
2350 const auto& mActivityManager = getActivityManager();
2351 if (mActivityManager) {
2352 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002353 callingUid,
2354 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002355 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002356 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002357}
2358
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002359bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2360 int callingPid, int callingUid) {
2361 if (!isAutomotiveDevice()) {
2362 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2363 }
2364
2365 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2366 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2367 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2368 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2369 "using camera %s", callingUid, cam_id.c_str());
2370 return false;
2371 }
2372
2373 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2374 return true;
2375 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2376 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002377 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2378 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002379 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2380 return false;
2381 } else {
2382 return true;
2383 }
2384 }
2385 return false;
2386}
2387
Austin Borger7d2b9232024-07-22 14:17:14 -07002388void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
2389 const std::string& cameraId, apiLevel effectiveApiLevel) const {
2390 int packagePid = (clientPid == USE_CALLING_PID) ?
2391 getCallingPid() : clientPid;
2392 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
2393 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
2394 static_cast<int>(effectiveApiLevel));
2395}
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002396
Austin Borger7d2b9232024-07-22 14:17:14 -07002397std::string CameraService::resolvePackageName(int clientUid,
2398 const std::string& clientPackageNameMaybe) const {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002399 if (clientPackageNameMaybe.size() <= 0) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002400 int packageUid = (clientUid == USE_CALLING_UID) ?
2401 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002402 // NDK calls don't come with package names, but we need one for various cases.
2403 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2404 // do exist. For all authentication cases, all packages under the same UID get the
2405 // same permissions, so picking any associated package name is sufficient. For some
2406 // other cases, this may give inaccurate names for clients in logs.
Austin Borger7d2b9232024-07-22 14:17:14 -07002407 return getPackageNameFromUid(packageUid);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002408 } else {
Austin Borger7d2b9232024-07-22 14:17:14 -07002409 return clientPackageNameMaybe;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002410 }
Austin Borger7d2b9232024-07-22 14:17:14 -07002411}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002412
Austin Borger7d2b9232024-07-22 14:17:14 -07002413template<class CALLBACK, class CLIENT>
2414Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2415 int api1CameraId, const std::string& clientPackageName, bool systemNativeClient,
2416 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2417 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2418 int rotationOverride, bool forceSlowJpegMode,
2419 const std::string& originalCameraId, bool isNonSystemNdk, /*out*/sp<CLIENT>& device) {
2420 binder::Status ret = binder::Status::ok();
2421
2422 int packageUid = (clientUid == USE_CALLING_UID) ?
2423 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002424 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger7d2b9232024-07-22 14:17:14 -07002425 getCallingPid() : clientPid;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002426
Shuzhen Wang316781a2020-08-18 18:11:01 -07002427 nsecs_t openTimeNs = systemTime();
2428
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002429 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002430 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002431 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002432
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002433 {
2434 // Acquire mServiceLock and prevent other clients from connecting
2435 std::unique_ptr<AutoConditionLock> lock =
2436 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2437
2438 if (lock == nullptr) {
2439 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2440 , clientPid);
2441 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2442 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002443 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002444 }
2445
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002446 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002447 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002448 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002449 return ret;
2450 }
2451
2452 // Check the shim parameters after acquiring lock, if they have already been updated and
2453 // we were doing a shim update, return immediately
2454 if (shimUpdateOnly) {
2455 auto cameraState = getCameraState(cameraId);
2456 if (cameraState != nullptr) {
2457 if (!cameraState->getShimParams().isEmpty()) return ret;
2458 }
2459 }
2460
2461 status_t err;
2462
2463 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002464 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002465 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002466 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2467 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002468 switch (err) {
2469 case -ENODEV:
2470 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2471 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002472 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002473 case -EBUSY:
2474 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2475 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002476 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002477 case -EUSERS:
2478 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2479 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002480 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002481 default:
2482 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2483 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002484 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002485 }
2486 }
2487
2488 if (clientTmp.get() != nullptr) {
2489 // Handle special case for API1 MediaRecorder where the existing client is returned
2490 device = static_cast<CLIENT*>(clientTmp.get());
2491 return ret;
2492 }
2493
2494 // give flashlight a chance to close devices if necessary.
2495 mFlashlight->prepareDeviceOpen(cameraId);
2496
Austin Borger18b30a72022-10-27 12:20:29 -07002497 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002498 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002499 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002500 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002501 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002502 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002503 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002504 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002505 }
2506
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002507 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002508 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002509 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002510
Austin Borger6e831c42024-07-22 13:07:56 -07002511 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2512 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002513 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002514 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger7d2b9232024-07-22 14:17:14 -07002515 orientation, getCallingPid(), clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002516 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002517 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002518 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002519 return ret;
2520 }
2521 client = static_cast<CLIENT*>(tmp.get());
2522
2523 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2524 __FUNCTION__);
2525
Austin Borgered99f642023-06-01 16:51:35 -07002526 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002527 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002528 if (err != OK) {
2529 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002530 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002531 mServiceLock.unlock();
2532 client->disconnect();
2533 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002534 switch(err) {
2535 case BAD_VALUE:
2536 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002537 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002538 case -EBUSY:
2539 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002540 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002541 case -EUSERS:
2542 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2543 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002544 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002545 case PERMISSION_DENIED:
2546 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002547 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002548 case -EACCES:
2549 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002550 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002551 case -ENODEV:
2552 default:
2553 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002554 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002555 strerror(-err), err);
2556 }
2557 }
2558
2559 // Update shim paremeters for legacy clients
2560 if (effectiveApiLevel == API_1) {
2561 // Assume we have always received a Client subclass for API1
2562 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2563 String8 rawParams = shimClient->getParameters();
2564 CameraParameters params(rawParams);
2565
2566 auto cameraState = getCameraState(cameraId);
2567 if (cameraState != nullptr) {
2568 cameraState->setShimParams(params);
2569 } else {
2570 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002571 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002572 }
2573 }
2574
Ravneetaeb20dc2022-03-30 05:33:03 +00002575 // Enable/disable camera service watchdog
2576 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2577
Emilian Peev6d45db82024-01-18 20:11:54 +00002578 CameraMetadata chars;
2579 bool rotateAndCropSupported = true;
2580 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002581 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002582 if (err == OK) {
2583 auto availableRotateCropEntry = chars.find(
2584 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2585 if (availableRotateCropEntry.count <= 1) {
2586 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002587 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002588 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002589 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2590 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002591 }
2592
Emilian Peev6d45db82024-01-18 20:11:54 +00002593 if (rotateAndCropSupported) {
2594 // Set rotate-and-crop override behavior
2595 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2596 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002597 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2598 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002599 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2600 switch (portraitRotation) {
2601 case 90:
2602 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2603 break;
2604 case 180:
2605 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2606 break;
2607 case 270:
2608 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2609 break;
2610 default:
2611 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2612 break;
2613 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002614 // Here we're communicating to the client the chosen rotate
2615 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002616 client->setRotateAndCropOverride(rotateAndCropMode);
2617 } else {
2618 client->setRotateAndCropOverride(
2619 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2620 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2621 }
2622 }
2623
2624 bool autoframingSupported = true;
2625 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2626 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2627 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2628 autoframingSupported = false;
2629 }
2630
2631 if (autoframingSupported) {
2632 // Set autoframing override behaviour
2633 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2634 client->setAutoframingOverride(mOverrideAutoframingMode);
2635 } else {
2636 client->setAutoframingOverride(
2637 mCameraServiceProxyWrapper->getAutoframingOverride(
2638 clientPackageName));
2639 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002640 }
2641
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002642 bool isCameraPrivacyEnabled;
2643 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002644 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002645 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2646 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2647 } else {
2648 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002649 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002650 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002651
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002652 if (client->supportsCameraMute()) {
2653 client->setCameraMute(
2654 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2655 } else if (isCameraPrivacyEnabled) {
2656 // no camera mute supported, but privacy is on! => disconnect
2657 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2658 client->getPackageName().c_str(), cameraId.c_str());
2659 // Do not hold mServiceLock while disconnecting clients, but
2660 // retain the condition blocking other clients from connecting
2661 // in mServiceLockWrapper if held.
2662 mServiceLock.unlock();
2663 // Clear caller identity temporarily so client disconnect PID
2664 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002665 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002666 // Note AppOp to trigger the "Unblock" dialog
2667 client->noteAppOp();
2668 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002669 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002670 // Reacquire mServiceLock
2671 mServiceLock.lock();
2672
2673 return STATUS_ERROR_FMT(ERROR_DISABLED,
2674 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002675 }
2676
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002677 if (shimUpdateOnly) {
2678 // If only updating legacy shim parameters, immediately disconnect client
2679 mServiceLock.unlock();
2680 client->disconnect();
2681 mServiceLock.lock();
2682 } else {
2683 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002684 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002685 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002686
2687 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002688 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002689 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002690 } // lock is destroyed, allow further connect calls
2691
2692 // Important: release the mutex here so the client can call back into the service from its
2693 // destructor (can be at the end of the call)
2694 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002695
2696 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002697 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002698 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002699
Cliff Wud3a05312021-04-26 23:07:31 +08002700 {
2701 Mutex::Autolock lock(mInjectionParametersLock);
2702 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2703 mInjectionInitPending = false;
2704 status_t res = NO_ERROR;
2705 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2706 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002707 sp<BasicClient> clientSp = clientDescriptor->getValue();
2708 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2709 if(res != OK) {
2710 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2711 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002712 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002713 }
2714 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002715 if (res != OK) {
2716 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2717 }
2718 } else {
2719 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002720 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002721 res = NO_INIT;
2722 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2723 }
2724 }
2725 }
2726
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002727 return ret;
2728}
2729
Austin Borgered99f642023-06-01 16:51:35 -07002730status_t CameraService::addOfflineClient(const std::string &cameraId,
2731 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002732 if (offlineClient.get() == nullptr) {
2733 return BAD_VALUE;
2734 }
2735
2736 {
2737 // Acquire mServiceLock and prevent other clients from connecting
2738 std::unique_ptr<AutoConditionLock> lock =
2739 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2740
2741 if (lock == nullptr) {
2742 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2743 , __FUNCTION__, offlineClient->getClientPid());
2744 return TIMED_OUT;
2745 }
2746
2747 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2748 if (onlineClientDesc.get() == nullptr) {
2749 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2750 cameraId.c_str());
2751 return BAD_VALUE;
2752 }
2753
2754 // Offline clients do not evict or conflict with other online devices. Resource sharing
2755 // conflicts are handled by the camera provider which will either succeed or fail before
2756 // reaching this method.
2757 const auto& onlinePriority = onlineClientDesc->getPriority();
2758 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2759 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002760 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002761 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002762 // native clients don't have offline processing support.
2763 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002764 if (offlineClientDesc == nullptr) {
2765 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2766 return BAD_VALUE;
2767 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002768
2769 // Allow only one offline device per camera
2770 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2771 if (!incompatibleClients.empty()) {
2772 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2773 return BAD_VALUE;
2774 }
2775
Austin Borgered99f642023-06-01 16:51:35 -07002776 std::string monitorTags = isClientWatched(offlineClient.get())
2777 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002778 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002779 if (err != OK) {
2780 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2781 return err;
2782 }
2783
2784 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2785 if (evicted.size() > 0) {
2786 for (auto& i : evicted) {
2787 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002788 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002789 }
2790
2791 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2792 "properly", __FUNCTION__);
2793
2794 return BAD_VALUE;
2795 }
2796
2797 logConnectedOffline(offlineClientDesc->getKey(),
2798 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002799 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002800
2801 sp<IBinder> remoteCallback = offlineClient->getRemote();
2802 if (remoteCallback != nullptr) {
2803 remoteCallback->linkToDeath(this);
2804 }
2805 } // lock is destroyed, allow further connect calls
2806
2807 return OK;
2808}
2809
Austin Borgered99f642023-06-01 16:51:35 -07002810Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002811 int32_t torchStrength, const sp<IBinder>& clientBinder,
2812 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002813 Mutex::Autolock lock(mServiceLock);
2814
2815 ATRACE_CALL();
2816 if (clientBinder == nullptr) {
2817 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2818 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2819 "Torch client binder in null.");
2820 }
2821
Austin Borger22c5c852024-03-08 13:31:36 -08002822 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002823 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2824 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002825 if (!cameraIdOptional.has_value()) {
2826 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002827 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002828 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2829 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2830 }
2831 std::string cameraId = cameraIdOptional.value();
2832
Austin Borgered99f642023-06-01 16:51:35 -07002833 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002834 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002835 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002836 }
2837
2838 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002839 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002840 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002841 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002842 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002843 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002844 }
2845
2846 StatusInternal cameraStatus = state->getStatus();
2847 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2848 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002849 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002850 (int)cameraStatus);
2851 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002852 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002853 }
2854
2855 {
2856 Mutex::Autolock al(mTorchStatusMutex);
2857 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002858 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002859 if (err != OK) {
2860 if (err == NAME_NOT_FOUND) {
2861 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002862 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002863 }
2864 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002865 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002866 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2867 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002868 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002869 }
2870
2871 if (status == TorchModeStatus::NOT_AVAILABLE) {
2872 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2873 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002874 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002875 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2876 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002877 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002878 } else {
2879 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002880 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002881 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2882 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002883 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002884 }
2885 }
2886 }
2887
2888 {
2889 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002890 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002891 }
2892 // Check if the current torch strength level is same as the new one.
2893 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002894 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002895
Austin Borgered99f642023-06-01 16:51:35 -07002896 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002897
2898 if (err != OK) {
2899 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002900 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002901 switch (err) {
2902 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002903 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2904 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002905 errorCode = ERROR_ILLEGAL_ARGUMENT;
2906 break;
2907 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002908 msg = fmt::sprintf("Camera \"%s\" is in use",
2909 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002910 errorCode = ERROR_CAMERA_IN_USE;
2911 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002912 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002913 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002914 "valid range.", torchStrength);
2915 errorCode = ERROR_ILLEGAL_ARGUMENT;
2916 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002917 default:
Austin Borgered99f642023-06-01 16:51:35 -07002918 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002919 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002920 }
Austin Borgered99f642023-06-01 16:51:35 -07002921 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2922 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002923 }
2924
2925 {
2926 // update the link to client's death
2927 // Store the last client that turns on each camera's torch mode.
2928 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002929 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002930 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002931 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002932 } else {
2933 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2934 mTorchClientMap.replaceValueAt(index, clientBinder);
2935 }
2936 clientBinder->linkToDeath(this);
2937 }
2938
Austin Borger22c5c852024-03-08 13:31:36 -08002939 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002940 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002941 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002942 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002943 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002944 }
2945 return Status::ok();
2946}
2947
malikakash73125c62023-07-21 22:44:34 +00002948Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002949 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2950 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002951 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002952
2953 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002954 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002955 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002956 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2957 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002958 }
2959
Austin Borger22c5c852024-03-08 13:31:36 -08002960 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002961 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2962 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002963 if (!cameraIdOptional.has_value()) {
2964 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002965 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002966 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2967 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2968 }
2969 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002970
Austin Borgered99f642023-06-01 16:51:35 -07002971 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002972 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002973 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002974 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002975 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002976 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002977 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002978 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002979 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002980 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002981 }
2982
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002983 StatusInternal cameraStatus = state->getStatus();
2984 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08002985 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07002986 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
2987 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002988 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002989 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002990 }
2991
2992 {
2993 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002994 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002995 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002996 if (err != OK) {
2997 if (err == NAME_NOT_FOUND) {
2998 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002999 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003000 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003001 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003002 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003003 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003004 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003005 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003006 }
3007
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003008 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003009 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003010 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003011 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003012 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3013 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003014 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003015 } else {
3016 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003017 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003018 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3019 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003020 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003021 }
3022 }
3023 }
3024
Ruben Brunk99e69712015-05-26 17:25:07 -07003025 {
3026 // Update UID map - this is used in the torch status changed callbacks, so must be done
3027 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003028 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003029 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003030 }
3031
Austin Borgered99f642023-06-01 16:51:35 -07003032 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003033
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 if (err != OK) {
3035 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003036 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003037 switch (err) {
3038 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003039 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3040 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003041 errorCode = ERROR_ILLEGAL_ARGUMENT;
3042 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003043 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003044 msg = fmt::sprintf("Camera \"%s\" is in use",
3045 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003046 errorCode = ERROR_CAMERA_IN_USE;
3047 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003048 default:
Austin Borgered99f642023-06-01 16:51:35 -07003049 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003050 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003051 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003052 errorCode = ERROR_INVALID_OPERATION;
3053 }
Austin Borgered99f642023-06-01 16:51:35 -07003054 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3055 logServiceError(msg, errorCode);
3056 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003057 }
3058
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003059 {
3060 // update the link to client's death
3061 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003062 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003063 if (enabled) {
3064 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003065 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003066 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003067 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003068 mTorchClientMap.replaceValueAt(index, clientBinder);
3069 }
3070 clientBinder->linkToDeath(this);
3071 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003072 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003073 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003074 }
3075
Austin Borger22c5c852024-03-08 13:31:36 -08003076 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003077 std::string torchState = enabled ? "on" : "off";
3078 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3079 torchState.c_str(), clientPid);
3080 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003081 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003082}
3083
Austin Borgered99f642023-06-01 16:51:35 -07003084void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3085 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3086 mTorchUidMap[cameraId].first = uid;
3087 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003088 } else {
3089 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003090 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003091 }
3092}
3093
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003094Status CameraService::notifySystemEvent(int32_t eventId,
3095 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003096 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003097 const int selfPid = getpid();
3098
3099 // Permission checks
3100 if (pid != selfPid) {
3101 // Ensure we're being called by system_server, or similar process with
3102 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003103 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003104 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003105 ALOGE("Permission Denial: cannot send updates to camera service about system"
3106 " events from pid=%d, uid=%d", pid, uid);
3107 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003108 "No permission to send updates to camera service about system events"
3109 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003110 }
3111 }
3112
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003113 ATRACE_CALL();
3114
Ruben Brunk36597b22015-03-20 22:15:57 -07003115 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003116 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003117 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003118 // from a system server crash
3119 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003120 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003121 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003122 break;
3123 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003124 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3125 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003126 if (args.size() != 1) {
3127 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3128 "USB Device Event requires 1 argument");
3129 }
3130
Valentin Iftime29e2e152021-08-13 15:17:33 +02003131 // Notify CameraProviderManager for lazy HALs
3132 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3133 std::to_string(args[0]));
3134 break;
3135 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003136 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003137 default: {
3138 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3139 eventId);
3140 break;
3141 }
3142 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003143 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003144}
3145
Emilian Peev53722fa2019-02-22 17:47:20 -08003146void CameraService::notifyMonitoredUids() {
3147 Mutex::Autolock lock(mStatusListenerLock);
3148
3149 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003150 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003151 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3152 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003153 }
3154}
3155
Austin Borgerdddb7552023-03-30 17:53:01 -07003156void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3157 Mutex::Autolock lock(mStatusListenerLock);
3158
3159 for (const auto& it : mListenerList) {
3160 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3161 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3162 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3163 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3164 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3165 }
3166 }
3167}
3168
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003169Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003170 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003171 const int selfPid = getpid();
3172
3173 // Permission checks
3174 if (pid != selfPid) {
3175 // Ensure we're being called by system_server, or similar process with
3176 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003177 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003178 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003179 ALOGE("Permission Denial: cannot send updates to camera service about device"
3180 " state changes from pid=%d, uid=%d", pid, uid);
3181 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3182 "No permission to send updates to camera service about device state"
3183 " changes from pid=%d, uid=%d", pid, uid);
3184 }
3185 }
3186
3187 ATRACE_CALL();
3188
Austin Borger18b30a72022-10-27 12:20:29 -07003189 {
3190 Mutex::Autolock lock(mServiceLock);
3191 mDeviceState = newState;
3192 }
3193
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003194 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003195
3196 return Status::ok();
3197}
3198
Emilian Peev8b64f282021-03-25 16:49:57 -07003199Status CameraService::notifyDisplayConfigurationChange() {
3200 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003201 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003202 const int selfPid = getpid();
3203
3204 // Permission checks
3205 if (callingPid != selfPid) {
3206 // Ensure we're being called by system_server, or similar process with
3207 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003208 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003209 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003210 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3211 " changes from pid=%d, uid=%d", callingPid, uid);
3212 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3213 "No permission to send updates to camera service about orientation"
3214 " changes from pid=%d, uid=%d", callingPid, uid);
3215 }
3216 }
3217
3218 Mutex::Autolock lock(mServiceLock);
3219
3220 // Don't do anything if rotate-and-crop override via cmd is active
3221 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3222
3223 const auto clients = mActiveClientManager.getAll();
3224 for (auto& current : clients) {
3225 if (current != nullptr) {
3226 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003227 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3228 basicClient->setRotateAndCropOverride(
3229 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3230 basicClient->getPackageName(),
3231 basicClient->getCameraFacing(),
3232 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003233 }
3234 }
3235 }
3236
3237 return Status::ok();
3238}
3239
3240Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003241 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3242 ATRACE_CALL();
3243 if (!concurrentCameraIds) {
3244 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3245 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3246 }
3247
3248 if (!mInitialized) {
3249 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003250 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003251 return STATUS_ERROR(ERROR_DISCONNECTED,
3252 "Camera subsystem is not available");
3253 }
3254 // First call into the provider and get the set of concurrent camera
3255 // combinations
3256 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003257 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003258 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003259 std::vector<std::pair<std::string, int32_t>> validCombination;
3260 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003261 for (auto &cameraId : combination) {
3262 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003263 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003264 if (state == nullptr) {
3265 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3266 continue;
3267 }
3268 StatusInternal status = state->getStatus();
3269 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3270 continue;
3271 }
Austin Borgered99f642023-06-01 16:51:35 -07003272 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003273 continue;
3274 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003275 auto [cameraOwnerDeviceId, mappedCameraId] =
3276 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3277 if (firstDeviceId == kInvalidDeviceId) {
3278 firstDeviceId = cameraOwnerDeviceId;
3279 } else if (firstDeviceId != cameraOwnerDeviceId) {
3280 // Found an invalid combination which contains cameras with different device id's,
3281 // hence discard it.
3282 validCombination.clear();
3283 break;
3284 }
3285 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003286 }
3287 if (validCombination.size() != 0) {
3288 concurrentCameraIds->push_back(std::move(validCombination));
3289 }
3290 }
3291 return Status::ok();
3292}
3293
3294Status CameraService::isConcurrentSessionConfigurationSupported(
3295 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003296 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003297 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003298 if (!isSupported) {
3299 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3301 }
3302
3303 if (!mInitialized) {
3304 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3305 return STATUS_ERROR(ERROR_DISCONNECTED,
3306 "Camera subsystem is not available");
3307 }
3308
Biswarup Pal7d072862024-04-17 15:24:47 +00003309 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3310 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003311 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3312 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003313 if (!cameraIdOptional.has_value()) {
3314 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003315 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003316 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3317 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3318 }
3319 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3320 }
3321
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003322 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003323 int callingPid = getCallingPid();
3324 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003325 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003326 hasPermissionsForCamera(callingPid, callingUid,
3327 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003328 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003329 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003330 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3331 "android.permission.CAMERA needed to call"
3332 "isConcurrentSessionConfigurationSupported");
3333 }
3334
3335 status_t res =
3336 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003337 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3338 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003339 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003340 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003341 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003342 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3343 "support %s (%d)", strerror(-res), res);
3344 }
3345 return Status::ok();
3346}
3347
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003348Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3349 /*out*/
3350 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003351 return addListenerHelper(listener, cameraStatuses);
3352}
3353
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003354binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3355 std::vector<hardware::CameraStatus>* cameraStatuses) {
3356 return addListenerHelper(listener, cameraStatuses, false, true);
3357}
3358
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003359Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3360 /*out*/
3361 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003362 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003363 ATRACE_CALL();
3364
Igor Murashkinbfc99152013-02-27 12:55:20 -08003365 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003366
Ruben Brunk3450ba72015-06-16 11:00:37 -07003367 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003368 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003369 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003370 }
3371
Austin Borger22c5c852024-03-08 13:31:36 -08003372 auto clientPid = getCallingPid();
3373 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003374 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003375
Igor Murashkinbfc99152013-02-27 12:55:20 -08003376 Mutex::Autolock lock(mServiceLock);
3377
Ruben Brunkcc776712015-02-17 20:18:47 -08003378 {
3379 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003380 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003381 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003382 ALOGW("%s: Tried to add listener %p which was already subscribed",
3383 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003384 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003385 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003386 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003387
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003388 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003389 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3390 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003391 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003392 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003393 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003394 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003395 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3396 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3397 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003398 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003399 // The listener still needs to be added to the list of listeners, regardless of what
3400 // permissions the listener process has / whether it is a vendor listener. Since it might be
3401 // eligible to listen to other camera ids.
3402 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003403 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003404 }
3405
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003406 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003407 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003408 Mutex::Autolock lock(mCameraStatesLock);
3409 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003410 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3411 auto [deviceId, mappedCameraId] =
3412 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3413
3414 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003415 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003416 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3417 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003418 }
3419 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003420 // Remove the camera statuses that should be hidden from the client, we do
3421 // this after collecting the states in order to avoid holding
3422 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3423 // the same time.
3424 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3425 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003426 std::string cameraId = s.cameraId;
3427 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003428 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003429 if (!cameraIdOptional.has_value()) {
3430 std::string msg =
3431 fmt::sprintf(
3432 "Camera %s: Invalid camera id for device id %d",
3433 s.cameraId.c_str(), s.deviceId);
3434 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3435 return true;
3436 }
3437 cameraId = cameraIdOptional.value();
3438 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3439 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3440 ALOGE("%s: Invalid camera id %s, skipping status update",
3441 __FUNCTION__, s.cameraId.c_str());
3442 return true;
3443 }
3444 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3445 clientUid);
3446 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003447
Biswarup Pal37a75182024-01-16 15:53:35 +00003448 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003449 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003450 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003451 // Add only default device cameras here, as virtual cameras currently don't support torch
3452 // anyway. Note that this is a simplification of the implementation here, and we should
3453 // change this when virtual cameras support torch.
3454 if (s.deviceId == kDefaultDeviceId) {
3455 idsChosenForCallback.insert(s.cameraId);
3456 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003457 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003458
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003459 /*
3460 * Immediately signal current torch status to this listener only
3461 * This may be a subset of all the devices, so don't include it in the response directly
3462 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003463 {
3464 Mutex::Autolock al(mTorchStatusMutex);
3465 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003466 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003467 // The camera id is visible to the client. Fine to send torch
3468 // callback.
3469 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003470 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3471 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003472 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003473 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003474 }
3475
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003476 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003477}
Ruben Brunkcc776712015-02-17 20:18:47 -08003478
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003479Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003480 ATRACE_CALL();
3481
Igor Murashkinbfc99152013-02-27 12:55:20 -08003482 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3483
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003484 if (listener == 0) {
3485 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003486 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003487 }
3488
Igor Murashkinbfc99152013-02-27 12:55:20 -08003489 Mutex::Autolock lock(mServiceLock);
3490
Ruben Brunkcc776712015-02-17 20:18:47 -08003491 {
3492 Mutex::Autolock lock(mStatusListenerLock);
3493 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003494 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003495 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003496 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003497 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003498 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003499 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003500 }
3501 }
3502
3503 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3504 __FUNCTION__, listener.get());
3505
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003506 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003507}
3508
Austin Borgered99f642023-06-01 16:51:35 -07003509Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003510
3511 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003512 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3513
3514 if (parameters == NULL) {
3515 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003516 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003517 }
3518
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003519 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003520
3521 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003522 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003523 // Error logged by caller
3524 return ret;
3525 }
3526
3527 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003528
Austin Borgered99f642023-06-01 16:51:35 -07003529 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003530
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003531 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003532}
3533
malikakash98260df2024-05-10 23:33:57 +00003534Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003535 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003536 ATRACE_CALL();
3537
Austin Borgered99f642023-06-01 16:51:35 -07003538 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003539
3540 switch (apiVersion) {
3541 case API_VERSION_1:
3542 case API_VERSION_2:
3543 break;
3544 default:
Austin Borgered99f642023-06-01 16:51:35 -07003545 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3546 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3547 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003548 }
3549
Austin Borger18b30a72022-10-27 12:20:29 -07003550 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003551 auto deviceVersionAndTransport =
3552 getDeviceVersion(cameraId,
3553 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3554 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003555 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003556 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3557 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3558 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003559 }
3560 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3561 int deviceVersion = deviceVersionAndTransport.first;
3562 switch (deviceVersion) {
3563 case CAMERA_DEVICE_API_VERSION_1_0:
3564 case CAMERA_DEVICE_API_VERSION_3_0:
3565 case CAMERA_DEVICE_API_VERSION_3_1:
3566 if (apiVersion == API_VERSION_2) {
3567 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003568 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003569 *isSupported = false;
3570 } else { // if (apiVersion == API_VERSION_1) {
3571 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003572 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003573 *isSupported = true;
3574 }
3575 break;
3576 case CAMERA_DEVICE_API_VERSION_3_2:
3577 case CAMERA_DEVICE_API_VERSION_3_3:
3578 case CAMERA_DEVICE_API_VERSION_3_4:
3579 case CAMERA_DEVICE_API_VERSION_3_5:
3580 case CAMERA_DEVICE_API_VERSION_3_6:
3581 case CAMERA_DEVICE_API_VERSION_3_7:
3582 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003583 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003584 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003585 break;
3586 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003587 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3588 deviceVersion, cameraId.c_str());
3589 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3590 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003591 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003592 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003593 } else {
3594 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003595 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003596 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003597}
3598
malikakash98260df2024-05-10 23:33:57 +00003599Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003600 /*out*/ bool *isSupported) {
3601 ATRACE_CALL();
3602
Austin Borgered99f642023-06-01 16:51:35 -07003603 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3604 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003605
3606 return Status::ok();
3607}
3608
Cliff Wud8cae102021-03-11 01:37:42 +08003609Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003610 const std::string& packageName, const std::string& internalCamId,
3611 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003612 const sp<ICameraInjectionCallback>& callback,
3613 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003614 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003615 ATRACE_CALL();
3616
Austin Borgered99f642023-06-01 16:51:35 -07003617 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003618 const int pid = getCallingPid();
3619 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003620 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3621 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003622 "Permission Denial: no permission to inject camera");
3623 }
3624
3625 // Do not allow any camera injection that injects or replaces a virtual camera.
3626 auto [deviceIdForInternalCamera, _] =
3627 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3628 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3629 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3630 "Cannot replace a virtual camera");
3631 }
3632 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3633 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3634 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3635 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3636 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003637 }
3638
3639 ALOGV(
3640 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3641 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003642 __FUNCTION__, packageName.c_str(),
3643 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003644
Cliff Wud3a05312021-04-26 23:07:31 +08003645 {
3646 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003647 mInjectionInternalCamId = internalCamId;
3648 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003649 mInjectionStatusListener->addListener(callback);
3650 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003651 status_t res = NO_ERROR;
3652 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3653 // If the client already exists, we can directly connect to the camera device through the
3654 // client's injectCamera(), otherwise we need to wait until the client is established
3655 // (execute connectHelper()) before injecting the camera to the camera device.
3656 if (clientDescriptor != nullptr) {
3657 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003658 sp<BasicClient> clientSp = clientDescriptor->getValue();
3659 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3660 if(res != OK) {
3661 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3662 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003663 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003664 }
3665 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003666 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003667 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3668 }
3669 } else {
3670 mInjectionInitPending = true;
3671 }
3672 }
Cliff Wud8cae102021-03-11 01:37:42 +08003673
Cliff Wud3a05312021-04-26 23:07:31 +08003674 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003675}
3676
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003677Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003678 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003679 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3680 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3681 return Status::ok();
3682}
3683
Ruben Brunkcc776712015-02-17 20:18:47 -08003684void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003685 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003686 for (auto& i : mActiveClientManager.getAll()) {
3687 auto clientSp = i->getValue();
3688 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003689 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003690 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003691 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003692 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003693 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003694}
3695
Ruben Brunkcc776712015-02-17 20:18:47 -08003696bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003697 bool ret = false;
3698 {
3699 // Acquire mServiceLock and prevent other clients from connecting
3700 std::unique_ptr<AutoConditionLock> lock =
3701 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003702
Ruben Brunkcc776712015-02-17 20:18:47 -08003703 std::vector<sp<BasicClient>> evicted;
3704 for (auto& i : mActiveClientManager.getAll()) {
3705 auto clientSp = i->getValue();
3706 if (clientSp.get() == nullptr) {
3707 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3708 mActiveClientManager.remove(i);
3709 continue;
3710 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003711 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003712 mActiveClientManager.remove(i);
3713 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003714
Ruben Brunkcc776712015-02-17 20:18:47 -08003715 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003716 clientSp->notifyError(
3717 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003718 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003719 }
3720 }
3721
Ruben Brunkcc776712015-02-17 20:18:47 -08003722 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3723 // other clients from connecting in mServiceLockWrapper if held
3724 mServiceLock.unlock();
3725
Ruben Brunk36597b22015-03-20 22:15:57 -07003726 // Do not clear caller identity, remote caller should be client proccess
3727
Ruben Brunkcc776712015-02-17 20:18:47 -08003728 for (auto& i : evicted) {
3729 if (i.get() != nullptr) {
3730 i->disconnect();
3731 ret = true;
3732 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003733 }
3734
Ruben Brunkcc776712015-02-17 20:18:47 -08003735 // Reacquire mServiceLock
3736 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003737
Ruben Brunkcc776712015-02-17 20:18:47 -08003738 } // lock is destroyed, allow further connect calls
3739
3740 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003741}
3742
Ruben Brunkcc776712015-02-17 20:18:47 -08003743std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003744 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003745 std::shared_ptr<CameraState> state;
3746 {
3747 Mutex::Autolock lock(mCameraStatesLock);
3748 auto iter = mCameraStates.find(cameraId);
3749 if (iter != mCameraStates.end()) {
3750 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003751 }
3752 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003753 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003754}
3755
Austin Borgered99f642023-06-01 16:51:35 -07003756sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003757 // Remove from active clients list
3758 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3759 if (clientDescriptorPtr == nullptr) {
3760 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003761 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003762 return sp<BasicClient>{nullptr};
3763 }
3764
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003765 sp<BasicClient> client = clientDescriptorPtr->getValue();
3766 if (client.get() != nullptr) {
3767 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3768 }
3769 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003770}
3771
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003772void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003773 // Acquire mServiceLock and prevent other clients from connecting
3774 std::unique_ptr<AutoConditionLock> lock =
3775 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3776
Ruben Brunk6267b532015-04-30 17:44:07 -07003777 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003778 for (size_t i = 0; i < newUserIds.size(); i++) {
3779 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003780 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003781 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003782 return;
3783 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003784 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003785 }
3786
Ruben Brunka8ca9152015-04-07 14:23:40 -07003787
Ruben Brunk6267b532015-04-30 17:44:07 -07003788 if (newAllowedUsers == mAllowedUsers) {
3789 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3790 return;
3791 }
3792
3793 logUserSwitch(mAllowedUsers, newAllowedUsers);
3794
3795 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003796
3797 // Current user has switched, evict all current clients.
3798 std::vector<sp<BasicClient>> evicted;
3799 for (auto& i : mActiveClientManager.getAll()) {
3800 auto clientSp = i->getValue();
3801
3802 if (clientSp.get() == nullptr) {
3803 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3804 continue;
3805 }
3806
Ruben Brunk6267b532015-04-30 17:44:07 -07003807 // Don't evict clients that are still allowed.
3808 uid_t clientUid = clientSp->getClientUid();
3809 userid_t clientUserId = multiuser_get_user_id(clientUid);
3810 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3811 continue;
3812 }
3813
Ruben Brunk36597b22015-03-20 22:15:57 -07003814 evicted.push_back(clientSp);
3815
Ruben Brunk36597b22015-03-20 22:15:57 -07003816 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003817 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003818
Ruben Brunk36597b22015-03-20 22:15:57 -07003819 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003820 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003821 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003822 " to user switch.", i->getKey().c_str(),
3823 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003824 i->getOwnerId(), i->getPriority().getScore(),
3825 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003826
3827 }
3828
3829 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3830 // blocking other clients from connecting in mServiceLockWrapper if held.
3831 mServiceLock.unlock();
3832
3833 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003834 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003835
3836 for (auto& i : evicted) {
3837 i->disconnect();
3838 }
3839
Austin Borger22c5c852024-03-08 13:31:36 -08003840 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003841
3842 // Reacquire mServiceLock
3843 mServiceLock.lock();
3844}
Ruben Brunkcc776712015-02-17 20:18:47 -08003845
Austin Borgered99f642023-06-01 16:51:35 -07003846void CameraService::logEvent(const std::string &event) {
3847 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003848 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003849 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003850 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003851 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003852 mEventLog.add(msg);
3853 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3854 // Error event not added to the dumpsys log before
3855 mEventLog.add(msg);
3856 sServiceErrorEventSet.insert(msg);
3857 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003858}
3859
Austin Borgered99f642023-06-01 16:51:35 -07003860void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3861 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003862 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003863 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3864 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003865}
3866
Austin Borgered99f642023-06-01 16:51:35 -07003867void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3868 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003869 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003870 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3871 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003872}
3873
Austin Borgered99f642023-06-01 16:51:35 -07003874void CameraService::logConnected(const std::string &cameraId, int clientPid,
3875 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003876 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003877 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3878 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003879}
3880
Austin Borgered99f642023-06-01 16:51:35 -07003881void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3882 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003883 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003884 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3885 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003886}
3887
Austin Borgered99f642023-06-01 16:51:35 -07003888void CameraService::logRejected(const std::string &cameraId, int clientPid,
3889 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003890 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003891 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3892 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003893}
3894
Austin Borgered99f642023-06-01 16:51:35 -07003895void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3896 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003897 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003898 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3899 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003900}
3901
Ruben Brunk6267b532015-04-30 17:44:07 -07003902void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3903 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003904 std::string newUsers = toString(newUserIds);
3905 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003906 if (oldUsers.size() == 0) {
3907 oldUsers = "<None>";
3908 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003909 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003910 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3911 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003912}
3913
Austin Borgered99f642023-06-01 16:51:35 -07003914void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003915 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003916 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003917}
3918
Austin Borgered99f642023-06-01 16:51:35 -07003919void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003920 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003921 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003922}
3923
Austin Borgered99f642023-06-01 16:51:35 -07003924void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003925 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003926 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003927}
3928
Austin Borgered99f642023-06-01 16:51:35 -07003929void CameraService::logServiceError(const std::string &msg, int errorCode) {
3930 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3931 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003932}
3933
Ruben Brunk36597b22015-03-20 22:15:57 -07003934status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3935 uint32_t flags) {
3936
Mathias Agopian65ab4712010-07-14 17:59:35 -07003937 // Permission checks
3938 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003939 case SHELL_COMMAND_TRANSACTION: {
3940 int in = data.readFileDescriptor();
3941 int out = data.readFileDescriptor();
3942 int err = data.readFileDescriptor();
3943 int argc = data.readInt32();
3944 Vector<String16> args;
3945 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3946 args.add(data.readString16());
3947 }
3948 sp<IBinder> unusedCallback;
3949 sp<IResultReceiver> resultReceiver;
3950 status_t status;
3951 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3952 return status;
3953 }
3954 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3955 return status;
3956 }
3957 status = shellCommand(in, out, err, args);
3958 if (resultReceiver != nullptr) {
3959 resultReceiver->send(status);
3960 }
3961 return NO_ERROR;
3962 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003963 }
3964
3965 return BnCameraService::onTransact(code, data, reply, flags);
3966}
3967
Mathias Agopian65ab4712010-07-14 17:59:35 -07003968// We share the media players for shutter and recording sound for all clients.
3969// A reference count is kept to determine when we will actually release the
3970// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003971sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3972 sp<MediaPlayer> mp = new MediaPlayer();
3973 status_t error;
3974 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003975 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003976 error = mp->prepare();
3977 }
3978 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003979 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003980 mp->disconnect();
3981 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003982 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003983 }
3984 return mp;
3985}
3986
username5755fea2018-12-27 09:48:08 +08003987void CameraService::increaseSoundRef() {
3988 Mutex::Autolock lock(mSoundLock);
3989 mSoundRef++;
3990}
3991
3992void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003993 ATRACE_CALL();
3994
username5755fea2018-12-27 09:48:08 +08003995 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
3996 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
3997 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
3998 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
3999 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4000 }
4001 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4002 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4003 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4004 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004005 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004006 }
4007 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4008 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4009 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4010 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4011 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004012 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004013}
4014
username5755fea2018-12-27 09:48:08 +08004015void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004016 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004017 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018 if (--mSoundRef) return;
4019
4020 for (int i = 0; i < NUM_SOUNDS; i++) {
4021 if (mSoundPlayer[i] != 0) {
4022 mSoundPlayer[i]->disconnect();
4023 mSoundPlayer[i].clear();
4024 }
4025 }
4026}
4027
4028void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004029 ATRACE_CALL();
4030
Mathias Agopian65ab4712010-07-14 17:59:35 -07004031 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004032 if (kind < 0 || kind >= NUM_SOUNDS) {
4033 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4034 return;
4035 }
4036
Mathias Agopian65ab4712010-07-14 17:59:35 -07004037 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004038 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004039 sp<MediaPlayer> player = mSoundPlayer[kind];
4040 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004041 player->seekTo(0);
4042 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004043 }
4044}
4045
4046// ----------------------------------------------------------------------------
4047
4048CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004049 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004050 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004051 const std::string& clientPackageName, bool systemNativeClient,
4052 const std::optional<std::string>& clientFeatureId,
4053 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004054 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004055 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004056 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004057 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004058 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004059 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004060 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004061 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004062 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004063 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004064 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004065{
Austin Borger22c5c852024-03-08 13:31:36 -08004066 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004067 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004069 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004070
username5755fea2018-12-27 09:48:08 +08004071 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004072
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004073 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004074}
4075
Mathias Agopian65ab4712010-07-14 17:59:35 -07004076// tear down the client
4077CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004078 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004079 mDestructionStarted = true;
4080
username5755fea2018-12-27 09:48:08 +08004081 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004082 // unconditionally disconnect. function is idempotent
4083 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084}
4085
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004086sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4087
Igor Murashkin634a5152013-02-20 17:15:11 -08004088CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004089 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004090 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004091 const std::string& clientPackageName, bool nativeClient,
4092 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004093 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004094 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004095 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004096 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004097 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004098 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4099 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004100 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004101 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004102 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004103 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004104 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004105 mRemoteBinder(remoteCallback),
4106 mOpsActive(false),
4107 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004108{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004109 if (sCameraService == nullptr) {
4110 sCameraService = cameraService;
4111 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004112
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004113 // There are 2 scenarios in which a client won't have AppOps operations
4114 // (both scenarios : native clients)
4115 // 1) It's an system native client*, the package name will be empty
4116 // and it will return from this function in the previous if condition
4117 // (This is the same as the previously existing behavior).
4118 // 2) It is a system native client, but its package name has been
4119 // modified for debugging, however it still must not use AppOps since
4120 // the package name is not a real one.
4121 //
4122 // * system native client - native client with UID < AID_APP_START. It
4123 // doesn't exclude clients not on the system partition.
4124 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004125 mAppOpsManager = std::make_unique<AppOpsManager>();
4126 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004127
Charles Chenf075f082024-03-04 23:32:55 +00004128 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004129}
4130
4131CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004132 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004133 mDestructionStarted = true;
4134}
4135
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004136binder::Status CameraService::BasicClient::disconnect() {
4137 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004138 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004139 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004140 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004141 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004142
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004143 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004144 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004145 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004146 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004147
4148 sp<IBinder> remote = getRemote();
4149 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004150 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004151 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004152
4153 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004154 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004155 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004156 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004157 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004158
Igor Murashkincba2c162013-03-20 15:56:31 -07004159 // client shouldn't be able to call into us anymore
4160 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004161
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004162 const auto& mActivityManager = getActivityManager();
4163 if (mActivityManager) {
4164 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004165 getCallingUid(),
4166 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004167 }
4168
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004169 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004170}
4171
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004172status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4173 // No dumping of clients directly over Binder,
4174 // must go through CameraService::dump
4175 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004176 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004177 return OK;
4178}
4179
Austin Borgered99f642023-06-01 16:51:35 -07004180status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004181 // Can't watch tags directly, must go through CameraService::startWatchingTags
4182 return OK;
4183}
4184
4185status_t CameraService::BasicClient::stopWatchingTags(int) {
4186 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4187 return OK;
4188}
4189
4190status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4191 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4192 return OK;
4193}
4194
Austin Borgered99f642023-06-01 16:51:35 -07004195std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004196 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004197}
4198
Emilian Peev8b64f282021-03-25 16:49:57 -07004199int CameraService::BasicClient::getCameraFacing() const {
4200 return mCameraFacing;
4201}
4202
4203int CameraService::BasicClient::getCameraOrientation() const {
4204 return mOrientation;
4205}
Ruben Brunkcc776712015-02-17 20:18:47 -08004206
4207int CameraService::BasicClient::getClientPid() const {
4208 return mClientPid;
4209}
4210
Ruben Brunk6267b532015-04-30 17:44:07 -07004211uid_t CameraService::BasicClient::getClientUid() const {
4212 return mClientUid;
4213}
4214
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004215bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4216 // Defaults to API2.
4217 return level == API_2;
4218}
4219
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004220status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004221 {
4222 Mutex::Autolock l(mAudioRestrictionLock);
4223 mAudioRestriction = mode;
4224 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004225 sCameraService->updateAudioRestriction();
4226 return OK;
4227}
4228
4229int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004230 return sCameraService->updateAudioRestriction();
4231}
4232
4233int32_t CameraService::BasicClient::getAudioRestriction() const {
4234 Mutex::Autolock l(mAudioRestrictionLock);
4235 return mAudioRestriction;
4236}
4237
4238bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4239 switch (mode) {
4240 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4241 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4242 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4243 return true;
4244 default:
4245 return false;
4246 }
4247}
4248
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004249status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4250 if (mode == AppOpsManager::MODE_ERRORED) {
4251 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004252 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004253 return PERMISSION_DENIED;
4254 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4255 // If the calling Uid is trusted (a native service), the AppOpsManager could
4256 // return MODE_IGNORED. Do not treat such case as error.
4257 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4258 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004259
4260 bool isCameraPrivacyEnabled;
4261 if (flags::camera_privacy_allowlist()) {
4262 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4263 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4264 } else {
4265 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004266 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004267 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004268 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4269 // We prefer to successfully open the camera and perform camera muting
4270 // or blocking in connectHelper as handleAppOpMode can be called before the
4271 // connection has been fully established and at that time camera muting
4272 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004273 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004274 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4275 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4276 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4277 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004278 // Return the same error as for device policy manager rejection
4279 return -EACCES;
4280 }
4281 }
4282 return OK;
4283}
4284
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004285status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004286 ATRACE_CALL();
4287
Igor Murashkine6800ce2013-03-04 17:25:57 -08004288 {
4289 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004290 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004291 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004292 if (mAppOpsManager != nullptr) {
4293 // Notify app ops that the camera is not available
4294 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004295
Austin Borger5755d9b2024-09-09 11:15:44 -07004296 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4297 toString16(mClientPackageName),
4298 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004299
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004300 // Just check for camera acccess here on open - delay startOp until
4301 // camera frames start streaming in startCameraStreamingOps
4302 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004303 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004304 status_t res = handleAppOpMode(mode);
4305 if (res != OK) {
4306 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004307 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004308 }
4309
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004310 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004311
4312 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004313 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004314
Austin Borgerdddb7552023-03-30 17:53:01 -07004315 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004316
Shuzhen Wang695044d2020-03-06 09:02:23 -08004317 // Notify listeners of camera open/close status
4318 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4319
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004320 return OK;
4321}
4322
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004323status_t CameraService::BasicClient::startCameraStreamingOps() {
4324 ATRACE_CALL();
4325
4326 if (!mOpsActive) {
4327 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4328 return INVALID_OPERATION;
4329 }
4330 if (mOpsStreaming) {
4331 ALOGV("%s: Streaming already active!", __FUNCTION__);
4332 return OK;
4333 }
4334
4335 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004336 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004337
4338 if (mAppOpsManager != nullptr) {
4339 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004340 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4341 toString16(mClientFeatureId),
4342 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004343 status_t res = handleAppOpMode(mode);
4344 if (res != OK) {
4345 return res;
4346 }
4347 }
4348
4349 mOpsStreaming = true;
4350
4351 return OK;
4352}
4353
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004354status_t CameraService::BasicClient::noteAppOp() {
4355 ATRACE_CALL();
4356
4357 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004358 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004359
4360 // noteAppOp is only used for when camera mute is not supported, in order
4361 // to trigger the sensor privacy "Unblock" dialog
4362 if (mAppOpsManager != nullptr) {
4363 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004364 toString16(mClientPackageName), toString16(mClientFeatureId),
4365 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004366 status_t res = handleAppOpMode(mode);
4367 if (res != OK) {
4368 return res;
4369 }
4370 }
4371
4372 return OK;
4373}
4374
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004375status_t CameraService::BasicClient::finishCameraStreamingOps() {
4376 ATRACE_CALL();
4377
4378 if (!mOpsActive) {
4379 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4380 return INVALID_OPERATION;
4381 }
4382 if (!mOpsStreaming) {
4383 ALOGV("%s: Streaming not active!", __FUNCTION__);
4384 return OK;
4385 }
4386
4387 if (mAppOpsManager != nullptr) {
4388 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004389 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004390 mOpsStreaming = false;
4391 }
4392
4393 return OK;
4394}
4395
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004396status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004397 ATRACE_CALL();
4398
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004399 if (mOpsStreaming) {
4400 // Make sure we've notified everyone about camera stopping
4401 finishCameraStreamingOps();
4402 }
4403
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004404 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004405 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004406 mOpsActive = false;
4407
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004408 // This function is called when a client disconnects. This should
4409 // release the camera, but actually only if it was in a proper
4410 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004411 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004412 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004413
Ruben Brunkcc776712015-02-17 20:18:47 -08004414 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004415 sCameraService->updateStatus(StatusInternal::PRESENT,
4416 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004417 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004418 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004419 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4420 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004421 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004422 mOpsCallback.clear();
4423
Austin Borgerdddb7552023-03-30 17:53:01 -07004424 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004425
Shuzhen Wang695044d2020-03-06 09:02:23 -08004426 // Notify listeners of camera open/close status
4427 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4428
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004429 return OK;
4430}
4431
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004432void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004433 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004434 if (mAppOpsManager == nullptr) {
4435 return;
4436 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004437 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004438 if (op != AppOpsManager::OP_CAMERA) {
4439 ALOGW("Unexpected app ops notification received: %d", op);
4440 return;
4441 }
4442
4443 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004444 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004445 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004446 ALOGV("checkOp returns: %d, %s ", res,
4447 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4448 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4449 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4450 "UNKNOWN");
4451
Shuzhen Wang64900852021-02-05 09:03:29 -08004452 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004453 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4454 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004455 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004456 } else if (res == AppOpsManager::MODE_IGNORED) {
4457 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004458
Austin Borgerca1e0062023-06-28 11:32:55 -07004459 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4460 // If not visible, but still active, then we want to block instead of muting the camera.
4461 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4462 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4463
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004464 bool isCameraPrivacyEnabled;
4465 if (flags::camera_privacy_allowlist()) {
4466 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4467 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4468 } else {
4469 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004470 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004471 }
4472
4473 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004474 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4475 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4476 isCameraPrivacyEnabled);
4477 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4478 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4479 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004480 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004481 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4482 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004483 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004484 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004485 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004486 }
Evan Severson09ab4002021-02-10 14:15:19 -08004487 } else if (res == AppOpsManager::MODE_ALLOWED) {
4488 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004489 }
4490}
4491
Svet Ganova453d0d2018-01-11 15:37:58 -08004492void CameraService::BasicClient::block() {
4493 ATRACE_CALL();
4494
4495 // Reset the client PID to allow server-initiated disconnect,
4496 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004497 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004498 CaptureResultExtras resultExtras; // a dummy result (invalid)
4499 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4500 disconnect();
4501}
4502
Mathias Agopian65ab4712010-07-14 17:59:35 -07004503// ----------------------------------------------------------------------------
4504
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004505void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004506 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004507 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004508 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4509 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4510 api1ErrorCode = CAMERA_ERROR_DISABLED;
4511 }
4512 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004513 } else {
4514 ALOGE("mRemoteCallback is NULL!!");
4515 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004516}
4517
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004518// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004519binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004520 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004521 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004522}
4523
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004524bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4525 return level == API_1;
4526}
4527
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004528CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4529 mClient(client) {
4530}
4531
4532void CameraService::Client::OpsCallback::opChanged(int32_t op,
4533 const String16& packageName) {
4534 sp<BasicClient> client = mClient.promote();
4535 if (client != NULL) {
4536 client->opChanged(op, packageName);
4537 }
4538}
4539
Mathias Agopian65ab4712010-07-14 17:59:35 -07004540// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004541// UidPolicy
4542// ----------------------------------------------------------------------------
4543
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004544void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004545 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004546 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004547
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004548 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004549 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004550 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004551 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004552 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4553 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004554 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004555 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004556 if (res == OK) {
4557 mRegistered = true;
4558 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004559 } else {
4560 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004561 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004562}
4563
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004564void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004565 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004566 return;
4567 }
4568
4569 registerWithActivityManager();
4570}
4571
4572void CameraService::UidPolicy::registerSelf() {
4573 // Use check service to see if the activity service is available
4574 // If not available then register for notifications, instead of blocking
4575 // till the service is ready
4576 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004577 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004578 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004579 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004580 } else {
4581 registerWithActivityManager();
4582 }
4583}
4584
Svet Ganova453d0d2018-01-11 15:37:58 -08004585void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004586 Mutex::Autolock _l(mUidLock);
4587
Steven Moreland2f348142019-07-02 15:59:07 -07004588 mAm.unregisterUidObserver(this);
4589 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004590 mRegistered = false;
4591 mActiveUids.clear();
4592 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004593}
4594
4595void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4596 onUidIdle(uid, disabled);
4597}
4598
4599void CameraService::UidPolicy::onUidActive(uid_t uid) {
4600 Mutex::Autolock _l(mUidLock);
4601 mActiveUids.insert(uid);
4602}
4603
4604void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4605 bool deleted = false;
4606 {
4607 Mutex::Autolock _l(mUidLock);
4608 if (mActiveUids.erase(uid) > 0) {
4609 deleted = true;
4610 }
4611 }
4612 if (deleted) {
4613 sp<CameraService> service = mService.promote();
4614 if (service != nullptr) {
4615 service->blockClientsForUid(uid);
4616 }
4617 }
4618}
4619
Emilian Peev53722fa2019-02-22 17:47:20 -08004620void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004621 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004622 bool procStateChange = false;
4623 {
4624 Mutex::Autolock _l(mUidLock);
4625 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4626 mMonitoredUids[uid].procState != procState) {
4627 mMonitoredUids[uid].procState = procState;
4628 procStateChange = true;
4629 }
4630 }
4631
4632 if (procStateChange) {
4633 sp<CameraService> service = mService.promote();
4634 if (service != nullptr) {
4635 service->notifyMonitoredUids();
4636 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004637 }
4638}
4639
Austin Borgerdddb7552023-03-30 17:53:01 -07004640/**
4641 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4642 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4643 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4644 * monitoredUids. If it is revised above some other monitoredUid, signal
4645 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4646 * foreground apps in split screen - state changes will capture all other cases.
4647 */
4648void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4649 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004650 {
4651 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004652 auto it = mMonitoredUids.find(uid);
4653
4654 if (it != mMonitoredUids.end()) {
4655 if (it->second.hasCamera) {
4656 for (auto &monitoredUid : mMonitoredUids) {
4657 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004658 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004659 notifyUidSet.emplace(monitoredUid.first);
4660 }
4661 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004662 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004663 notifyUidSet.emplace(uid);
4664 } else {
4665 for (auto &monitoredUid : mMonitoredUids) {
4666 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004667 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004668 notifyUidSet.emplace(uid);
4669 }
4670 }
4671 }
4672 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004673 }
4674 }
4675
Austin Borgerdddb7552023-03-30 17:53:01 -07004676 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004677 sp<CameraService> service = mService.promote();
4678 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004679 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004680 }
4681 }
4682}
4683
Austin Borgerdddb7552023-03-30 17:53:01 -07004684/**
4685 * Register a uid for monitoring, and note whether it owns a camera.
4686 */
4687void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004688 Mutex::Autolock _l(mUidLock);
4689 auto it = mMonitoredUids.find(uid);
4690 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004691 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004692 } else {
Austin Borger65577682022-02-17 00:25:43 +00004693 MonitoredUid monitoredUid;
4694 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004695 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004696 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004697 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004698 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004699 if (res != OK) {
4700 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4701 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004702 }
4703
4704 if (openCamera) {
4705 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004706 }
4707}
4708
Austin Borgerdddb7552023-03-30 17:53:01 -07004709/**
4710 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4711 */
4712void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004713 Mutex::Autolock _l(mUidLock);
4714 auto it = mMonitoredUids.find(uid);
4715 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004716 it->second.refCount--;
4717 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004718 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004719 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004720 if (res != OK) {
4721 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4722 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004723 } else if (closeCamera) {
4724 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004725 }
4726 } else {
4727 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4728 }
4729}
4730
Austin Borgered99f642023-06-01 16:51:35 -07004731bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004732 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004733 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004734}
4735
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004736static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4737static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004738
Austin Borgered99f642023-06-01 16:51:35 -07004739bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004740 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004741 // If activity manager is unreachable, assume everything is active
4742 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004743 return true;
4744 }
4745 auto it = mOverrideUids.find(uid);
4746 if (it != mOverrideUids.end()) {
4747 return it->second;
4748 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004749 bool active = mActiveUids.find(uid) != mActiveUids.end();
4750 if (!active) {
4751 // We want active UIDs to always access camera with their first attempt since
4752 // there is no guarantee the app is robustly written and would retry getting
4753 // the camera on failure. The inverse case is not a problem as we would take
4754 // camera away soon once we get the callback that the uid is no longer active.
4755 ActivityManager am;
4756 // Okay to access with a lock held as UID changes are dispatched without
4757 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004758 int64_t startTimeMillis = 0;
4759 do {
4760 // TODO: Fix this b/109950150!
4761 // Okay this is a hack. There is a race between the UID turning active and
4762 // activity being resumed. The proper fix is very risky, so we temporary add
4763 // some polling which should happen pretty rarely anyway as the race is hard
4764 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004765 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004766 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004767 if (active) {
4768 break;
4769 }
4770 if (startTimeMillis <= 0) {
4771 startTimeMillis = uptimeMillis();
4772 }
4773 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004774 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004775 if (remainingTimeMillis <= 0) {
4776 break;
4777 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004778 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4779
4780 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004781 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004782 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004783 } while (true);
4784
Svet Ganov7b4ab782018-03-25 12:48:10 -07004785 if (active) {
4786 // Now that we found out the UID is actually active, cache that
4787 mActiveUids.insert(uid);
4788 }
4789 }
4790 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004791}
4792
Varun Shahb42f1eb2019-04-16 14:45:13 -07004793int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4794 Mutex::Autolock _l(mUidLock);
4795 return getProcStateLocked(uid);
4796}
4797
4798int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4799 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4800 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004801 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004802 }
4803 return procState;
4804}
4805
Austin Borgered99f642023-06-01 16:51:35 -07004806void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4807 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004808 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004809}
4810
Austin Borgered99f642023-06-01 16:51:35 -07004811void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004812 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004813}
4814
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004815void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4816 Mutex::Autolock _l(mUidLock);
4817 ALOGV("UidPolicy: ActivityManager has died");
4818 mRegistered = false;
4819 mActiveUids.clear();
4820}
4821
Austin Borgered99f642023-06-01 16:51:35 -07004822void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004823 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004824 bool wasActive = false;
4825 bool isActive = false;
4826 {
4827 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004828 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004829 mOverrideUids.erase(uid);
4830 if (insert) {
4831 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4832 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004833 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004834 }
4835 if (wasActive != isActive && !isActive) {
4836 sp<CameraService> service = mService.promote();
4837 if (service != nullptr) {
4838 service->blockClientsForUid(uid);
4839 }
4840 }
4841}
4842
4843// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004844// SensorPrivacyPolicy
4845// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004846
4847void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4848{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004849 Mutex::Autolock _l(mSensorPrivacyLock);
4850 if (mRegistered) {
4851 return;
4852 }
Evan Severson09ab4002021-02-10 14:15:19 -08004853 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004854 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004855 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004856 mSpm.addToggleSensorPrivacyListener(this);
4857 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004858 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004859 if (flags::camera_privacy_allowlist()) {
4860 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4861 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4862 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4863 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004864 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004865 if (res == OK) {
4866 mRegistered = true;
4867 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4868 }
4869}
4870
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004871void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4872 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004873 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004874 return;
4875 }
4876
4877 registerWithSensorPrivacyManager();
4878}
4879
4880void CameraService::SensorPrivacyPolicy::registerSelf() {
4881 // Use checkservice to see if the sensor_privacy service is available
4882 // If service is not available then register for notification
4883 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004884 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004885 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004886 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004887 } else {
4888 registerWithSensorPrivacyManager();
4889 }
4890}
4891
Michael Grooverd1d435a2018-12-18 17:39:42 -08004892void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4893 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004894 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004895 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004896 mSpm.removeToggleSensorPrivacyListener(this);
4897 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004898 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004899 mRegistered = false;
4900 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4901}
4902
4903bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004904 if (!mRegistered) {
4905 registerWithSensorPrivacyManager();
4906 }
4907
Michael Grooverd1d435a2018-12-18 17:39:42 -08004908 Mutex::Autolock _l(mSensorPrivacyLock);
4909 return mSensorPrivacyEnabled;
4910}
4911
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004912int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4913 if (!mRegistered) {
4914 registerWithSensorPrivacyManager();
4915 }
4916
4917 Mutex::Autolock _l(mSensorPrivacyLock);
4918 return mCameraPrivacyState;
4919}
4920
Evan Seversond0b69922022-01-27 10:47:34 -08004921bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004922 if (!hasCameraPrivacyFeature()) {
4923 return false;
4924 }
Evan Seversond0b69922022-01-27 10:47:34 -08004925 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004926}
4927
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004928bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4929 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004930 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004931 }
4932 return mSpm.isCameraPrivacyEnabled(packageName);
4933}
4934
Evan Seversond0b69922022-01-27 10:47:34 -08004935binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004936 int toggleType, int sensor, bool enabled) {
4937 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4938 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4939 {
4940 Mutex::Autolock _l(mSensorPrivacyLock);
4941 mSensorPrivacyEnabled = enabled;
4942 }
4943 // if sensor privacy is enabled then block all clients from accessing the camera
4944 if (enabled) {
4945 sp<CameraService> service = mService.promote();
4946 if (service != nullptr) {
4947 service->blockAllClients();
4948 }
4949 }
4950 }
4951 return binder::Status::ok();
4952}
4953
4954binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4955 int, int sensor, int state) {
4956 if (!flags::camera_privacy_allowlist()
4957 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4958 return binder::Status::ok();
4959 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004960 {
4961 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004962 mCameraPrivacyState = state;
4963 }
4964 sp<CameraService> service = mService.promote();
4965 if (!service) {
4966 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004967 }
4968 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004969 if (state == SensorPrivacyManager::ENABLED) {
4970 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08004971 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004972 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004973 }
4974 return binder::Status::ok();
4975}
4976
4977void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
4978 Mutex::Autolock _l(mSensorPrivacyLock);
4979 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
4980 mRegistered = false;
4981}
4982
Evan Severson09ab4002021-02-10 14:15:19 -08004983bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08004984 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
4985 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4986 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
4987 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4988 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08004989}
4990
Michael Grooverd1d435a2018-12-18 17:39:42 -08004991// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08004992// CameraState
4993// ----------------------------------------------------------------------------
4994
Austin Borgered99f642023-06-01 16:51:35 -07004995CameraService::CameraState::CameraState(const std::string& id, int cost,
4996 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004997 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07004998 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00004999 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005000
5001CameraService::CameraState::~CameraState() {}
5002
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005003CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005004 Mutex::Autolock lock(mStatusLock);
5005 return mStatus;
5006}
5007
Austin Borgered99f642023-06-01 16:51:35 -07005008std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005009 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005010 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005011 return res;
5012}
5013
Ruben Brunkcc776712015-02-17 20:18:47 -08005014CameraParameters CameraService::CameraState::getShimParams() const {
5015 return mShimParams;
5016}
5017
5018void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5019 mShimParams = params;
5020}
5021
5022int CameraService::CameraState::getCost() const {
5023 return mCost;
5024}
5025
Austin Borgered99f642023-06-01 16:51:35 -07005026std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005027 return mConflicting;
5028}
5029
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005030SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5031 return mSystemCameraKind;
5032}
5033
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005034bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5035 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5036 != mPhysicalCameras.end();
5037}
5038
Austin Borgered99f642023-06-01 16:51:35 -07005039bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005040 Mutex::Autolock lock(mStatusLock);
5041 auto result = mUnavailablePhysicalIds.insert(physicalId);
5042 return result.second;
5043}
5044
Austin Borgered99f642023-06-01 16:51:35 -07005045bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005046 Mutex::Autolock lock(mStatusLock);
5047 auto count = mUnavailablePhysicalIds.erase(physicalId);
5048 return count > 0;
5049}
5050
Austin Borgered99f642023-06-01 16:51:35 -07005051void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005052 Mutex::Autolock lock(mStatusLock);
5053 mClientPackage = clientPackage;
5054}
5055
Austin Borgered99f642023-06-01 16:51:35 -07005056std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005057 Mutex::Autolock lock(mStatusLock);
5058 return mClientPackage;
5059}
5060
Ruben Brunkcc776712015-02-17 20:18:47 -08005061// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005062// ClientEventListener
5063// ----------------------------------------------------------------------------
5064
5065void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005066 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005067 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005068 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005069 if (basicClient.get() != nullptr) {
5070 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005071 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005072 static_cast<int>(basicClient->getClientUid()));
5073 }
5074}
5075
5076void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005077 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005078 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005079 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005080 if (basicClient.get() != nullptr) {
5081 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005082 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005083 static_cast<int>(basicClient->getClientUid()));
5084 }
5085}
5086
Ruben Brunk99e69712015-05-26 17:25:07 -07005087// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005088// CameraClientManager
5089// ----------------------------------------------------------------------------
5090
Ruben Brunk99e69712015-05-26 17:25:07 -07005091CameraService::CameraClientManager::CameraClientManager() {
5092 setListener(std::make_shared<ClientEventListener>());
5093}
5094
Ruben Brunkcc776712015-02-17 20:18:47 -08005095CameraService::CameraClientManager::~CameraClientManager() {}
5096
5097sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005098 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005099 auto descriptor = get(id);
5100 if (descriptor == nullptr) {
5101 return sp<BasicClient>{nullptr};
5102 }
5103 return descriptor->getValue();
5104}
5105
Austin Borgered99f642023-06-01 16:51:35 -07005106std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005107 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005108 std::ostringstream ret;
5109 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005110 bool hasAny = false;
5111 for (auto& i : all) {
5112 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005113 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005114 int32_t cost = i->getCost();
5115 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005116 int32_t score = i->getPriority().getScore();
5117 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005118 auto conflicting = i->getConflicting();
5119 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005120 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005121 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005122 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005123 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005124 uid_t clientUid = clientSp->getClientUid();
5125 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005126 }
Austin Borgered99f642023-06-01 16:51:35 -07005127 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5128 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005129
Ruben Brunk6267b532015-04-30 17:44:07 -07005130 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005131 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005132 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005133 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005134 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005135 }
5136
Austin Borgered99f642023-06-01 16:51:35 -07005137 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005138 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005139 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005140 }
Austin Borgered99f642023-06-01 16:51:35 -07005141 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005142 }
Austin Borgered99f642023-06-01 16:51:35 -07005143 if (hasAny) ret << "\n";
5144 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005145 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005146}
5147
5148CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005149 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5150 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005151 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005152
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005153 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005154 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005155
Austin Borgered99f642023-06-01 16:51:35 -07005156 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005157 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5158 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005159}
5160
5161CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005162 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005163 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005164 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005165 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005166 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5167 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005168}
5169
5170// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005171// InjectionStatusListener
5172// ----------------------------------------------------------------------------
5173
5174void CameraService::InjectionStatusListener::addListener(
5175 const sp<ICameraInjectionCallback>& callback) {
5176 Mutex::Autolock lock(mListenerLock);
5177 if (mCameraInjectionCallback) return;
5178 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5179 if (res == OK) {
5180 mCameraInjectionCallback = callback;
5181 }
5182}
5183
5184void CameraService::InjectionStatusListener::removeListener() {
5185 Mutex::Autolock lock(mListenerLock);
5186 if (mCameraInjectionCallback == nullptr) {
5187 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5188 return;
5189 }
5190 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5191 mCameraInjectionCallback = nullptr;
5192}
5193
5194void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005195 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005196 if (mCameraInjectionCallback == nullptr) {
5197 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5198 return;
5199 }
Cliff Wud3a05312021-04-26 23:07:31 +08005200
5201 switch (err) {
5202 case -ENODEV:
5203 mCameraInjectionCallback->onInjectionError(
5204 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5205 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005206 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005207 break;
5208 case -EBUSY:
5209 mCameraInjectionCallback->onInjectionError(
5210 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5211 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005212 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005213 break;
5214 case DEAD_OBJECT:
5215 mCameraInjectionCallback->onInjectionError(
5216 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5217 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005218 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005219 break;
5220 case INVALID_OPERATION:
5221 mCameraInjectionCallback->onInjectionError(
5222 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5223 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005224 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005225 break;
5226 case UNKNOWN_TRANSACTION:
5227 mCameraInjectionCallback->onInjectionError(
5228 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5229 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005230 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005231 break;
5232 default:
5233 mCameraInjectionCallback->onInjectionError(
5234 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5235 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005236 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005237 }
Cliff Wud8cae102021-03-11 01:37:42 +08005238}
5239
5240void CameraService::InjectionStatusListener::binderDied(
5241 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005242 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5243 auto parent = mParent.promote();
5244 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005245 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5246 if (clientDescriptor != nullptr) {
5247 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5248 baseClientPtr->stopInjection();
5249 }
Cliff Wu3b268182021-07-06 15:44:43 +08005250 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005251 }
5252}
5253
5254// ----------------------------------------------------------------------------
5255// CameraInjectionSession
5256// ----------------------------------------------------------------------------
5257
5258binder::Status CameraService::CameraInjectionSession::stopInjection() {
5259 Mutex::Autolock lock(mInjectionSessionLock);
5260 auto parent = mParent.promote();
5261 if (parent == nullptr) {
5262 ALOGE("CameraInjectionSession: Parent is gone");
5263 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5264 "Camera service encountered error");
5265 }
Cliff Wud3a05312021-04-26 23:07:31 +08005266
5267 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005268 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5269 if (clientDescriptor != nullptr) {
5270 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5271 res = baseClientPtr->stopInjection();
5272 if (res != OK) {
5273 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5274 " ret != NO_ERROR: %d", res);
5275 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5276 "Camera session encountered error");
5277 }
5278 }
Cliff Wu3b268182021-07-06 15:44:43 +08005279 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005280 return binder::Status::ok();
5281}
5282
5283// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005284
5285static const int kDumpLockRetries = 50;
5286static const int kDumpLockSleep = 60000;
5287
5288static bool tryLock(Mutex& mutex)
5289{
5290 bool locked = false;
5291 for (int i = 0; i < kDumpLockRetries; ++i) {
5292 if (mutex.tryLock() == NO_ERROR) {
5293 locked = true;
5294 break;
5295 }
5296 usleep(kDumpLockSleep);
5297 }
5298 return locked;
5299}
5300
Rucha Katakwardf223072021-06-15 10:21:00 -07005301void CameraService::cacheDump() {
5302 if (mMemFd != -1) {
5303 const Vector<String16> args;
5304 ATRACE_CALL();
5305 // Acquiring service lock here will avoid the deadlock since
5306 // cacheDump will not be called during the second disconnect.
5307 Mutex::Autolock lock(mServiceLock);
5308
5309 Mutex::Autolock l(mCameraStatesLock);
5310 // Start collecting the info for open sessions and store it in temp file.
5311 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005312 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005313 auto clientDescriptor = mActiveClientManager.get(cameraId);
5314 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005315 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005316 // Log the current open session info before device is disconnected.
5317 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5318 }
5319 }
5320 }
5321}
5322
Mathias Agopian65ab4712010-07-14 17:59:35 -07005323status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005324 ATRACE_CALL();
5325
Austin Borgered99f642023-06-01 16:51:35 -07005326 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005327 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005328 getCallingPid(),
5329 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005330 return NO_ERROR;
5331 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005332 bool locked = tryLock(mServiceLock);
5333 // failed to lock - CameraService is probably deadlocked
5334 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005335 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005336 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005337
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005338 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005339 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005340
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005341 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005342 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005343
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005344 if (locked) mServiceLock.unlock();
5345 return NO_ERROR;
5346 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005347 dprintf(fd, "\n== Service global info: ==\n\n");
5348 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005349 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005350 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5351 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005352 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5353 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5354 }
Austin Borgered99f642023-06-01 16:51:35 -07005355 std::string activeClientString = mActiveClientManager.toString();
5356 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5357 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005358 if (mStreamUseCaseOverrides.size() > 0) {
5359 dprintf(fd, "Active stream use case overrides:");
5360 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5361 dprintf(fd, " %" PRId64, useCaseOverride);
5362 }
5363 dprintf(fd, "\n");
5364 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005365
5366 dumpEventLog(fd);
5367
5368 bool stateLocked = tryLock(mCameraStatesLock);
5369 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005370 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005371 }
5372
Emilian Peevbd8c5032018-02-14 23:05:40 +00005373 int argSize = args.size();
5374 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005375 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005376 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005377 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005378 }
5379 break;
5380 }
5381 }
5382
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005383 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005384 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005385
Austin Borgered99f642023-06-01 16:51:35 -07005386 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005387
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005388 CameraParameters p = state.second->getShimParams();
5389 if (!p.isEmpty()) {
5390 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5391 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005392 }
5393
5394 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005395 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005396 // log the current open session info
5397 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005398 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005399 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005400 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005401
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005402 }
5403
5404 if (stateLocked) mCameraStatesLock.unlock();
5405
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005406 if (locked) mServiceLock.unlock();
5407
Emilian Peevf53f66e2017-04-11 14:29:43 +01005408 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005409
5410 dprintf(fd, "\n== Vendor tags: ==\n\n");
5411
5412 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5413 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005414 sp<VendorTagDescriptorCache> cache =
5415 VendorTagDescriptorCache::getGlobalVendorTagCache();
5416 if (cache == NULL) {
5417 dprintf(fd, "No vendor tags.\n");
5418 } else {
5419 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5420 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005421 } else {
5422 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5423 }
5424
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005425 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005426 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005427 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005428
5429 // Process dump arguments, if any
5430 int n = args.size();
5431 String16 verboseOption("-v");
5432 String16 unreachableOption("--unreachable");
5433 for (int i = 0; i < n; i++) {
5434 if (args[i] == verboseOption) {
5435 // change logging level
5436 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005437 std::string levelStr = toStdString(args[i+1]);
5438 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005439 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005440 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005441 } else if (args[i] == unreachableOption) {
5442 // Dump memory analysis
5443 // TODO - should limit be an argument parameter?
5444 UnreachableMemoryInfo info;
5445 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5446 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005447 dprintf(fd, "\n== Unable to dump unreachable memory. "
5448 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005449 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005450 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005451 std::string s = info.ToString(/*log_contents*/ true);
5452 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005453 }
5454 }
5455 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005456
5457 bool serviceLocked = tryLock(mServiceLock);
5458
5459 // Dump info from previous open sessions.
5460 // Reposition the offset to beginning of the file before reading
5461
5462 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5463 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5464 ssize_t size_read;
5465 char buf[4096];
5466 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5467 // Read data from file to a small buffer and write it to fd.
5468 write(fd, buf, size_read);
5469 if (size_read == -1) {
5470 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5471 break;
5472 }
5473 }
5474 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5475 } else {
5476 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5477 }
5478
5479 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005480 return NO_ERROR;
5481}
5482
Rucha Katakwardf223072021-06-15 10:21:00 -07005483void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005484 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005485 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005486 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005487 getFormattedCurrentTime().c_str(),
5488 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005489 dprintf(fd, " Client priority score: %d state: %d\n",
5490 clientDescriptor->getPriority().getScore(),
5491 clientDescriptor->getPriority().getState());
5492 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5493
5494 auto client = clientDescriptor->getValue();
5495 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005496 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005497
5498 client->dumpClient(fd, args);
5499}
5500
Austin Borgered99f642023-06-01 16:51:35 -07005501void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005502 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005503 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005504}
5505
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005506void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005507 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005508
5509 Mutex::Autolock l(mLogLock);
5510 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005511 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005512 }
5513
5514 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005515 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005516 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005517 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005518 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005519 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005520}
5521
Austin Borgered99f642023-06-01 16:51:35 -07005522void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005523 Mutex::Autolock lock(mLogLock);
5524 if (!isClientWatchedLocked(client)) { return; }
5525
5526 std::vector<std::string> dumpVector;
5527 client->dumpWatchedEventsToVector(dumpVector);
5528
5529 if (dumpVector.empty()) { return; }
5530
Austin Borgered99f642023-06-01 16:51:35 -07005531 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005532
Austin Borgered99f642023-06-01 16:51:35 -07005533 std::string currentTime = getFormattedCurrentTime();
5534 dumpString << "Cached @ ";
5535 dumpString << currentTime;
5536 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005537
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005538 size_t i = dumpVector.size();
5539
5540 // Store the string in reverse order (latest last)
5541 while (i > 0) {
5542 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005543 dumpString << cameraId;
5544 dumpString << ":";
5545 dumpString << client->getPackageName();
5546 dumpString << " ";
5547 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005548 }
5549
Austin Borgered99f642023-06-01 16:51:35 -07005550 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005551}
5552
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005553void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005554 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005555 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5556 if (mTorchClientMap[i] == who) {
5557 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005558 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005559 status_t res = mFlashlight->setTorchMode(cameraId, false);
5560 if (res) {
5561 ALOGE("%s: torch client died but couldn't turn off torch: "
5562 "%s (%d)", __FUNCTION__, strerror(-res), res);
5563 return;
5564 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005565 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005566 break;
5567 }
5568 }
5569}
5570
Ruben Brunkcc776712015-02-17 20:18:47 -08005571/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005572
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005573 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005574 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5575 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005576 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005577 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005578 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005579
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005580 // check torch client
5581 handleTorchClientBinderDied(who);
5582
5583 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005584 if(!evictClientIdByRemote(who)) {
5585 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005586 return;
5587 }
5588
Ruben Brunkcc776712015-02-17 20:18:47 -08005589 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5590 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005591}
5592
Austin Borgered99f642023-06-01 16:51:35 -07005593void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005594 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005595}
5596
Austin Borgered99f642023-06-01 16:51:35 -07005597void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005598 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005599 // Do not lock mServiceLock here or can get into a deadlock from
5600 // connect() -> disconnect -> updateStatus
5601
5602 auto state = getCameraState(cameraId);
5603
5604 if (state == nullptr) {
5605 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005606 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005607 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005608 }
5609
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005610 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5611 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5612 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005613 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005614 return;
5615 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005616
Biswarup Pal37a75182024-01-16 15:53:35 +00005617 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5618 CameraMetadata cameraInfo;
5619 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005620 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005621 if (res != OK) {
5622 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5623 __FUNCTION__, cameraId.c_str());
5624 } else {
5625 int32_t deviceId = getDeviceId(cameraInfo);
5626 if (deviceId != kDefaultDeviceId) {
5627 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5628 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5629 static_cast<camera_metadata_enum_android_lens_facing_t>(
5630 lensFacingEntry.data.u8[0]);
5631 std::string mappedCameraId;
5632 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5633 mappedCameraId = kVirtualDeviceBackCameraId;
5634 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5635 mappedCameraId = kVirtualDeviceFrontCameraId;
5636 } else {
5637 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5638 __func__);
5639 }
5640 if (!mappedCameraId.empty()) {
5641 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5642 }
5643 }
5644 }
5645 }
5646
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005647 // Collect the logical cameras without holding mStatusLock in updateStatus
5648 // as that can lead to a deadlock(b/162192331).
5649 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005650 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005651 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005652 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005653 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005654 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005655 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5656 auto [deviceId, mappedCameraId] =
5657 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005658
Biswarup Pal37a75182024-01-16 15:53:35 +00005659 if (status != StatusInternal::ENUMERATING) {
5660 // Update torch status if it has a flash unit.
5661 Mutex::Autolock al(mTorchStatusMutex);
5662 TorchModeStatus torchStatus;
5663 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5664 NAME_NOT_FOUND) {
5665 TorchModeStatus newTorchStatus =
5666 status == StatusInternal::PRESENT ?
5667 TorchModeStatus::AVAILABLE_OFF :
5668 TorchModeStatus::NOT_AVAILABLE;
5669 if (torchStatus != newTorchStatus) {
5670 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5671 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005672 }
5673 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005674
Biswarup Pal37a75182024-01-16 15:53:35 +00005675 Mutex::Autolock lock(mStatusListenerLock);
5676 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5677 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005678
Biswarup Pal37a75182024-01-16 15:53:35 +00005679 for (auto& listener : mListenerList) {
5680 bool isVendorListener = listener->isVendorListener();
5681 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5682 listener->getListenerPid(), listener->getListenerUid())) {
5683 ALOGV("Skipping discovery callback for system-only camera device %s",
5684 cameraId.c_str());
5685 continue;
5686 }
5687
5688 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5689 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005690 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005691 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005692 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5693 ret.exceptionCode());
5694 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005695 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005696}
5697
Austin Borgered99f642023-06-01 16:51:35 -07005698void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5699 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005700 auto state = getCameraState(cameraId);
5701 if (state == nullptr) {
5702 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005703 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005704 return;
5705 }
5706 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005707 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005708 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005709 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005710 }
5711
Biswarup Pal37a75182024-01-16 15:53:35 +00005712 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5713 auto [deviceId, mappedCameraId] =
5714 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5715
Shuzhen Wang695044d2020-03-06 09:02:23 -08005716 Mutex::Autolock lock(mStatusListenerLock);
5717
5718 for (const auto& it : mListenerList) {
5719 if (!it->isOpenCloseCallbackAllowed()) {
5720 continue;
5721 }
5722
5723 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005724 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005725 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5726 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005727 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005728 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005729 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005730
5731 it->handleBinderStatus(ret,
5732 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5733 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005734 }
5735}
5736
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005737template<class Func>
5738void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005739 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005740 std::initializer_list<StatusInternal> rejectSourceStates,
5741 Func onStatusUpdatedLocked) {
5742 Mutex::Autolock lock(mStatusLock);
5743 StatusInternal oldStatus = mStatus;
5744 mStatus = status;
5745
5746 if (oldStatus == status) {
5747 return;
5748 }
5749
5750 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005751 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005752
5753 if (oldStatus == StatusInternal::NOT_PRESENT &&
5754 (status != StatusInternal::PRESENT &&
5755 status != StatusInternal::ENUMERATING)) {
5756
5757 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5758 __FUNCTION__);
5759 mStatus = oldStatus;
5760 return;
5761 }
5762
5763 /**
5764 * Sometimes we want to conditionally do a transition.
5765 * For example if a client disconnects, we want to go to PRESENT
5766 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5767 */
5768 for (auto& rejectStatus : rejectSourceStates) {
5769 if (oldStatus == rejectStatus) {
5770 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005771 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005772 mStatus = oldStatus;
5773 return;
5774 }
5775 }
5776
5777 onStatusUpdatedLocked(cameraId, status);
5778}
5779
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005780status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005781 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005782 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005783 if (!status) {
5784 return BAD_VALUE;
5785 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005786 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5787 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005788 // invalid camera ID or the camera doesn't have a flash unit
5789 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005790 }
5791
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005792 *status = mTorchStatusMap.valueAt(index);
5793 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005794}
5795
Austin Borgered99f642023-06-01 16:51:35 -07005796status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005797 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005798 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5799 if (index == NAME_NOT_FOUND) {
5800 return BAD_VALUE;
5801 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005802 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005803
5804 return OK;
5805}
5806
Austin Borgered99f642023-06-01 16:51:35 -07005807std::list<std::string> CameraService::getLogicalCameras(
5808 const std::string& physicalCameraId) {
5809 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005810 Mutex::Autolock lock(mCameraStatesLock);
5811 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005812 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5813 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005814 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005815 }
5816 return retList;
5817}
5818
5819void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005820 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005821 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005822 // mStatusListenerLock is expected to be locked
5823 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005824 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005825 // Note: we check only the deviceKind of the physical camera id
5826 // since, logical camera ids and their physical camera ids are
5827 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005828 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5829 listener->getListenerPid(), listener->getListenerUid())) {
5830 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005831 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005832 continue;
5833 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005834 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005835 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005836 listener->handleBinderStatus(ret,
5837 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5838 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5839 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005840 }
5841 }
5842}
5843
Svet Ganova453d0d2018-01-11 15:37:58 -08005844void CameraService::blockClientsForUid(uid_t uid) {
5845 const auto clients = mActiveClientManager.getAll();
5846 for (auto& current : clients) {
5847 if (current != nullptr) {
5848 const auto basicClient = current->getValue();
5849 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5850 basicClient->block();
5851 }
5852 }
5853 }
5854}
5855
Michael Grooverd1d435a2018-12-18 17:39:42 -08005856void CameraService::blockAllClients() {
5857 const auto clients = mActiveClientManager.getAll();
5858 for (auto& current : clients) {
5859 if (current != nullptr) {
5860 const auto basicClient = current->getValue();
5861 if (basicClient.get() != nullptr) {
5862 basicClient->block();
5863 }
5864 }
5865 }
5866}
5867
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005868void CameraService::blockPrivacyEnabledClients() {
5869 const auto clients = mActiveClientManager.getAll();
5870 for (auto& current : clients) {
5871 if (current != nullptr) {
5872 const auto basicClient = current->getValue();
5873 if (basicClient.get() != nullptr) {
5874 std::string pkgName = basicClient->getPackageName();
5875 bool cameraPrivacyEnabled =
5876 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5877 if (cameraPrivacyEnabled) {
5878 basicClient->block();
5879 }
5880 }
5881 }
5882 }
5883}
5884
Svet Ganova453d0d2018-01-11 15:37:58 -08005885// NOTE: This is a remote API - make sure all args are validated
5886status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005887 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005888 return PERMISSION_DENIED;
5889 }
5890 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5891 return BAD_VALUE;
5892 }
Austin Borgered99f642023-06-01 16:51:35 -07005893 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005894 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005895 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005896 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005897 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005898 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005899 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005900 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005901 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005902 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005903 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005904 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005905 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005906 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005907 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005908 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005909 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005910 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005911 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005912 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005913 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005914 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005915 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005916 handleClearStreamUseCaseOverrides();
5917 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005918 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005919 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005920 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005921 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005922 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005923 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005924 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005925 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005926 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005927 }
5928 printHelp(err);
5929 return BAD_VALUE;
5930}
5931
5932status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005933 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005934
Svet Ganova453d0d2018-01-11 15:37:58 -08005935 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005936 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005937 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005938 } else if ((args[2] != toString16("idle"))) {
5939 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005940 return BAD_VALUE;
5941 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005942
5943 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005944 if (args.size() >= 5 && args[3] == toString16("--user")) {
5945 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005946 }
5947
5948 uid_t uid;
5949 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5950 return BAD_VALUE;
5951 }
5952
5953 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005954 return NO_ERROR;
5955}
5956
5957status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005958 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005959
5960 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005961 if (args.size() >= 4 && args[2] == toString16("--user")) {
5962 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005963 }
5964
5965 uid_t uid;
5966 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005967 return BAD_VALUE;
5968 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005969
5970 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08005971 return NO_ERROR;
5972}
5973
5974status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005975 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005976
5977 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005978 if (args.size() >= 4 && args[2] == toString16("--user")) {
5979 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005980 }
5981
5982 uid_t uid;
5983 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005984 return BAD_VALUE;
5985 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005986
5987 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005988 return dprintf(out, "active\n");
5989 } else {
5990 return dprintf(out, "idle\n");
5991 }
5992}
5993
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005994status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005995 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005996 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
5997 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
5998 Mutex::Autolock lock(mServiceLock);
5999
6000 mOverrideRotateAndCropMode = rotateValue;
6001
6002 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6003
6004 const auto clients = mActiveClientManager.getAll();
6005 for (auto& current : clients) {
6006 if (current != nullptr) {
6007 const auto basicClient = current->getValue();
6008 if (basicClient.get() != nullptr) {
6009 basicClient->setRotateAndCropOverride(rotateValue);
6010 }
6011 }
6012 }
6013
6014 return OK;
6015}
6016
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006017status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6018 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006019 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006020 if ((*end != '\0') ||
6021 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6022 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6023 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6024 return BAD_VALUE;
6025 }
6026
6027 Mutex::Autolock lock(mServiceLock);
6028 mOverrideAutoframingMode = autoframingValue;
6029
6030 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6031
6032 const auto clients = mActiveClientManager.getAll();
6033 for (auto& current : clients) {
6034 if (current != nullptr) {
6035 const auto basicClient = current->getValue();
6036 if (basicClient.get() != nullptr) {
6037 basicClient->setAutoframingOverride(autoframingValue);
6038 }
6039 }
6040 }
6041
6042 return OK;
6043}
6044
Ravneetaeb20dc2022-03-30 05:33:03 +00006045status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006046 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006047
6048 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6049
6050 Mutex::Autolock lock(mServiceLock);
6051
6052 mCameraServiceWatchdogEnabled = enableWatchdog;
6053
6054 const auto clients = mActiveClientManager.getAll();
6055 for (auto& current : clients) {
6056 if (current != nullptr) {
6057 const auto basicClient = current->getValue();
6058 if (basicClient.get() != nullptr) {
6059 basicClient->setCameraServiceWatchdog(enableWatchdog);
6060 }
6061 }
6062 }
6063
6064 return OK;
6065}
6066
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006067status_t CameraService::handleGetRotateAndCrop(int out) {
6068 Mutex::Autolock lock(mServiceLock);
6069
6070 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6071}
6072
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006073status_t CameraService::handleGetAutoframing(int out) {
6074 Mutex::Autolock lock(mServiceLock);
6075
6076 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6077}
6078
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006079status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6080 char *endPtr;
6081 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006082 std::string maskString = toStdString(args[1]);
6083 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006084
6085 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006086 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006087 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6088
6089 Mutex::Autolock lock(mServiceLock);
6090
6091 mImageDumpMask = maskValue;
6092
6093 return OK;
6094}
6095
6096status_t CameraService::handleGetImageDumpMask(int out) {
6097 Mutex::Autolock lock(mServiceLock);
6098
6099 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6100}
6101
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006102status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006103 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006104 if (errno != 0) return BAD_VALUE;
6105
6106 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6107 Mutex::Autolock lock(mServiceLock);
6108
6109 mOverrideCameraMuteMode = (muteValue == 1);
6110
6111 const auto clients = mActiveClientManager.getAll();
6112 for (auto& current : clients) {
6113 if (current != nullptr) {
6114 const auto basicClient = current->getValue();
6115 if (basicClient.get() != nullptr) {
6116 if (basicClient->supportsCameraMute()) {
6117 basicClient->setCameraMute(mOverrideCameraMuteMode);
6118 }
6119 }
6120 }
6121 }
6122
6123 return OK;
6124}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006125
Shuzhen Wang16610a62022-12-15 22:38:07 -08006126status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6127 std::vector<int64_t> useCasesOverride;
6128 for (size_t i = 1; i < args.size(); i++) {
6129 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006130 std::string arg = toStdString(args[i]);
6131 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006132 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006133 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006134 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006135 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006136 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006137 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006138 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006139 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006140 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006141 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006142 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006143 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006144 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6145 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006146 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006147 return BAD_VALUE;
6148 }
6149 useCasesOverride.push_back(useCase);
6150 }
6151
6152 Mutex::Autolock lock(mServiceLock);
6153 mStreamUseCaseOverrides = std::move(useCasesOverride);
6154
6155 return OK;
6156}
6157
6158void CameraService::handleClearStreamUseCaseOverrides() {
6159 Mutex::Autolock lock(mServiceLock);
6160 mStreamUseCaseOverrides.clear();
6161}
6162
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006163status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6164 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006165 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006166 if ((*end != '\0') ||
6167 (zoomOverrideValue != -1 &&
6168 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6169 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6170 return BAD_VALUE;
6171 }
6172
6173 Mutex::Autolock lock(mServiceLock);
6174 mZoomOverrideValue = zoomOverrideValue;
6175
6176 const auto clients = mActiveClientManager.getAll();
6177 for (auto& current : clients) {
6178 if (current != nullptr) {
6179 const auto basicClient = current->getValue();
6180 if (basicClient.get() != nullptr) {
6181 if (basicClient->supportsZoomOverride()) {
6182 basicClient->setZoomOverride(mZoomOverrideValue);
6183 }
6184 }
6185 }
6186 }
6187
6188 return OK;
6189}
6190
Avichal Rakesh84147132021-11-11 17:47:11 -08006191status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006192 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006193 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006194 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006195 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006196 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006197 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006198 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006199 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006200 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006201 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006202 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006203 dprintf(outFd, "Camera service watch commands:\n"
6204 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6205 " starts watching the provided tags for clients with provided package\n"
6206 " recognizes tag shorthands like '3a'\n"
6207 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006208 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006209 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006210 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006211 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006212 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006213 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006214 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006215}
6216
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006217status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6218 Mutex::Autolock lock(mLogLock);
6219 size_t tagsIdx; // index of '-m'
6220 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006221 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006222 if (tagsIdx < args.size() - 1) {
6223 tags = args[tagsIdx + 1];
6224 } else {
6225 dprintf(outFd, "No tags provided.\n");
6226 return BAD_VALUE;
6227 }
6228
6229 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006230 // watch all clients if no clients are provided
6231 String16 clients = toString16(kWatchAllClientsFlag);
6232 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006233 clientsIdx++);
6234 if (clientsIdx < args.size() - 1) {
6235 clients = args[clientsIdx + 1];
6236 }
Austin Borgered99f642023-06-01 16:51:35 -07006237 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006238
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006239 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006240 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006241
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006242 bool serviceLock = tryLock(mServiceLock);
6243 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006244 auto cameraClients = mActiveClientManager.getAll();
6245 for (const auto &clientDescriptor: cameraClients) {
6246 if (clientDescriptor == nullptr) { continue; }
6247 sp<BasicClient> client = clientDescriptor->getValue();
6248 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006249
6250 if (isClientWatchedLocked(client.get())) {
6251 client->startWatchingTags(mMonitorTags, outFd);
6252 numWatchedClients++;
6253 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006254 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006255 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6256
6257 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006258 return OK;
6259}
6260
6261status_t CameraService::stopWatchingTags(int outFd) {
6262 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006263 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006264 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006265
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006266 mWatchedClientPackages.clear();
6267 mWatchedClientsDumpCache.clear();
6268
6269 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006270 auto cameraClients = mActiveClientManager.getAll();
6271 for (const auto &clientDescriptor : cameraClients) {
6272 if (clientDescriptor == nullptr) { continue; }
6273 sp<BasicClient> client = clientDescriptor->getValue();
6274 if (client.get() == nullptr) { continue; }
6275 client->stopWatchingTags(outFd);
6276 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006277 dprintf(outFd, "Stopped watching all clients.\n");
6278 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006279 return OK;
6280}
6281
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006282status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6283 Mutex::Autolock lock(mLogLock);
6284 size_t clearedSize = mWatchedClientsDumpCache.size();
6285 mWatchedClientsDumpCache.clear();
6286 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6287 return OK;
6288}
6289
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006290status_t CameraService::printWatchedTags(int outFd) {
6291 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006292 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006293
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006294 bool printedSomething = false; // tracks if any monitoring information was printed
6295 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006296
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006297 bool serviceLock = tryLock(mServiceLock);
6298 // get all watched clients that are currently connected
6299 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6300 if (clientDescriptor == nullptr) { continue; }
6301
6302 sp<BasicClient> client = clientDescriptor->getValue();
6303 if (client.get() == nullptr) { continue; }
6304 if (!isClientWatchedLocked(client.get())) { continue; }
6305
6306 std::vector<std::string> dumpVector;
6307 client->dumpWatchedEventsToVector(dumpVector);
6308
6309 size_t printIdx = dumpVector.size();
6310 if (printIdx == 0) {
6311 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006312 }
6313
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006314 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006315 const std::string &cameraId = clientDescriptor->getKey();
6316 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006317 while(printIdx > 0) {
6318 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006319 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006320 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006321 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006322 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006323 printedSomething = true;
6324
6325 connectedMonitoredClients.emplace(client->getPackageName());
6326 }
6327 if (serviceLock) { mServiceLock.unlock(); }
6328
6329 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6330 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006331 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006332 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6333 continue;
6334 }
6335
Austin Borgered99f642023-06-01 16:51:35 -07006336 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006337 dprintf(outFd, "%s\n", kv.second.c_str());
6338 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006339 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006340
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006341 if (!printedSomething) {
6342 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006343 }
6344
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006345 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006346}
6347
Avichal Rakesh84147132021-11-11 17:47:11 -08006348// Print all events in vector `events' that came after lastPrintedEvent
6349void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006350 const std::string &cameraId,
6351 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006352 const std::vector<std::string> &events,
6353 const std::string &lastPrintedEvent) {
6354 if (events.empty()) { return; }
6355
6356 // index of lastPrintedEvent in events.
6357 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6358 size_t lastPrintedIdx;
6359 for (lastPrintedIdx = 0;
6360 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6361 lastPrintedIdx++);
6362
6363 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6364
Avichal Rakesh84147132021-11-11 17:47:11 -08006365 // print events in chronological order (latest event last)
6366 size_t idxToPrint = lastPrintedIdx;
6367 do {
6368 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006369 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6370 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006371 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006372}
6373
6374// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6375// command should be interrupted if the user presses the return key, or if user loses any way to
6376// signal interrupt.
6377// If timeoutMs == 0, this function will always return false
6378bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6379 struct timeval startTime;
6380 int startTimeError = gettimeofday(&startTime, nullptr);
6381 if (startTimeError) {
6382 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6383 return true;
6384 }
6385
6386 const nfds_t numFds = 1;
6387 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6388
6389 struct timeval currTime;
6390 char buffer[2];
6391 while(true) {
6392 int currTimeError = gettimeofday(&currTime, nullptr);
6393 if (currTimeError) {
6394 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6395 return true;
6396 }
6397
6398 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6399 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6400 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6401
6402 if (remainingTimeMs <= 0) {
6403 // No user interrupt within timeoutMs, don't interrupt watch command
6404 return false;
6405 }
6406
6407 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6408 if (numFdsUpdated < 0) {
6409 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6410 return true;
6411 }
6412
6413 if (numFdsUpdated == 0) {
6414 // No user input within timeoutMs, don't interrupt watch command
6415 return false;
6416 }
6417
6418 if (!(pollFd.revents & POLLIN)) {
6419 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6420 return true;
6421 }
6422
6423 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6424 if (sizeRead < 0) {
6425 dprintf(outFd, "Error reading user input. Exiting.\n");
6426 return true;
6427 }
6428
6429 if (sizeRead == 0) {
6430 // Reached end of input fd (can happen if input is piped)
6431 // User has no way to signal an interrupt, so interrupt here
6432 return true;
6433 }
6434
6435 if (buffer[0] == '\n') {
6436 // User pressed return, interrupt watch command.
6437 return true;
6438 }
6439 }
6440}
6441
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006442status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6443 int inFd, int outFd) {
6444 // Figure out refresh interval, if present in args
6445 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006446 if (args.size() > 2) {
6447 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006448 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006449 intervalIdx++);
6450
6451 size_t intervalValIdx = intervalIdx + 1;
6452 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006453 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006454 if (errno) { return BAD_VALUE; }
6455 }
6456 }
6457
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006458 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6459 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006460
Avichal Rakesh84147132021-11-11 17:47:11 -08006461 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006462 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006463
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006464 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006465 bool serviceLock = tryLock(mServiceLock);
6466 auto cameraClients = mActiveClientManager.getAll();
6467 if (serviceLock) { mServiceLock.unlock(); }
6468
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006469 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006470 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006471 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006472
6473 sp<BasicClient> client = clientDescriptor->getValue();
6474 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006475 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006476
Austin Borgered99f642023-06-01 16:51:35 -07006477 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006478 // This also initializes the map entries with an empty string
6479 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6480
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006481 std::vector<std::string> latestEvents;
6482 client->dumpWatchedEventsToVector(latestEvents);
6483
6484 if (!latestEvents.empty()) {
6485 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006486 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006487 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006488 latestEvents,
6489 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006490 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006491 }
6492 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006493 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006494 break;
6495 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006496 }
6497 return OK;
6498}
6499
Austin Borgered99f642023-06-01 16:51:35 -07006500void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006501 mWatchedClientPackages.clear();
6502
Austin Borgered99f642023-06-01 16:51:35 -07006503 std::istringstream iss(clients);
6504 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006505
Austin Borgered99f642023-06-01 16:51:35 -07006506 while (std::getline(iss, nextClient, ',')) {
6507 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006508 // Don't need to track any other package if 'all' is present
6509 mWatchedClientPackages.clear();
6510 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6511 break;
6512 }
6513
6514 // track package names
6515 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006516 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006517}
6518
Svet Ganova453d0d2018-01-11 15:37:58 -08006519status_t CameraService::printHelp(int out) {
6520 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006521 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6522 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6523 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006524 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6525 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6526 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006527 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6528 " Valid values 0=false, 1=true, 2=auto\n"
6529 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006530 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6531 " Valid values 0=OFF, 1=ON for JPEG\n"
6532 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006533 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006534 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6535 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6536 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6537 " on. In case the number of usecases is smaller than the number of streams, the\n"
6538 " last use case is assigned to all the remaining streams. In case of multiple\n"
6539 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6540 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6541 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6542 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006543 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6544 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006545 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6546 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006547 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006548 " help print this message\n");
6549}
6550
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006551bool CameraService::isClientWatched(const BasicClient *client) {
6552 Mutex::Autolock lock(mLogLock);
6553 return isClientWatchedLocked(client);
6554}
6555
6556bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6557 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6558 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6559}
6560
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006561int32_t CameraService::updateAudioRestriction() {
6562 Mutex::Autolock lock(mServiceLock);
6563 return updateAudioRestrictionLocked();
6564}
6565
6566int32_t CameraService::updateAudioRestrictionLocked() {
6567 int32_t mode = 0;
6568 // iterate through all active client
6569 for (const auto& i : mActiveClientManager.getAll()) {
6570 const auto clientSp = i->getValue();
6571 mode |= clientSp->getAudioRestriction();
6572 }
6573
6574 bool modeChanged = (mAudioRestriction != mode);
6575 mAudioRestriction = mode;
6576 if (modeChanged) {
6577 mAppOps.setCameraAudioRestriction(mode);
6578 }
6579 return mode;
6580}
6581
Austin Borgered99f642023-06-01 16:51:35 -07006582status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006583 sp<BasicClient> clientSp) {
6584 std::unique_ptr<AutoConditionLock> lock =
6585 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6586 status_t res = NO_ERROR;
6587 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006588 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006589 mInjectionStatusListener->notifyInjectionError(
6590 externalCamId, UNKNOWN_TRANSACTION);
6591 clientSp->notifyError(
6592 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6593 CaptureResultExtras());
6594
6595 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6596 // other clients from connecting in mServiceLockWrapper if held
6597 mServiceLock.unlock();
6598
6599 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006600 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006601 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006602 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006603
6604 // Reacquire mServiceLock
6605 mServiceLock.lock();
6606 }
6607
6608 return res;
6609}
6610
Cliff Wud3a05312021-04-26 23:07:31 +08006611void CameraService::clearInjectionParameters() {
6612 {
6613 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006614 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006615 mInjectionInternalCamId = "";
6616 }
6617 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006618 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006619}
6620
Biswarup Pal37a75182024-01-16 15:53:35 +00006621} // namespace android