blob: f7afeabacf7189a8d536da4382e4c75ce2a6173d [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#define LOG_TAG "CameraService"
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -070018#define ATRACE_TAG ATRACE_TAG_CAMERA
Iliyan Malchev8951a972011-04-14 16:55:59 -070019//#define LOG_NDEBUG 0
Mathias Agopian65ab4712010-07-14 17:59:35 -070020
Ruben Brunkcc776712015-02-17 20:18:47 -080021#include <algorithm>
22#include <climits>
Mathias Agopian65ab4712010-07-14 17:59:35 -070023#include <stdio.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080024#include <cstdlib>
Ruben Brunkcc776712015-02-17 20:18:47 -080025#include <cstring>
26#include <ctime>
Austin Borgered99f642023-06-01 16:51:35 -070027#include <iostream>
28#include <sstream>
Ruben Brunkcc776712015-02-17 20:18:47 -080029#include <string>
Mathias Agopian65ab4712010-07-14 17:59:35 -070030#include <sys/types.h>
Ruben Brunkcc776712015-02-17 20:18:47 -080031#include <inttypes.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070032#include <pthread.h>
Avichal Rakesh84147132021-11-11 17:47:11 -080033#include <poll.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080035#include <android/hardware/ICamera.h>
36#include <android/hardware/ICameraClient.h>
37
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -070038#include <aidl/AidlCameraService.h>
Alex Deymo9c2a2c22016-08-25 11:59:14 -070039#include <android-base/macros.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080040#include <android-base/parseint.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000041#include <android_companion_virtualdevice_flags.h>
42#include <android/companion/virtualnative/IVirtualDeviceManagerNative.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080043#include <binder/ActivityManager.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080044#include <binder/AppOpsManager.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070045#include <binder/IPCThreadState.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070046#include <binder/MemoryBase.h>
47#include <binder/MemoryHeapBase.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080048#include <binder/PermissionController.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080049#include <binder/IResultReceiver.h>
Steven Moreland89a2c5c2020-01-31 15:02:25 -080050#include <binderthreadstate/CallerUtils.h>
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -070051#include <com_android_internal_camera_flags.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070052#include <cutils/atomic.h>
Nipun Kwatrab5ca4612010-09-11 19:31:10 -070053#include <cutils/properties.h>
Svet Ganova453d0d2018-01-11 15:37:58 -080054#include <cutils/misc.h>
Mathias Agopiandf712ea2012-02-25 18:48:35 -080055#include <gui/Surface.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070056#include <hardware/hardware.h>
Jayant Chowdharybe543d42018-08-15 13:16:14 -070057#include "hidl/HidlCameraService.h"
58#include <hidl/HidlTransportSupport.h>
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -080059#include <hwbinder/IPCThreadState.h>
Eino-Ville Talvalad89821e2016-04-20 11:23:50 -070060#include <memunreachable/memunreachable.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070061#include <media/AudioSystem.h>
Andreas Huber1b86fe02014-01-29 11:13:26 -080062#include <media/IMediaHTTPService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070063#include <media/mediaplayer.h>
Ruben Brunk99e69712015-05-26 17:25:07 -070064#include <mediautils/BatteryNotifier.h>
Steven Moreland886d7322021-04-02 04:19:45 +000065#include <processinfo/ProcessInfoService.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070066#include <utils/Errors.h>
67#include <utils/Log.h>
68#include <utils/String16.h>
Svet Ganov94ec46f2018-06-08 15:03:46 -070069#include <utils/SystemClock.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080070#include <utils/Trace.h>
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -080071#include <utils/CallStack.h>
Chien-Yu Chen98a668f2015-12-18 14:10:33 -080072#include <private/android_filesystem_config.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080073#include <system/camera_vendor_tags.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070074#include <system/camera_metadata.h>
Kunal Malhotrabfc96052023-02-28 23:25:34 +000075#include <binder/IServiceManager.h>
76#include <binder/IActivityManager.h>
Biswarup Pal37a75182024-01-16 15:53:35 +000077#include <camera/CameraUtils.h>
Austin Borgered99f642023-06-01 16:51:35 -070078#include <camera/StringUtils.h>
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080079
Ruben Brunkb2119af2014-05-09 19:57:56 -070080#include <system/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070081
82#include "CameraService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070083#include "api1/Camera2Client.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070084#include "api2/CameraDeviceClient.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070085#include "utils/CameraServiceProxyWrapper.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000086#include "utils/CameraTraces.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070087#include "utils/SessionConfigurationUtils.h"
Emilian Peev31bd2422024-04-23 22:24:09 +000088#include "utils/TagMonitor.h"
89#include "utils/Utils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070090
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080091namespace {
92 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080093 const char* kActivityServiceName = "activity";
94 const char* kSensorPrivacyServiceName = "sensor_privacy";
95 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070096 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000097 const char* kVirtualDeviceBackCameraId = "0";
98 const char* kVirtualDeviceFrontCameraId = "1";
99
100 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
101 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
102 return android::kDefaultDeviceId;
103 }
104
105 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
106 return deviceIdEntry.data.i32[0];
107 }
108} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800109
Mathias Agopian65ab4712010-07-14 17:59:35 -0700110namespace android {
111
Austin Borgerea931242021-12-13 23:10:41 +0000112using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700113using namespace camera3::SessionConfigurationUtils;
114
115using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000116using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700117using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700118using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800119using hardware::ICamera;
120using hardware::ICameraClient;
121using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800122using hardware::camera2::ICameraInjectionCallback;
123using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800124using hardware::camera2::utils::CameraIdAndSessionConfiguration;
125using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000126
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700127namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000128namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800129
Mathias Agopian65ab4712010-07-14 17:59:35 -0700130// ----------------------------------------------------------------------------
131// Logging support -- this is for debugging only
132// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700133volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700134
Steve Blockb8a80522011-12-20 16:23:08 +0000135#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
136#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700137
138static void setLogLevel(int level) {
139 android_atomic_write(level, &gLogLevel);
140}
141
Henri Chataingbcb99452023-11-01 17:40:30 +0000142int32_t format_as(CameraService::StatusInternal s) {
143 return fmt::underlying(s);
144}
145
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146// ----------------------------------------------------------------------------
147
Austin Borger249e6592024-03-10 22:28:11 -0700148// Permission strings (references to AttributionAndPermissionUtils for brevity)
149static const std::string &sDumpPermission =
150 AttributionAndPermissionUtils::sDumpPermission;
151static const std::string &sManageCameraPermission =
152 AttributionAndPermissionUtils::sManageCameraPermission;
153static const std::string &sCameraSendSystemEventsPermission =
154 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
155static const std::string &sCameraInjectExternalCameraPermission =
156 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
157
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000158// Constant integer for FGS Logging, used to denote the API type for logger
159static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700160const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800161static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
162static constexpr int32_t kSystemNativeClientState =
163 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700164static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700165
Austin Borgered99f642023-06-01 16:51:35 -0700166const std::string CameraService::kOfflineDevice("offline-");
167const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700168
Biswarup Pal7d072862024-04-17 15:24:47 +0000169constexpr int32_t kInvalidDeviceId = -1;
170
Rucha Katakward9ea6452021-05-06 11:57:16 -0700171// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700172static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700173
Austin Borger74fca042022-05-23 12:41:21 -0700174CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700175 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
176 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
177 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
178 std::make_shared<AttributionAndPermissionUtils>()\
179 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700180 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
181 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800182 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800183 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700184 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700185 mSoundRef(0), mInitialized(false),
186 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000187 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700188 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800189 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700190 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
191 if (mMemFd == -1) {
192 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
193 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700194}
195
Charles Chena7b613c2023-01-24 21:57:33 +0000196// Enable processes with isolated AID to request the binder
197void CameraService::instantiate() {
198 CameraService::publish(true);
199}
200
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800201void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700202 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800203 return;
204 }
205
206 ALOGV("appops service registered. setting camera audio restriction");
207 mAppOps.setCameraAudioRestriction(mAudioRestriction);
208}
209
Iliyan Malchev8951a972011-04-14 16:55:59 -0700210void CameraService::onFirstRef()
211{
Ruben Brunkcc776712015-02-17 20:18:47 -0800212 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800213
Iliyan Malchev8951a972011-04-14 16:55:59 -0700214 BnCameraService::onFirstRef();
215
Ruben Brunk99e69712015-05-26 17:25:07 -0700216 // Update battery life tracking if service is restarting
217 BatteryNotifier& notifier(BatteryNotifier::getInstance());
218 notifier.noteResetCamera();
219 notifier.noteResetFlashlight();
220
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800221 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800222
Emilian Peevf53f66e2017-04-11 14:29:43 +0100223 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800224 if (res == OK) {
225 mInitialized = true;
226 }
227
Svet Ganova453d0d2018-01-11 15:37:58 -0800228 mUidPolicy = new UidPolicy(this);
229 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700230 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800231 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800232 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800233
234 // appops function setCamerAudioRestriction uses getService which
235 // is blocking till the appops service is ready. To enable early
236 // boot availability for cameraservice, use checkService which is
237 // non blocking and register for notifications
238 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700239 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800240 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700241 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800242 } else {
243 mAppOps.setCameraAudioRestriction(mAudioRestriction);
244 }
245
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700246 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
247 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000248 // Deprecated, so it will fail to register on newer devices
249 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700250 __FUNCTION__);
251 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700252
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700253 if (!AidlCameraService::registerService(this)) {
254 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
255 }
256
Shuzhen Wang24b44152019-09-20 10:38:11 -0700257 // This needs to be last call in this function, so that it's as close to
258 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700259 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700260 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261}
262
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800264 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100265
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000267 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800268 {
269 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800270
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800271 if (nullptr == mCameraProviderManager.get()) {
272 mCameraProviderManager = new CameraProviderManager();
273 res = mCameraProviderManager->initialize(this);
274 if (res != OK) {
275 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
276 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700277 logServiceError("Unable to initialize camera provider manager",
278 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800279 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100280 }
281 }
282
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800283 // Setup vendor tags before we call get_camera_info the first time
284 // because HAL might need to setup static vendor keys in get_camera_info
285 // TODO: maybe put this into CameraProviderManager::initialize()?
286 mCameraProviderManager->setUpVendorTags();
287
288 if (nullptr == mFlashlight.get()) {
289 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700290 }
291
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800292 res = mFlashlight->findFlashUnits();
293 if (res != OK) {
294 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
295 }
296
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000297 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800298 }
299
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800300 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700301 if (getCameraState(cameraId) == nullptr) {
302 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800303 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000304 if (unavailPhysicalIds.count(cameraId) > 0) {
305 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700306 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000307 }
308 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800309 }
310
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700311 // Derive primary rear/front cameras, and filter their charactierstics.
312 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700313 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700314 // Assume internal cameras are advertised from the same
315 // provider. If multiple providers are registered at different time,
316 // and each provider contains multiple internal color cameras, the current
317 // logic may filter the characteristics of more than one front/rear color
318 // cameras.
319 Mutex::Autolock l(mServiceLock);
320 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700321 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700322
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800323 return OK;
324}
325
Austin Borgered99f642023-06-01 16:51:35 -0700326void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700327 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000328 // Get the device id and app-visible camera id for the given HAL-visible camera id.
329 auto [deviceId, mappedCameraId] =
330 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
331
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800333 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700334 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
335 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000336 ALOGV("%s: Skipping torch callback for system-only camera device %s",
337 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700338 continue;
339 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000340
Austin Borgere8e2c422022-05-12 13:45:24 -0700341 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000342 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700343 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
344 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800345 }
346}
347
Mathias Agopian65ab4712010-07-14 17:59:35 -0700348CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800349 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800350 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800351 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800352 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700353}
354
Emilian Peevaee727d2017-05-04 16:35:48 +0100355void CameraService::onNewProviderRegistered() {
356 enumerateProviders();
357}
358
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700359void CameraService::filterAPI1SystemCameraLocked(
360 const std::vector<std::string> &normalDeviceIds) {
361 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000362 for (auto &cameraId : normalDeviceIds) {
363 if (vd_flags::camera_device_awareness()) {
364 CameraMetadata cameraInfo;
365 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000366 cameraId, false, &cameraInfo,
367 hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +0000368 int32_t deviceId = kDefaultDeviceId;
369 if (res != OK) {
370 ALOGW("%s: Not able to get camera characteristics for camera id %s",
371 __FUNCTION__, cameraId.c_str());
372 } else {
373 deviceId = getDeviceId(cameraInfo);
374 }
375 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
376 // system cameras, so skip for non-default device id's.
377 if (deviceId != kDefaultDeviceId) {
378 continue;
379 }
380 }
381
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700382 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000383 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
384 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700385 continue;
386 }
387 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700388 // All system camera ids will necessarily come after public camera
389 // device ids as per the HAL interface contract.
390 break;
391 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000392 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700393 }
394 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
395 mNormalDeviceIdsWithoutSystemCamera.size());
396}
397
Austin Borgered99f642023-06-01 16:51:35 -0700398status_t CameraService::getSystemCameraKind(const std::string& cameraId,
399 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700400 auto state = getCameraState(cameraId);
401 if (state != nullptr) {
402 *kind = state->getSystemCameraKind();
403 return OK;
404 }
405 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700406 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700407}
408
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800409void CameraService::updateCameraNumAndIds() {
410 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700411 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
412 // Excludes hidden secure cameras
413 mNumberOfCameras =
414 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
415 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800416 mNormalDeviceIds =
417 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700418 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800419}
420
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700421void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700422 // To claim to be S Performance primary cameras, the cameras must be
423 // backward compatible. So performance class primary camera Ids must be API1
424 // compatible.
425 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
426 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
427 int facing = -1;
428 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800429 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000430 getDeviceVersion(cameraId,
431 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
432 /*out*/&portraitRotation, /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700433 if (facing == -1) {
434 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
435 return;
436 }
437
438 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
439 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700440 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
441 if (res == OK) {
442 mPerfClassPrimaryCameraIds.insert(cameraId);
443 } else {
444 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
445 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
446 break;
447 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700448
449 if (facing == hardware::CAMERA_FACING_BACK) {
450 firstRearCameraSeen = true;
451 }
452 if (facing == hardware::CAMERA_FACING_FRONT) {
453 firstFrontCameraSeen = true;
454 }
455 }
456
457 if (firstRearCameraSeen && firstFrontCameraSeen) {
458 break;
459 }
460 }
461}
462
Austin Borgered99f642023-06-01 16:51:35 -0700463void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700464 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100465 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
466 if (res != OK) {
467 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
468 return;
469 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000470 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700471 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
472 if (res != OK) {
473 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
474 return;
475 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000476 std::vector<std::string> physicalCameraIds;
477 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700478 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100479 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700480 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100481 }
482
483 {
484 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700485 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000486 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100487 }
488
Austin Borgered99f642023-06-01 16:51:35 -0700489 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100490 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700491 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800492
Austin Borgered99f642023-06-01 16:51:35 -0700493 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100494 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800495
496 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700497 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100498}
499
Austin Borgered99f642023-06-01 16:51:35 -0700500void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800501 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700502 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100503 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700504 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100505 }
506
507 {
508 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700509 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100510 }
511}
512
Austin Borgered99f642023-06-01 16:51:35 -0700513void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800514 CameraDeviceStatus newHalStatus) {
515 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700516 cameraId.c_str(), eToI(newHalStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700517
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800518 StatusInternal newStatus = mapToInternal(newHalStatus);
519
Austin Borgered99f642023-06-01 16:51:35 -0700520 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800521
522 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700523 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100524 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700525 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100526
527 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700528 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100529
Austin Borgered99f642023-06-01 16:51:35 -0700530 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700531 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700532 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700533 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700534 return;
535 }
536
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800537 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800538
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800539 if (oldStatus == newStatus) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700540 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__,
541 eToI(newStatus));
Igor Murashkincba2c162013-03-20 15:56:31 -0700542 return;
543 }
544
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800545 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000546 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
547 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800548 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
549 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700550 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000551 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800552
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800553 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700554 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800555 // Don't do this in updateStatus to avoid deadlock over mServiceLock
556 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700557
Ruben Brunkcc776712015-02-17 20:18:47 -0800558 // Remove cached shim parameters
559 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700560
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800561 // Remove online as well as offline client from the list of active clients,
562 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700563 clientToDisconnectOnline = removeClientLocked(cameraId);
564 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700565 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800566
Austin Borgered99f642023-06-01 16:51:35 -0700567 disconnectClient(cameraId, clientToDisconnectOnline);
568 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700569
Austin Borgered99f642023-06-01 16:51:35 -0700570 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800571 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800572 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000573 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
574 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700575 }
Austin Borgered99f642023-06-01 16:51:35 -0700576 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700577 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800578}
Igor Murashkincba2c162013-03-20 15:56:31 -0700579
Austin Borgered99f642023-06-01 16:51:35 -0700580void CameraService::onDeviceStatusChanged(const std::string& id,
581 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800582 CameraDeviceStatus newHalStatus) {
583 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700584 __FUNCTION__, id.c_str(), physicalId.c_str(), eToI(newHalStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800585
586 StatusInternal newStatus = mapToInternal(newHalStatus);
587
588 std::shared_ptr<CameraState> state = getCameraState(id);
589
590 if (state == nullptr) {
591 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700592 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800593 return;
594 }
595
596 StatusInternal logicalCameraStatus = state->getStatus();
597 if (logicalCameraStatus != StatusInternal::PRESENT &&
598 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
599 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700600 __FUNCTION__, physicalId.c_str(), eToI(newHalStatus), eToI(logicalCameraStatus));
Shuzhen Wang43858162020-01-10 13:42:15 -0800601 return;
602 }
603
604 bool updated = false;
605 if (newStatus == StatusInternal::PRESENT) {
606 updated = state->removeUnavailablePhysicalId(physicalId);
607 } else {
608 updated = state->addUnavailablePhysicalId(physicalId);
609 }
610
611 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700612 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800613 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000614 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800615 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000616 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800617 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700618 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
619 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
620 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700621 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700622 return;
623 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800624 Mutex::Autolock lock(mStatusListenerLock);
625 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700626 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
627 listener->getListenerPid(), listener->getListenerUid())) {
628 ALOGV("Skipping discovery callback for system-only camera device %s",
629 id.c_str());
630 continue;
631 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700632 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000633 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700634 listener->handleBinderStatus(ret,
635 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
636 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
637 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800638 }
639 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700640}
641
Austin Borgered99f642023-06-01 16:51:35 -0700642void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800643 if (clientToDisconnect.get() != nullptr) {
644 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700645 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800646 // Notify the client of disconnection
647 clientToDisconnect->notifyError(
648 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
649 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800650 clientToDisconnect->disconnect();
651 }
652}
653
Austin Borgered99f642023-06-01 16:51:35 -0700654void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800655 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700656 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
657 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
658 if (res != OK) {
659 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700660 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700661 return;
662 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800663 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700664 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800665}
666
Austin Borgered99f642023-06-01 16:51:35 -0700667void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700668 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
669 Mutex::Autolock al(mTorchStatusMutex);
670 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
671}
672
Austin Borgered99f642023-06-01 16:51:35 -0700673void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800674 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000675 // Get the device id and app-visible camera id for the given HAL-visible camera id.
676 auto [deviceId, mappedCameraId] =
677 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
678
Rucha Katakwar38284522021-11-10 11:25:21 -0800679 Mutex::Autolock lock(mStatusListenerLock);
680 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000681 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
682 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700683 i->handleBinderStatus(ret,
684 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
685 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800686 }
687}
688
Austin Borgered99f642023-06-01 16:51:35 -0700689void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700690 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800691 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Eino-Ville Talvalab7723202024-06-24 17:45:51 -0700692 __FUNCTION__, cameraId.c_str(), eToI(newStatus));
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800693
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800694 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800695 status_t res = getTorchStatusLocked(cameraId, &status);
696 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700697 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700698 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800699 return;
700 }
701 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800702 return;
703 }
704
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800705 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800707 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
708 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800709 return;
710 }
711
Ruben Brunkcc776712015-02-17 20:18:47 -0800712 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700713 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700714 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700715 auto iter = mTorchUidMap.find(cameraId);
716 if (iter != mTorchUidMap.end()) {
717 int oldUid = iter->second.second;
718 int newUid = iter->second.first;
719 BatteryNotifier& notifier(BatteryNotifier::getInstance());
720 if (oldUid != newUid) {
721 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800722 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700723 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700724 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800725 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700726 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700727 }
728 iter->second.second = newUid;
729 } else {
730 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800731 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700732 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700733 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700734 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700735 }
736 }
737 }
738 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700739 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800740}
741
Austin Borger249e6592024-03-10 22:28:11 -0700742bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700743 // Returns false if this is not an automotive device type.
744 if (!isAutomotiveDevice())
745 return false;
746
747 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700748 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700749 return false;
750
751 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
752 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
753 // This isn't a known camera ID, so it's not a system camera.
754 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
755 return false;
756 }
757
758 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
759 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
760 return false;
761 }
762
763 CameraMetadata cameraInfo;
764 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000765 cam_id, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700766 if (res != OK){
767 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
768 cam_id.c_str());
769 return false;
770 }
771
772 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
773 if (auto_location.count != 1)
774 return false;
775
776 uint8_t location = auto_location.data.u8[0];
777 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
778 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
779 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
780 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
781 return false;
782 }
783
784 return true;
785}
786
Austin Borger65e64642024-06-11 15:58:23 -0700787Status CameraService::getNumberOfCameras(int32_t type,
788 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000789 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700790 ATRACE_CALL();
Austin Borger65e64642024-06-11 15:58:23 -0700791 if (vd_flags::camera_device_awareness() && (clientAttribution.deviceId != kDefaultDeviceId)
Biswarup Pal37a75182024-01-16 15:53:35 +0000792 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
Austin Borger65e64642024-06-11 15:58:23 -0700793 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000794 return Status::ok();
795 }
796
Emilian Peevaee727d2017-05-04 16:35:48 +0100797 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700798 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800799 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
800 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700801 switch (type) {
802 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700803 if (hasSystemCameraPermissions) {
804 *numCameras = static_cast<int>(mNormalDeviceIds.size());
805 } else {
806 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
807 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800808 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700809 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700810 if (hasSystemCameraPermissions) {
811 *numCameras = mNumberOfCameras;
812 } else {
813 *numCameras = mNumberOfCamerasWithoutSystemCamera;
814 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800815 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700816 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800817 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700818 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800819 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
820 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700821 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700823}
824
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700825Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Austin Borger65e64642024-06-11 15:58:23 -0700826 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700827 /* out */
828 hardware::camera2::impl::CameraMetadataNative* request) {
829 ATRACE_CALL();
830
831 if (!flags::feature_combination_query()) {
832 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
833 "Camera subsystem doesn't support this method!");
834 }
835 if (!mInitialized) {
836 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
837 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
838 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
839 }
840
Austin Borger65e64642024-06-11 15:58:23 -0700841 std::optional<std::string> cameraIdOptional =
842 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000843 if (!cameraIdOptional.has_value()) {
844 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700845 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000846 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
847 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
848 }
849 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700850
851 binder::Status res;
852 if (request == nullptr) {
853 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
854 "Camera %s: Error creating default request", cameraId.c_str());
855 return res;
856 }
857 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
858 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
859 cameraId, templateId, &tempId);
860 if (!res.isOk()) {
861 ALOGE("%s: Camera %s: failed to map request Template %d",
862 __FUNCTION__, cameraId.c_str(), templateId);
863 return res;
864 }
865
866 if (shouldRejectSystemCameraConnection(cameraId)) {
867 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
868 "request for system only device %s: ", cameraId.c_str());
869 }
870
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700871 CameraMetadata metadata;
872 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
873 if (err == OK) {
874 request->swap(metadata);
875 } else if (err == BAD_VALUE) {
876 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
877 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
878 cameraId.c_str(), templateId, strerror(-err), err);
879 } else {
880 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
881 "Camera %s: Error creating default request for template %d: %s (%d)",
882 cameraId.c_str(), templateId, strerror(-err), err);
883 }
884 return res;
885}
886
887Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700888 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700889 const SessionConfiguration& sessionConfiguration,
Austin Borger65e64642024-06-11 15:58:23 -0700890 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700891 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700892 ATRACE_CALL();
893
894 if (!flags::feature_combination_query()) {
895 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
896 "Camera subsystem doesn't support this method!");
897 }
898 if (!mInitialized) {
899 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
900 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
901 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
902 }
903
Austin Borger65e64642024-06-11 15:58:23 -0700904 std::optional<std::string> cameraIdOptional =
905 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +0000906 if (!cameraIdOptional.has_value()) {
907 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -0700908 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000909 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
910 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
911 }
912 std::string cameraId = cameraIdOptional.value();
913
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700914 if (supported == nullptr) {
915 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
916 unresolvedCameraId.c_str());
917 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
918 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
919 }
920
921 if (shouldRejectSystemCameraConnection(cameraId)) {
922 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
923 "session configuration with parameters support for system only device %s: ",
924 cameraId.c_str());
925 }
926
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700927 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
928 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
929 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
930
Shuzhen Wange3e8e732024-05-22 17:48:01 -0700931 auto ret = isSessionConfigurationWithParametersSupportedUnsafe(cameraId,
932 sessionConfiguration, overrideForPerfClass, supported);
933 if (flags::analytics_24q3()) {
934 mCameraServiceProxyWrapper->logFeatureCombinationQuery(cameraId,
935 getCallingUid(), sessionConfiguration, ret);
936 }
937 return ret;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700938}
939
940Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
941 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
942 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700943 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700944 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
945 cameraId, sessionConfiguration, overrideForPerfClass,
946 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700947 binder::Status res;
948 switch (ret) {
949 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700950 // Expected. Do Nothing.
951 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700952 case INVALID_OPERATION: {
953 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700954 "Camera %s: Session configuration with parameters supported query not "
955 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700956 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700957 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
958 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
959 *supported = false;
960 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700961 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700962 break;
963 case NAME_NOT_FOUND: {
964 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
965 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
966 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
967 *supported = false;
968 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
969 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 break;
971 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700972 std::string msg = fmt::sprintf(
973 "Unable to retrieve session configuration support for camera "
974 "device %s: Error: %s (%d)",
975 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700976 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700977 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
978 *supported = false;
979 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700980 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700981 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700982 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700983}
984
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800985Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +0000986 int targetSdkVersion, int rotationOverride,
Austin Borger65e64642024-06-11 15:58:23 -0700987 const SessionConfiguration& sessionConfiguration,
988 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal37a75182024-01-16 15:53:35 +0000989 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800990 ATRACE_CALL();
991
Avichal Rakesh3c522e22024-02-07 16:40:46 -0800992 if (outMetadata == nullptr) {
993 std::string msg =
994 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
995 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
996 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
997 }
998
Avichal Rakesh4baf7262024-03-20 19:16:04 -0700999 if (!mInitialized) {
1000 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1001 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1002 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1003 }
1004
Austin Borger65e64642024-06-11 15:58:23 -07001005 std::optional<std::string> cameraIdOptional =
1006 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001007 if (!cameraIdOptional.has_value()) {
1008 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001009 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001010 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1011 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1012 }
1013 std::string cameraId = cameraIdOptional.value();
1014
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001015 if (shouldRejectSystemCameraConnection(cameraId)) {
1016 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1017 "Unable to retrieve camera"
1018 "characteristics for system only device %s: ",
1019 cameraId.c_str());
1020 }
1021
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001022 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1023 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001024 if (flags::check_session_support_before_session_char()) {
1025 bool sessionConfigSupported;
1026 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1027 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1028 if (!res.isOk()) {
1029 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1030 // report the correct Status to send to the client. Simply forward the error to
1031 // the client.
1032 outMetadata->clear();
1033 return res;
1034 }
1035 if (!sessionConfigSupported) {
1036 std::string msg = fmt::sprintf(
1037 "Session configuration not supported for camera device %s.", cameraId.c_str());
1038 outMetadata->clear();
1039 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1040 }
1041 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001042
1043 status_t ret = mCameraProviderManager->getSessionCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001044 cameraId, sessionConfiguration, overrideForPerfClass, rotationOverride, outMetadata);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001045
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001046 switch (ret) {
1047 case OK:
1048 // Expected, no handling needed.
1049 break;
1050 case INVALID_OPERATION: {
1051 std::string msg = fmt::sprintf(
1052 "Camera %s: Session characteristics query not supported!",
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_INVALID_OPERATION);
1056 outMetadata->clear();
1057 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1058 }
1059 break;
1060 case NAME_NOT_FOUND: {
1061 std::string msg = fmt::sprintf(
1062 "Camera %s: Unknown camera ID.",
1063 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001064 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001065 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1066 outMetadata->clear();
1067 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001068 }
1069 break;
1070 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001071 std::string msg = fmt::sprintf(
1072 "Unable to retrieve session characteristics for camera device %s: "
1073 "Error: %s (%d)",
1074 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001075 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001076 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1077 outMetadata->clear();
1078 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001079 }
1080 }
1081
Shuzhen Wange3e8e732024-05-22 17:48:01 -07001082 Status res = filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1083 if (flags::analytics_24q3()) {
1084 mCameraServiceProxyWrapper->logSessionCharacteristicsQuery(cameraId,
1085 getCallingUid(), sessionConfiguration, res);
1086 }
1087 return res;
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001088}
1089
1090Status CameraService::filterSensitiveMetadataIfNeeded(
1091 const std::string& cameraId, CameraMetadata* metadata) {
1092 int callingPid = getCallingPid();
1093 int callingUid = getCallingUid();
1094
1095 if (callingPid == getpid()) {
1096 // Caller is cameraserver; no need to remove keys
1097 return Status::ok();
1098 }
1099
1100 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1101 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1102 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1103 metadata->clear();
1104 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1105 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1106 }
1107 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1108 // Attempting to query system only camera without system camera permission would have
1109 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1110 // for a system only camera, then the caller has the required permission.
1111 // No need to remove keys
1112 return Status::ok();
1113 }
1114
1115 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001116 // Get the device id that owns this camera.
1117 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1118 cameraId);
1119 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1120 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001121 if (hasCameraPermission) {
1122 // Caller has camera permission; no need to remove keys
1123 return Status::ok();
1124 }
1125
1126 status_t ret = metadata->removePermissionEntries(
1127 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1128 if (ret != OK) {
1129 metadata->clear();
1130 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1131 "Failed to remove camera characteristics needing camera permission "
1132 "for device %s:%s (%d)",
1133 cameraId.c_str(), strerror(-ret), ret);
1134 }
1135
1136 if (!tagsRemoved.empty()) {
1137 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1138 tagsRemoved.data(), tagsRemoved.size());
1139 if (ret != OK) {
1140 metadata->clear();
1141 return STATUS_ERROR_FMT(
1142 ERROR_INVALID_OPERATION,
1143 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1144 cameraId.c_str(), strerror(-ret), ret);
1145 }
1146 }
1147 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001148}
1149
malikakash22af94c2023-12-04 18:13:14 +00001150Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001151 const std::string& cameraId,
1152 const CameraMetadata& sessionParams) {
1153 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001154 const int pid = getCallingPid();
1155 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001156 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1157 __FUNCTION__, pid, uid);
1158 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1159 "Permission Denial: no permission to inject session params");
1160 }
1161
Biswarup Pal37a75182024-01-16 15:53:35 +00001162 // Do not allow session params injection for a virtual camera.
1163 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1164 if (deviceId != kDefaultDeviceId) {
1165 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1166 "Cannot inject session params for a virtual camera");
1167 }
1168
malikakash22af94c2023-12-04 18:13:14 +00001169 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1170 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1171
1172 auto clientDescriptor = mActiveClientManager.get(cameraId);
1173 if (clientDescriptor == nullptr) {
1174 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1175 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1176 "No active client for camera id %s", cameraId.c_str());
1177 }
1178
1179 sp<BasicClient> clientSp = clientDescriptor->getValue();
1180 status_t res = clientSp->injectSessionParams(sessionParams);
1181
1182 if (res != OK) {
1183 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1184 "Error injecting session params into camera \"%s\": %s (%d)",
1185 cameraId.c_str(), strerror(-res), res);
1186 }
1187 return Status::ok();
1188}
1189
Biswarup Pal37a75182024-01-16 15:53:35 +00001190std::optional<std::string> CameraService::resolveCameraId(
1191 const std::string& inputCameraId,
1192 int32_t deviceId,
malikakash98260df2024-05-10 23:33:57 +00001193 int32_t devicePolicy) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001194 if ((deviceId == kDefaultDeviceId)
1195 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1196 auto [storedDeviceId, _] =
1197 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1198 if (storedDeviceId != kDefaultDeviceId) {
1199 // Trying to access a virtual camera from default-policy device context, we should fail.
1200 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1201 inputCameraId.c_str(), deviceId);
1202 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1203 return std::nullopt;
1204 }
malikakash98260df2024-05-10 23:33:57 +00001205 return inputCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001206 }
1207
1208 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1209}
1210
Austin Borger65e64642024-06-11 15:58:23 -07001211Status CameraService::getCameraInfo(int cameraId, int rotationOverride,
1212 const AttributionSourceState& clientAttribution, int32_t devicePolicy,
1213 CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001214 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001215 Mutex::Autolock l(mServiceLock);
Austin Borger65e64642024-06-11 15:58:23 -07001216 std::string cameraIdStr =
1217 cameraIdIntToStrLocked(cameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001218 if (cameraIdStr.empty()) {
1219 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001220 cameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001221 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1222 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1223 }
malikakashedb38962023-09-06 00:03:35 +00001224
Austin Borgered99f642023-06-01 16:51:35 -07001225 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001226 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1227 "characteristics for system only device %s: ", cameraIdStr.c_str());
1228 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001229
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001230 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001231 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001232 return STATUS_ERROR(ERROR_DISCONNECTED,
1233 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001234 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001235 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001236 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001237 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1238 if (hasSystemCameraPermissions) {
1239 cameraIdBound = mNumberOfCameras;
1240 }
1241 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001242 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1243 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001244 }
1245
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001246 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001247 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001248 status_t err = mCameraProviderManager->getCameraInfo(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001249 cameraIdStr, rotationOverride, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001250 if (err != OK) {
1251 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1252 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1253 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001254 logServiceError(std::string("Error retrieving camera info from device ")
1255 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001256 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001257
Ruben Brunkcc776712015-02-17 20:18:47 -08001258 return ret;
1259}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001260
Biswarup Pal37a75182024-01-16 15:53:35 +00001261std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1262 int32_t deviceId, int32_t devicePolicy) {
1263 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1264 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1265 std::optional<std::string> cameraIdOptional =
1266 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1267 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1268 }
1269
1270 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001271 auto callingPid = getCallingPid();
1272 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001273 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1274 callingPid, callingUid, /* checkCameraPermissions= */ false);
1275 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001276 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001277 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001278 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1279 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1280 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001281 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001282 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001283
malikakash98260df2024-05-10 23:33:57 +00001284 return (*cameraIds)[cameraIdInt];
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001285}
1286
Biswarup Pal37a75182024-01-16 15:53:35 +00001287std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1288 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001289 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001290 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001291}
1292
Austin Borgered99f642023-06-01 16:51:35 -07001293Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07001294 int targetSdkVersion, int rotationOverride, const AttributionSourceState& clientAttribution,
1295 int32_t devicePolicy, CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001296 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001297
Zhijun He2b59be82013-09-25 10:14:30 -07001298 if (!cameraInfo) {
1299 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001301 }
1302
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001303 if (!mInitialized) {
1304 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001305 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001306 return STATUS_ERROR(ERROR_DISCONNECTED,
1307 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001308 }
1309
Austin Borger65e64642024-06-11 15:58:23 -07001310 std::optional<std::string> cameraIdOptional =
1311 resolveCameraId(unresolvedCameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001312 if (!cameraIdOptional.has_value()) {
1313 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001314 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001315 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1316 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1317 }
1318 std::string cameraId = cameraIdOptional.value();
1319
Austin Borgered99f642023-06-01 16:51:35 -07001320 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001321 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001322 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001323 }
1324
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001325 bool overrideForPerfClass =
1326 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001327 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001328 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001329 cameraId, overrideForPerfClass, cameraInfo, rotationOverride);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001330 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001331 if (res == NAME_NOT_FOUND) {
1332 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001333 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001334 strerror(-res), res);
1335 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001336 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1337 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001338 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001339 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001340 strerror(-res), res);
1341 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001342 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001343
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001344 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001345}
1346
Austin Borger65e64642024-06-11 15:58:23 -07001347Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId,
1348 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00001349 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001350 ATRACE_CALL();
1351 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001352
Austin Borger65e64642024-06-11 15:58:23 -07001353 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
1354 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00001355 if (!cameraIdOptional.has_value()) {
1356 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07001357 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001358 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1359 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1360 }
1361 std::string cameraId = cameraIdOptional.value();
1362
Rucha Katakwar38284522021-11-10 11:25:21 -08001363 if (!mInitialized) {
1364 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1365 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1366 }
1367
Biswarup Pal37a75182024-01-16 15:53:35 +00001368 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001369 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1370 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1371 }
1372
Austin Borgered99f642023-06-01 16:51:35 -07001373 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001374 if (res != OK) {
1375 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001376 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001377 strerror(-res), res);
1378 }
1379 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1380 return Status::ok();
1381}
1382
Austin Borgered99f642023-06-01 16:51:35 -07001383std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001384 time_t now = time(nullptr);
1385 char formattedTime[64];
1386 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001387 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001388}
1389
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001390Status CameraService::getCameraVendorTagDescriptor(
1391 /*out*/
1392 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001393 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001394 if (!mInitialized) {
1395 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001396 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001397 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001398 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1399 if (globalDescriptor != nullptr) {
1400 *desc = *(globalDescriptor.get());
1401 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001402 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001403}
1404
Emilian Peev71c73a22017-03-21 16:35:51 +00001405Status CameraService::getCameraVendorTagCache(
1406 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1407 ATRACE_CALL();
1408 if (!mInitialized) {
1409 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1410 return STATUS_ERROR(ERROR_DISCONNECTED,
1411 "Camera subsystem not available");
1412 }
1413 sp<VendorTagDescriptorCache> globalCache =
1414 VendorTagDescriptorCache::getGlobalVendorTagCache();
1415 if (globalCache != nullptr) {
1416 *cache = *(globalCache.get());
1417 }
1418 return Status::ok();
1419}
1420
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001421void CameraService::clearCachedVariables() {
1422 BasicClient::BasicClient::sCameraService = nullptr;
1423}
1424
Austin Borgered99f642023-06-01 16:51:35 -07001425std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001426 int rotationOverride, int* portraitRotation, int* facing,
1427 int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001428 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001429
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001430 int deviceVersion = 0;
1431
Emilian Peevf53f66e2017-04-11 14:29:43 +01001432 status_t res;
1433 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001434 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001435 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001436 if (res != OK || transport == IPCTransport::INVALID) {
1437 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001438 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001439 return std::make_pair(-1, IPCTransport::INVALID) ;
1440 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001441 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001442
Emilian Peevf53f66e2017-04-11 14:29:43 +01001443 hardware::CameraInfo info;
1444 if (facing) {
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001445 res = mCameraProviderManager->getCameraInfo(cameraId, rotationOverride,
Austin Borger18b30a72022-10-27 12:20:29 -07001446 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001447 if (res != OK) {
1448 return std::make_pair(-1, IPCTransport::INVALID);
1449 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001450 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001451 if (orientation) {
1452 *orientation = info.orientation;
1453 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001454 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001455
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001456 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001457}
1458
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001459Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001460 switch(err) {
1461 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001462 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001463 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001464 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1465 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001466 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001467 return STATUS_ERROR(ERROR_DISCONNECTED,
1468 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001469 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001470 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1471 "Camera HAL encountered error %d: %s",
1472 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001473 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001474}
1475
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001476Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001477 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1478 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001479 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001480 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001481 apiLevel effectiveApiLevel, bool overrideForPerfClass, int rotationOverride,
malikakash73125c62023-07-21 22:44:34 +00001482 bool forceSlowJpegMode, const std::string& originalCameraId,
1483 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001484 // For HIDL devices
1485 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1486 // Create CameraClient based on device version reported by the HAL.
1487 int deviceVersion = deviceVersionAndTransport.first;
1488 switch(deviceVersion) {
1489 case CAMERA_DEVICE_API_VERSION_1_0:
1490 ALOGE("Camera using old HAL version: %d", deviceVersion);
1491 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1492 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001493 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001494 break;
1495 case CAMERA_DEVICE_API_VERSION_3_0:
1496 case CAMERA_DEVICE_API_VERSION_3_1:
1497 case CAMERA_DEVICE_API_VERSION_3_2:
1498 case CAMERA_DEVICE_API_VERSION_3_3:
1499 case CAMERA_DEVICE_API_VERSION_3_4:
1500 case CAMERA_DEVICE_API_VERSION_3_5:
1501 case CAMERA_DEVICE_API_VERSION_3_6:
1502 case CAMERA_DEVICE_API_VERSION_3_7:
1503 break;
1504 default:
1505 // Should not be reachable
1506 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1507 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1508 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001509 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001510 }
1511 }
1512 if (effectiveApiLevel == API_1) { // Camera1 API route
1513 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001514 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001515 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001516 api1CameraId, facing, sensorOrientation,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001517 clientPid, clientUid, servicePid, overrideForPerfClass, rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00001518 forceSlowJpegMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001519 ALOGI("%s: Camera1 API (legacy), rotationOverride %d, forceSlowJpegMode %d",
1520 __FUNCTION__, rotationOverride, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001521 } else { // Camera2 API route
1522 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1523 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001524 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001525 cameraService->mCameraServiceProxyWrapper,
1526 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001527 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001528 overrideForPerfClass, rotationOverride, originalCameraId);
1529 ALOGI("%s: Camera2 API, rotationOverride %d", __FUNCTION__, rotationOverride);
Ruben Brunkcc776712015-02-17 20:18:47 -08001530 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001531 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001532}
1533
Austin Borgered99f642023-06-01 16:51:35 -07001534std::string CameraService::toString(std::set<userid_t> intSet) {
1535 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001536 bool first = true;
1537 for (userid_t i : intSet) {
1538 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001539 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001540 first = false;
1541 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001542 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001543 }
1544 }
Austin Borgered99f642023-06-01 16:51:35 -07001545 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001546}
1547
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001548int32_t CameraService::mapToInterface(TorchModeStatus status) {
1549 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1550 switch (status) {
1551 case TorchModeStatus::NOT_AVAILABLE:
1552 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1553 break;
1554 case TorchModeStatus::AVAILABLE_OFF:
1555 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1556 break;
1557 case TorchModeStatus::AVAILABLE_ON:
1558 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1559 break;
1560 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001561 ALOGW("Unknown new flash status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001562 }
1563 return serviceStatus;
1564}
1565
1566CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1567 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1568 switch (status) {
1569 case CameraDeviceStatus::NOT_PRESENT:
1570 serviceStatus = StatusInternal::NOT_PRESENT;
1571 break;
1572 case CameraDeviceStatus::PRESENT:
1573 serviceStatus = StatusInternal::PRESENT;
1574 break;
1575 case CameraDeviceStatus::ENUMERATING:
1576 serviceStatus = StatusInternal::ENUMERATING;
1577 break;
1578 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001579 ALOGW("Unknown new HAL device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001580 }
1581 return serviceStatus;
1582}
1583
1584int32_t CameraService::mapToInterface(StatusInternal status) {
1585 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1586 switch (status) {
1587 case StatusInternal::NOT_PRESENT:
1588 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1589 break;
1590 case StatusInternal::PRESENT:
1591 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1592 break;
1593 case StatusInternal::ENUMERATING:
1594 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1595 break;
1596 case StatusInternal::NOT_AVAILABLE:
1597 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1598 break;
1599 case StatusInternal::UNKNOWN:
1600 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1601 break;
1602 default:
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001603 ALOGW("Unknown new internal device status: %d", eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001604 }
1605 return serviceStatus;
1606}
1607
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001608Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001609 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001610
Austin Borgered99f642023-06-01 16:51:35 -07001611 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001612 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001613 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001614 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001615 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1616 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001617 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001618 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1619 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borgered99f642023-06-01 16:51:35 -07001620 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001621 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001622 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001623 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001624 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001625}
1626
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001627Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001628 /*out*/
1629 CameraParameters* parameters) {
1630
1631 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1632
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001633 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001634
1635 if (parameters == NULL) {
1636 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001637 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001638 }
1639
malikakash98260df2024-05-10 23:33:57 +00001640 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001641
1642 // Check if we already have parameters
1643 {
1644 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001645 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001646 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001647 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001648 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001649 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001650 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001651 }
1652 CameraParameters p = cameraState->getShimParams();
1653 if (!p.isEmpty()) {
1654 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001655 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001656 }
1657 }
1658
Austin Borger22c5c852024-03-08 13:31:36 -08001659 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001660 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001661 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001662 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001663 // Error already logged by callee
1664 return ret;
1665 }
1666
1667 // Check for parameters again
1668 {
1669 // Scope for service lock
1670 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001671 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001672 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001673 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001674 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001675 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001676 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001677 CameraParameters p = cameraState->getShimParams();
1678 if (!p.isEmpty()) {
1679 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001680 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001681 }
1682 }
1683
Ruben Brunkcc776712015-02-17 20:18:47 -08001684 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1685 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001686 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001687}
1688
Austin Borgered99f642023-06-01 16:51:35 -07001689Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borger6e831c42024-07-22 13:07:56 -07001690 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001691
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001692#ifdef __BRILLO__
1693 UNUSED(clientName8);
1694 UNUSED(clientUid);
1695 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001696#else
Austin Borger6e831c42024-07-22 13:07:56 -07001697 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001698 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001699 return allowed;
1700 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001701#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001702
Austin Borger22c5c852024-03-08 13:31:36 -08001703 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001704
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001705 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001706 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1707 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001708 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001709 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001710 }
1711
Ruben Brunkcc776712015-02-17 20:18:47 -08001712 if (getCameraState(cameraId) == nullptr) {
1713 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001714 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001715 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001716 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001717 }
1718
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001719 status_t err = checkIfDeviceIsUsable(cameraId);
1720 if (err != NO_ERROR) {
1721 switch(err) {
1722 case -ENODEV:
1723 case -EBUSY:
1724 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001725 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001726 default:
1727 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001728 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001729 }
1730 }
1731 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001732}
1733
Austin Borgered99f642023-06-01 16:51:35 -07001734Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
Austin Borger6e831c42024-07-22 13:07:56 -07001735 const std::string& clientName, int& clientUid, int& clientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001736 int callingPid = getCallingPid();
1737 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001738
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001739 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001740 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001741 clientUid = callingUid;
1742 } else if (!isTrustedCallingUid(callingUid)) {
1743 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1744 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001745 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1746 "Untrusted caller (calling PID %d, UID %d) trying to "
1747 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001748 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001749 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001750 }
1751
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001752 // Check if we can trust clientPid
1753 if (clientPid == USE_CALLING_PID) {
1754 clientPid = callingPid;
1755 } else if (!isTrustedCallingUid(callingUid)) {
1756 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1757 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001758 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1759 "Untrusted caller (calling PID %d, UID %d) trying to "
1760 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001761 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001762 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001763 }
1764
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001765 if (shouldRejectSystemCameraConnection(cameraId)) {
1766 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1767 cameraId.c_str());
1768 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001769 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001770 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001771 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1772 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001773 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001774 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001775 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001776 }
1777
Biswarup Pale506e732024-03-27 13:46:20 +00001778 // Get the device id that owns this camera.
1779 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1780
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001781 // If it's not calling from cameraserver, check the permission if the
1782 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1783 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001784 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001785 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001786 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001787 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001788 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001789 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1790 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001791 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001792 }
1793
Svet Ganova453d0d2018-01-11 15:37:58 -08001794 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001795 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001796 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001797 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1798 clientPid, clientUid);
1799 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001800 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1801 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001802 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001803 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001804 }
1805
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001806 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1807 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1808 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1809 if ((!isAutomotivePrivilegedClient(callingUid) ||
1810 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1811 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001812 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1813 return STATUS_ERROR_FMT(ERROR_DISABLED,
1814 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001815 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001816 }
1817
Austin Borger6e831c42024-07-22 13:07:56 -07001818 userid_t clientUserId = multiuser_get_user_id(clientUid);
1819
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001820 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1821 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001822
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001823 // For non-system clients : Only allow clients who are being used by the current foreground
1824 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001825 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001826 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001827 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1828 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001829 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001830 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1831 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001832 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001833 }
1834
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001835 if (flags::camera_hsum_permission()) {
1836 // If the System User tries to access the camera when the device is running in
1837 // headless system user mode, ensure that client has the required permission
1838 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001839 if (isHeadlessSystemUserMode()
1840 && (clientUserId == USER_SYSTEM)
1841 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001842 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001843 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1844 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1845 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001846 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001847 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001848 }
1849
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001850 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001851}
1852
Austin Borgered99f642023-06-01 16:51:35 -07001853status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001854 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001855 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 if (cameraState == nullptr) {
1857 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001858 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001859 return -ENODEV;
1860 }
1861
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001862 StatusInternal currentStatus = cameraState->getStatus();
1863 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001864 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001865 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001866 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001867 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001868 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001869 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001870 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001871 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001872
Ruben Brunkcc776712015-02-17 20:18:47 -08001873 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001874}
1875
Ruben Brunkcc776712015-02-17 20:18:47 -08001876void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001877 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001878
Ruben Brunkcc776712015-02-17 20:18:47 -08001879 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001880 auto clientDescriptor =
1881 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001882 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001883 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1884
1885 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001886 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001887
1888 if (evicted.size() > 0) {
1889 // This should never happen - clients should already have been removed in disconnect
1890 for (auto& i : evicted) {
1891 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001892 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 }
1894
1895 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1896 __FUNCTION__);
1897 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001898
1899 // And register a death notification for the client callback. Do
1900 // this last to avoid Binder policy where a nested Binder
1901 // transaction might be pre-empted to service the client death
1902 // notification if the client process dies before linkToDeath is
1903 // invoked.
1904 sp<IBinder> remoteCallback = client->getRemote();
1905 if (remoteCallback != nullptr) {
1906 remoteCallback->linkToDeath(this);
1907 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001908}
1909
Austin Borgered99f642023-06-01 16:51:35 -07001910status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1911 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1912 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001913 /*out*/
1914 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001915 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001916 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001917 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001918 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001919 DescriptorPtr clientDescriptor;
1920 {
1921 if (effectiveApiLevel == API_1) {
1922 // If we are using API1, any existing client for this camera ID with the same remote
1923 // should be returned rather than evicted to allow MediaRecorder to work properly.
1924
1925 auto current = mActiveClientManager.get(cameraId);
1926 if (current != nullptr) {
1927 auto clientSp = current->getValue();
1928 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001929 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001930 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001931 " API level, evicting prior client...");
1932 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001933 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001934 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001935 *client = clientSp;
1936 return NO_ERROR;
1937 }
1938 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001939 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001940 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001941
Ruben Brunkcc776712015-02-17 20:18:47 -08001942 // Get state for the given cameraId
1943 auto state = getCameraState(cameraId);
1944 if (state == nullptr) {
1945 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001946 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001947 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001948 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001949 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001950
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001951 sp<IServiceManager> sm = defaultServiceManager();
1952 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001953 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001954 // If processinfo service is not available and the client is automotive privileged
1955 // client used for safety critical uses cases such as rear-view and surround-view which
1956 // needs to be available before android boot completes, then use the hardcoded values
1957 // for the process state and priority score. As this scenario is before android system
1958 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1959 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1960 // visible on the top.
1961 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1962 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1963 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1964 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1965 } else {
1966 // Get current active client PIDs
1967 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1968 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001969
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001970 std::vector<int> priorityScores(ownerPids.size());
1971 std::vector<int> states(ownerPids.size());
1972
1973 // Get priority scores of all active PIDs
1974 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1975 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1976 if (err != OK) {
1977 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1978 return err;
1979 }
1980
1981 // Update all active clients' priorities
1982 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1983 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1984 pidToPriorityMap.emplace(ownerPids[i],
1985 resource_policy::ClientPriority(priorityScores[i], states[i],
1986 /* isVendorClient won't get copied over*/ false,
1987 /* oomScoreOffset won't get copied over*/ 0));
1988 }
1989 mActiveClientManager.updatePriorities(pidToPriorityMap);
1990
1991 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1992 int32_t actualState = states[states.size() - 1];
1993
1994 // Make descriptor for incoming client. We store the oomScoreOffset
1995 // since we might need it later on new handleEvictionsLocked and
1996 // ProcessInfoService would not take that into account.
1997 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1998 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1999 state->getConflicting(), actualScore, clientPid, actualState,
2000 oomScoreOffset, systemNativeClient);
2001 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002002
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002003 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2004
Ruben Brunkcc776712015-02-17 20:18:47 -08002005 // Find clients that would be evicted
2006 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2007
2008 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2009 // background, so we cannot do evictions
2010 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2011 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2012 " priority).", clientPid);
2013
2014 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002015 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002016 auto incompatibleClients =
2017 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2018
Austin Borgered99f642023-06-01 16:51:35 -07002019 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2020 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2021 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002022 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002023
2024 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002025 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002026 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002027 i->getKey().c_str(),
2028 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002029 i->getOwnerId(), i->getPriority().getScore(),
2030 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002031 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002032 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2033 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002034 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002035 }
2036
2037 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002038 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 mEventLog.add(msg);
2040
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002041 auto current = mActiveClientManager.get(cameraId);
2042 if (current != nullptr) {
2043 return -EBUSY; // CAMERA_IN_USE
2044 } else {
2045 return -EUSERS; // MAX_CAMERAS_IN_USE
2046 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002047 }
2048
2049 for (auto& i : evicted) {
2050 sp<BasicClient> clientSp = i->getValue();
2051 if (clientSp.get() == nullptr) {
2052 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2053
2054 // TODO: Remove this
2055 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2056 __FUNCTION__);
2057 mActiveClientManager.remove(i);
2058 continue;
2059 }
2060
2061 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002062 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002063 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002064
Ruben Brunkcc776712015-02-17 20:18:47 -08002065 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002066 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002067 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2068 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002069 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002070 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002071 i->getPriority().getState(), cameraId.c_str(),
2072 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002073 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002074
2075 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002076 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002077 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002078 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002079 }
2080
Ruben Brunkcc776712015-02-17 20:18:47 -08002081 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2082 // other clients from connecting in mServiceLockWrapper if held
2083 mServiceLock.unlock();
2084
2085 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002086 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002087
2088 // Destroy evicted clients
2089 for (auto& i : evictedClients) {
2090 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002091 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002092 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002093
Austin Borger22c5c852024-03-08 13:31:36 -08002094 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002095
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002096 for (const auto& i : evictedClients) {
2097 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002098 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002099 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2100 if (ret == TIMED_OUT) {
2101 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002102 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2103 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002104 return -EBUSY;
2105 }
2106 if (ret != NO_ERROR) {
2107 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002108 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2109 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002110 return ret;
2111 }
2112 }
2113
2114 evictedClients.clear();
2115
Ruben Brunkcc776712015-02-17 20:18:47 -08002116 // Once clients have been disconnected, relock
2117 mServiceLock.lock();
2118
2119 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2120 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2121 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002122 }
2123
Ruben Brunkcc776712015-02-17 20:18:47 -08002124 *partial = clientDescriptor;
2125 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002126}
2127
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002128Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002129 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002130 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002131 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002132 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002133 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002134 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002135 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002136 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002137 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002138 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002139 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002140
Austin Borger65e64642024-06-11 15:58:23 -07002141 std::string cameraIdStr =
2142 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002143 if (cameraIdStr.empty()) {
2144 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002145 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002146 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2147 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2148 }
malikakashedb38962023-09-06 00:03:35 +00002149
Ruben Brunkcc776712015-02-17 20:18:47 -08002150 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002151 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002152 clientAttribution.packageName.value_or(""), /*systemNativeClient*/ false, {},
2153 clientAttribution.uid, clientAttribution.pid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002154 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002155 rotationOverride, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002156
Biswarup Pal37a75182024-01-16 15:53:35 +00002157 if (!ret.isOk()) {
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002158 logRejected(cameraIdStr, getCallingPid(), clientAttribution.packageName.value_or(""),
2159 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002160 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002161 }
2162
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002163 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002164
2165 const sp<IServiceManager> sm(defaultServiceManager());
2166 const auto& mActivityManager = getActivityManager();
2167 if (mActivityManager) {
2168 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002169 getCallingUid(),
2170 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002171 }
2172
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002173 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002174}
2175
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002176bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2177 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002178 // If the client is not a vendor client, don't add listener if
2179 // a) the camera is a publicly hidden secure camera OR
2180 // b) the camera is a system only camera and the client doesn't
2181 // have android.permission.SYSTEM_CAMERA permissions.
2182 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2183 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002184 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002185 return true;
2186 }
2187 return false;
2188}
2189
Austin Borgered99f642023-06-01 16:51:35 -07002190bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002191 // Rules for rejection:
2192 // 1) If cameraserver tries to access this camera device, accept the
2193 // connection.
2194 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002195 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002196 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2197 // and the serving thread is a non hwbinder thread, the client must have
2198 // android.permission.SYSTEM_CAMERA permissions to connect.
2199
Austin Borger22c5c852024-03-08 13:31:36 -08002200 int cPid = getCallingPid();
2201 int cUid = getCallingUid();
2202 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002203 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2204 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002205 // This isn't a known camera ID, so it's not a system camera
2206 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2207 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002208 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002209
2210 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002211 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002212 return false;
2213 }
2214 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002215 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002216 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2217 return true;
2218 }
2219 // (3) Here we only check for permissions if it is a system only camera device. This is since
2220 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2221 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2222 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002223 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002224 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002225 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2226 cameraId.c_str());
2227 return true;
2228 }
2229
2230 return false;
2231}
2232
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002233Status CameraService::connectDevice(
2234 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002235 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002236 int oomScoreOffset, int targetSdkVersion,
2237 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002238 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002239 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002240 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002241 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002242 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002243 sp<CameraDeviceClient> client = nullptr;
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002244 std::string clientPackageNameAdj = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002245 int callingPid = getCallingPid();
2246 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002247 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002248 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002249 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002250 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002251 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002252 }
Austin Borger249e6592024-03-10 22:28:11 -07002253
Austin Borger65e64642024-06-11 15:58:23 -07002254 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2255 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002256 if (!cameraIdOptional.has_value()) {
2257 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002258 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002259 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2260 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2261 }
2262 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002263
2264 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002265 std::string msg =
2266 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2267 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2268 cameraId.c_str());
2269 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2270 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002271 }
2272
Austin Borger65e64642024-06-11 15:58:23 -07002273 userid_t clientUserId = multiuser_get_user_id(clientAttribution.uid);
2274 if (clientAttribution.uid == USE_CALLING_UID) {
Austin Borger9bfa0a72022-08-03 17:50:40 -07002275 clientUserId = multiuser_get_user_id(callingUid);
2276 }
2277
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002278 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2279 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002280 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2281 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002282 std::string msg = "Camera disabled by device policy";
2283 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2284 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002285 }
2286
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002287 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002288 if (oomScoreOffset > 0
2289 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002290 callingUid)
2291 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002292 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002293 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002294 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2295 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2296 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002297 }
2298
Austin Borgered99f642023-06-01 16:51:35 -07002299 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002300 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient,
2301 clientAttribution.attributionTag, clientAttribution.uid, USE_CALLING_PID, API_2,
2302 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
2303 /*forceSlowJpegMode*/false, unresolvedCameraId, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002304
Biswarup Pal37a75182024-01-16 15:53:35 +00002305 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002306 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002307 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002308 }
2309
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002310 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002311 Mutex::Autolock lock(mServiceLock);
2312
2313 // Clear the previous cached logs and reposition the
2314 // file offset to beginning of the file to log new data.
2315 // If either truncate or lseek fails, close the previous file and create a new one.
2316 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2317 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2318 // Close the previous memfd.
2319 close(mMemFd);
2320 // If failure to wipe the data, then create a new file and
2321 // assign the new value to mMemFd.
2322 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2323 if (mMemFd == -1) {
2324 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2325 }
2326 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002327 const sp<IServiceManager> sm(defaultServiceManager());
2328 const auto& mActivityManager = getActivityManager();
2329 if (mActivityManager) {
2330 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002331 callingUid,
2332 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002333 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002334 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002335}
2336
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002337bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2338 int callingPid, int callingUid) {
2339 if (!isAutomotiveDevice()) {
2340 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2341 }
2342
2343 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2344 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2345 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2346 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2347 "using camera %s", callingUid, cam_id.c_str());
2348 return false;
2349 }
2350
2351 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2352 return true;
2353 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2354 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002355 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2356 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002357 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2358 return false;
2359 } else {
2360 return true;
2361 }
2362 }
2363 return false;
2364}
2365
Austin Borgered99f642023-06-01 16:51:35 -07002366std::string CameraService::getPackageNameFromUid(int clientUid) {
2367 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002368
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002369 sp<IPermissionController> permCtrl;
2370 if (flags::cache_permission_services()) {
2371 permCtrl = getPermissionController();
2372 } else {
2373 sp<IServiceManager> sm = defaultServiceManager();
2374#pragma clang diagnostic push
2375#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2376 // Using deprecated function to preserve functionality until the
2377 // cache_permission_services flag is removed.
2378 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2379#pragma clang diagnostic pop
2380 if (binder == 0) {
2381 ALOGE("Cannot get permission service");
2382 permCtrl = nullptr;
2383 } else {
2384 permCtrl = interface_cast<IPermissionController>(binder);
2385 }
2386 }
2387
2388 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002389 // Return empty package name and the further interaction
2390 // with camera will likely fail
2391 return packageName;
2392 }
2393
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002394 Vector<String16> packages;
2395
2396 permCtrl->getPackagesForUid(clientUid, packages);
2397
2398 if (packages.isEmpty()) {
2399 ALOGE("No packages for calling UID %d", clientUid);
2400 // Return empty package name and the further interaction
2401 // with camera will likely fail
2402 return packageName;
2403 }
2404
2405 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002406 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002407
2408 return packageName;
2409}
2410
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002411template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002412Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2413 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2414 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002415 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002416 int rotationOverride, bool forceSlowJpegMode,
2417 const std::string& originalCameraId, /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002418 binder::Status ret = binder::Status::ok();
2419
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002420 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002421 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002422 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002423 getCallingUid() : clientUid;
Austin Borger6e831c42024-07-22 13:07:56 -07002424 int callingPid = getCallingPid();
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002425 if (clientPackageNameMaybe.size() <= 0) {
2426 // NDK calls don't come with package names, but we need one for various cases.
2427 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2428 // do exist. For all authentication cases, all packages under the same UID get the
2429 // same permissions, so picking any associated package name is sufficient. For some
2430 // other cases, this may give inaccurate names for clients in logs.
2431 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002432 clientPackageName = getPackageNameFromUid(packageUid);
2433 } else {
2434 clientPackageName = clientPackageNameMaybe;
2435 }
2436
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002437 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger6e831c42024-07-22 13:07:56 -07002438 callingPid : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002439 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002440 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002441 static_cast<int>(effectiveApiLevel));
2442
Shuzhen Wang316781a2020-08-18 18:11:01 -07002443 nsecs_t openTimeNs = systemTime();
2444
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002445 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002446 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002447 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002448
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002449 {
2450 // Acquire mServiceLock and prevent other clients from connecting
2451 std::unique_ptr<AutoConditionLock> lock =
2452 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2453
2454 if (lock == nullptr) {
2455 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2456 , clientPid);
2457 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2458 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002459 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002460 }
2461
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002462 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002463 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002464 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002465 return ret;
2466 }
2467
2468 // Check the shim parameters after acquiring lock, if they have already been updated and
2469 // we were doing a shim update, return immediately
2470 if (shimUpdateOnly) {
2471 auto cameraState = getCameraState(cameraId);
2472 if (cameraState != nullptr) {
2473 if (!cameraState->getShimParams().isEmpty()) return ret;
2474 }
2475 }
2476
2477 status_t err;
2478
2479 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002480 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002481 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002482 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2483 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002484 switch (err) {
2485 case -ENODEV:
2486 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2487 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002488 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002489 case -EBUSY:
2490 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2491 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002492 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002493 case -EUSERS:
2494 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2495 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002496 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002497 default:
2498 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2499 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002500 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002501 }
2502 }
2503
2504 if (clientTmp.get() != nullptr) {
2505 // Handle special case for API1 MediaRecorder where the existing client is returned
2506 device = static_cast<CLIENT*>(clientTmp.get());
2507 return ret;
2508 }
2509
2510 // give flashlight a chance to close devices if necessary.
2511 mFlashlight->prepareDeviceOpen(cameraId);
2512
Austin Borger18b30a72022-10-27 12:20:29 -07002513 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002514 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002515 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002516 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002517 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002518 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002519 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002520 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002521 }
2522
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002523 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002524 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002525 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002526
Austin Borger6e831c42024-07-22 13:07:56 -07002527 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2528 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002529 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002530 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger6e831c42024-07-22 13:07:56 -07002531 orientation, callingPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002532 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002533 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002534 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002535 return ret;
2536 }
2537 client = static_cast<CLIENT*>(tmp.get());
2538
2539 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2540 __FUNCTION__);
2541
Austin Borgered99f642023-06-01 16:51:35 -07002542 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002543 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002544 if (err != OK) {
2545 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002546 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002547 mServiceLock.unlock();
2548 client->disconnect();
2549 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002550 switch(err) {
2551 case BAD_VALUE:
2552 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002553 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002554 case -EBUSY:
2555 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002556 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002557 case -EUSERS:
2558 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2559 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002560 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002561 case PERMISSION_DENIED:
2562 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002563 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002564 case -EACCES:
2565 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002566 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002567 case -ENODEV:
2568 default:
2569 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002570 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002571 strerror(-err), err);
2572 }
2573 }
2574
2575 // Update shim paremeters for legacy clients
2576 if (effectiveApiLevel == API_1) {
2577 // Assume we have always received a Client subclass for API1
2578 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2579 String8 rawParams = shimClient->getParameters();
2580 CameraParameters params(rawParams);
2581
2582 auto cameraState = getCameraState(cameraId);
2583 if (cameraState != nullptr) {
2584 cameraState->setShimParams(params);
2585 } else {
2586 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002587 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002588 }
2589 }
2590
Ravneetaeb20dc2022-03-30 05:33:03 +00002591 // Enable/disable camera service watchdog
2592 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2593
Emilian Peev6d45db82024-01-18 20:11:54 +00002594 CameraMetadata chars;
2595 bool rotateAndCropSupported = true;
2596 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002597 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002598 if (err == OK) {
2599 auto availableRotateCropEntry = chars.find(
2600 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2601 if (availableRotateCropEntry.count <= 1) {
2602 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002603 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002604 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002605 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2606 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002607 }
2608
Emilian Peev6d45db82024-01-18 20:11:54 +00002609 if (rotateAndCropSupported) {
2610 // Set rotate-and-crop override behavior
2611 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2612 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002613 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2614 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002615 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2616 switch (portraitRotation) {
2617 case 90:
2618 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2619 break;
2620 case 180:
2621 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2622 break;
2623 case 270:
2624 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2625 break;
2626 default:
2627 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2628 break;
2629 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002630 // Here we're communicating to the client the chosen rotate
2631 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002632 client->setRotateAndCropOverride(rotateAndCropMode);
2633 } else {
2634 client->setRotateAndCropOverride(
2635 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2636 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2637 }
2638 }
2639
2640 bool autoframingSupported = true;
2641 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2642 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2643 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2644 autoframingSupported = false;
2645 }
2646
2647 if (autoframingSupported) {
2648 // Set autoframing override behaviour
2649 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2650 client->setAutoframingOverride(mOverrideAutoframingMode);
2651 } else {
2652 client->setAutoframingOverride(
2653 mCameraServiceProxyWrapper->getAutoframingOverride(
2654 clientPackageName));
2655 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002656 }
2657
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002658 bool isCameraPrivacyEnabled;
2659 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002660 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002661 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2662 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2663 } else {
2664 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002665 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002666 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002667
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002668 if (client->supportsCameraMute()) {
2669 client->setCameraMute(
2670 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2671 } else if (isCameraPrivacyEnabled) {
2672 // no camera mute supported, but privacy is on! => disconnect
2673 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2674 client->getPackageName().c_str(), cameraId.c_str());
2675 // Do not hold mServiceLock while disconnecting clients, but
2676 // retain the condition blocking other clients from connecting
2677 // in mServiceLockWrapper if held.
2678 mServiceLock.unlock();
2679 // Clear caller identity temporarily so client disconnect PID
2680 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002681 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002682 // Note AppOp to trigger the "Unblock" dialog
2683 client->noteAppOp();
2684 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002685 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002686 // Reacquire mServiceLock
2687 mServiceLock.lock();
2688
2689 return STATUS_ERROR_FMT(ERROR_DISABLED,
2690 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002691 }
2692
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002693 if (shimUpdateOnly) {
2694 // If only updating legacy shim parameters, immediately disconnect client
2695 mServiceLock.unlock();
2696 client->disconnect();
2697 mServiceLock.lock();
2698 } else {
2699 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002700 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002701 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002702
2703 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002704 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002705 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002706 } // lock is destroyed, allow further connect calls
2707
2708 // Important: release the mutex here so the client can call back into the service from its
2709 // destructor (can be at the end of the call)
2710 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002711
2712 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002713 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002714 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002715
Cliff Wud3a05312021-04-26 23:07:31 +08002716 {
2717 Mutex::Autolock lock(mInjectionParametersLock);
2718 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2719 mInjectionInitPending = false;
2720 status_t res = NO_ERROR;
2721 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2722 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002723 sp<BasicClient> clientSp = clientDescriptor->getValue();
2724 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2725 if(res != OK) {
2726 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2727 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002728 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002729 }
2730 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002731 if (res != OK) {
2732 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2733 }
2734 } else {
2735 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002736 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002737 res = NO_INIT;
2738 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2739 }
2740 }
2741 }
2742
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002743 return ret;
2744}
2745
Austin Borgered99f642023-06-01 16:51:35 -07002746status_t CameraService::addOfflineClient(const std::string &cameraId,
2747 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002748 if (offlineClient.get() == nullptr) {
2749 return BAD_VALUE;
2750 }
2751
2752 {
2753 // Acquire mServiceLock and prevent other clients from connecting
2754 std::unique_ptr<AutoConditionLock> lock =
2755 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2756
2757 if (lock == nullptr) {
2758 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2759 , __FUNCTION__, offlineClient->getClientPid());
2760 return TIMED_OUT;
2761 }
2762
2763 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2764 if (onlineClientDesc.get() == nullptr) {
2765 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2766 cameraId.c_str());
2767 return BAD_VALUE;
2768 }
2769
2770 // Offline clients do not evict or conflict with other online devices. Resource sharing
2771 // conflicts are handled by the camera provider which will either succeed or fail before
2772 // reaching this method.
2773 const auto& onlinePriority = onlineClientDesc->getPriority();
2774 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2775 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002776 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002777 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002778 // native clients don't have offline processing support.
2779 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002780 if (offlineClientDesc == nullptr) {
2781 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2782 return BAD_VALUE;
2783 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002784
2785 // Allow only one offline device per camera
2786 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2787 if (!incompatibleClients.empty()) {
2788 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2789 return BAD_VALUE;
2790 }
2791
Austin Borgered99f642023-06-01 16:51:35 -07002792 std::string monitorTags = isClientWatched(offlineClient.get())
2793 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002794 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002795 if (err != OK) {
2796 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2797 return err;
2798 }
2799
2800 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2801 if (evicted.size() > 0) {
2802 for (auto& i : evicted) {
2803 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002804 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002805 }
2806
2807 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2808 "properly", __FUNCTION__);
2809
2810 return BAD_VALUE;
2811 }
2812
2813 logConnectedOffline(offlineClientDesc->getKey(),
2814 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002815 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002816
2817 sp<IBinder> remoteCallback = offlineClient->getRemote();
2818 if (remoteCallback != nullptr) {
2819 remoteCallback->linkToDeath(this);
2820 }
2821 } // lock is destroyed, allow further connect calls
2822
2823 return OK;
2824}
2825
Austin Borgered99f642023-06-01 16:51:35 -07002826Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002827 int32_t torchStrength, const sp<IBinder>& clientBinder,
2828 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002829 Mutex::Autolock lock(mServiceLock);
2830
2831 ATRACE_CALL();
2832 if (clientBinder == nullptr) {
2833 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2834 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2835 "Torch client binder in null.");
2836 }
2837
Austin Borger22c5c852024-03-08 13:31:36 -08002838 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002839 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2840 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002841 if (!cameraIdOptional.has_value()) {
2842 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002843 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002844 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2845 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2846 }
2847 std::string cameraId = cameraIdOptional.value();
2848
Austin Borgered99f642023-06-01 16:51:35 -07002849 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002850 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002851 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002852 }
2853
2854 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002855 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002856 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002857 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002858 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002859 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002860 }
2861
2862 StatusInternal cameraStatus = state->getStatus();
2863 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2864 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002865 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002866 (int)cameraStatus);
2867 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002868 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002869 }
2870
2871 {
2872 Mutex::Autolock al(mTorchStatusMutex);
2873 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002874 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002875 if (err != OK) {
2876 if (err == NAME_NOT_FOUND) {
2877 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002878 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002879 }
2880 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002881 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002882 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2883 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002884 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002885 }
2886
2887 if (status == TorchModeStatus::NOT_AVAILABLE) {
2888 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2889 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002890 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002891 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2892 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002893 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002894 } else {
2895 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002896 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002897 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2898 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002899 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002900 }
2901 }
2902 }
2903
2904 {
2905 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002906 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002907 }
2908 // Check if the current torch strength level is same as the new one.
2909 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002910 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002911
Austin Borgered99f642023-06-01 16:51:35 -07002912 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002913
2914 if (err != OK) {
2915 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002916 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002917 switch (err) {
2918 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002919 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2920 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 errorCode = ERROR_ILLEGAL_ARGUMENT;
2922 break;
2923 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002924 msg = fmt::sprintf("Camera \"%s\" is in use",
2925 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002926 errorCode = ERROR_CAMERA_IN_USE;
2927 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002928 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002929 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002930 "valid range.", torchStrength);
2931 errorCode = ERROR_ILLEGAL_ARGUMENT;
2932 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002933 default:
Austin Borgered99f642023-06-01 16:51:35 -07002934 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002935 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002936 }
Austin Borgered99f642023-06-01 16:51:35 -07002937 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2938 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002939 }
2940
2941 {
2942 // update the link to client's death
2943 // Store the last client that turns on each camera's torch mode.
2944 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002945 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002946 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002947 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002948 } else {
2949 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2950 mTorchClientMap.replaceValueAt(index, clientBinder);
2951 }
2952 clientBinder->linkToDeath(this);
2953 }
2954
Austin Borger22c5c852024-03-08 13:31:36 -08002955 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002956 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002957 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002958 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002959 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002960 }
2961 return Status::ok();
2962}
2963
malikakash73125c62023-07-21 22:44:34 +00002964Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07002965 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
2966 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002967 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002968
2969 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07002970 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002971 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002972 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2973 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08002974 }
2975
Austin Borger22c5c852024-03-08 13:31:36 -08002976 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002977 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2978 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002979 if (!cameraIdOptional.has_value()) {
2980 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002981 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002982 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2983 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2984 }
2985 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002986
Austin Borgered99f642023-06-01 16:51:35 -07002987 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002988 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07002989 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07002990 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002991 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07002992 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08002993 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002994 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002995 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002996 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002997 }
2998
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002999 StatusInternal cameraStatus = state->getStatus();
3000 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003001 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003002 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3003 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003004 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003005 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003006 }
3007
3008 {
3009 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003010 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003011 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003012 if (err != OK) {
3013 if (err == NAME_NOT_FOUND) {
3014 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003015 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003016 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003017 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003018 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003019 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003020 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003021 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003022 }
3023
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003024 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003025 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003026 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003027 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003028 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3029 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003030 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003031 } else {
3032 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003033 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3035 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003036 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003037 }
3038 }
3039 }
3040
Ruben Brunk99e69712015-05-26 17:25:07 -07003041 {
3042 // Update UID map - this is used in the torch status changed callbacks, so must be done
3043 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003044 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003045 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003046 }
3047
Austin Borgered99f642023-06-01 16:51:35 -07003048 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003049
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003050 if (err != OK) {
3051 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003052 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003053 switch (err) {
3054 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003055 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3056 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003057 errorCode = ERROR_ILLEGAL_ARGUMENT;
3058 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003059 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003060 msg = fmt::sprintf("Camera \"%s\" is in use",
3061 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003062 errorCode = ERROR_CAMERA_IN_USE;
3063 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003064 default:
Austin Borgered99f642023-06-01 16:51:35 -07003065 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003066 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003067 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003068 errorCode = ERROR_INVALID_OPERATION;
3069 }
Austin Borgered99f642023-06-01 16:51:35 -07003070 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3071 logServiceError(msg, errorCode);
3072 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003073 }
3074
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003075 {
3076 // update the link to client's death
3077 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003078 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003079 if (enabled) {
3080 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003081 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003082 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003083 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003084 mTorchClientMap.replaceValueAt(index, clientBinder);
3085 }
3086 clientBinder->linkToDeath(this);
3087 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003088 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003089 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003090 }
3091
Austin Borger22c5c852024-03-08 13:31:36 -08003092 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003093 std::string torchState = enabled ? "on" : "off";
3094 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3095 torchState.c_str(), clientPid);
3096 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003097 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003098}
3099
Austin Borgered99f642023-06-01 16:51:35 -07003100void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3101 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3102 mTorchUidMap[cameraId].first = uid;
3103 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003104 } else {
3105 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003106 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003107 }
3108}
3109
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003110Status CameraService::notifySystemEvent(int32_t eventId,
3111 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003112 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003113 const int selfPid = getpid();
3114
3115 // Permission checks
3116 if (pid != selfPid) {
3117 // Ensure we're being called by system_server, or similar process with
3118 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003119 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003120 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003121 ALOGE("Permission Denial: cannot send updates to camera service about system"
3122 " events from pid=%d, uid=%d", pid, uid);
3123 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003124 "No permission to send updates to camera service about system events"
3125 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003126 }
3127 }
3128
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003129 ATRACE_CALL();
3130
Ruben Brunk36597b22015-03-20 22:15:57 -07003131 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003132 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003133 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003134 // from a system server crash
3135 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003136 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003137 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003138 break;
3139 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003140 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3141 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003142 if (args.size() != 1) {
3143 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3144 "USB Device Event requires 1 argument");
3145 }
3146
Valentin Iftime29e2e152021-08-13 15:17:33 +02003147 // Notify CameraProviderManager for lazy HALs
3148 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3149 std::to_string(args[0]));
3150 break;
3151 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003152 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003153 default: {
3154 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3155 eventId);
3156 break;
3157 }
3158 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003159 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003160}
3161
Emilian Peev53722fa2019-02-22 17:47:20 -08003162void CameraService::notifyMonitoredUids() {
3163 Mutex::Autolock lock(mStatusListenerLock);
3164
3165 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003166 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003167 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3168 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003169 }
3170}
3171
Austin Borgerdddb7552023-03-30 17:53:01 -07003172void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3173 Mutex::Autolock lock(mStatusListenerLock);
3174
3175 for (const auto& it : mListenerList) {
3176 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3177 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3178 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3179 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3180 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3181 }
3182 }
3183}
3184
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003185Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003186 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003187 const int selfPid = getpid();
3188
3189 // Permission checks
3190 if (pid != selfPid) {
3191 // Ensure we're being called by system_server, or similar process with
3192 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003193 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003194 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003195 ALOGE("Permission Denial: cannot send updates to camera service about device"
3196 " state changes from pid=%d, uid=%d", pid, uid);
3197 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3198 "No permission to send updates to camera service about device state"
3199 " changes from pid=%d, uid=%d", pid, uid);
3200 }
3201 }
3202
3203 ATRACE_CALL();
3204
Austin Borger18b30a72022-10-27 12:20:29 -07003205 {
3206 Mutex::Autolock lock(mServiceLock);
3207 mDeviceState = newState;
3208 }
3209
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003210 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003211
3212 return Status::ok();
3213}
3214
Emilian Peev8b64f282021-03-25 16:49:57 -07003215Status CameraService::notifyDisplayConfigurationChange() {
3216 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003217 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003218 const int selfPid = getpid();
3219
3220 // Permission checks
3221 if (callingPid != selfPid) {
3222 // Ensure we're being called by system_server, or similar process with
3223 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003224 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003225 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003226 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3227 " changes from pid=%d, uid=%d", callingPid, uid);
3228 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3229 "No permission to send updates to camera service about orientation"
3230 " changes from pid=%d, uid=%d", callingPid, uid);
3231 }
3232 }
3233
3234 Mutex::Autolock lock(mServiceLock);
3235
3236 // Don't do anything if rotate-and-crop override via cmd is active
3237 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3238
3239 const auto clients = mActiveClientManager.getAll();
3240 for (auto& current : clients) {
3241 if (current != nullptr) {
3242 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003243 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3244 basicClient->setRotateAndCropOverride(
3245 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3246 basicClient->getPackageName(),
3247 basicClient->getCameraFacing(),
3248 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003249 }
3250 }
3251 }
3252
3253 return Status::ok();
3254}
3255
3256Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003257 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3258 ATRACE_CALL();
3259 if (!concurrentCameraIds) {
3260 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3261 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3262 }
3263
3264 if (!mInitialized) {
3265 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003266 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003267 return STATUS_ERROR(ERROR_DISCONNECTED,
3268 "Camera subsystem is not available");
3269 }
3270 // First call into the provider and get the set of concurrent camera
3271 // combinations
3272 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003273 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003274 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003275 std::vector<std::pair<std::string, int32_t>> validCombination;
3276 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003277 for (auto &cameraId : combination) {
3278 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003279 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003280 if (state == nullptr) {
3281 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3282 continue;
3283 }
3284 StatusInternal status = state->getStatus();
3285 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3286 continue;
3287 }
Austin Borgered99f642023-06-01 16:51:35 -07003288 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003289 continue;
3290 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003291 auto [cameraOwnerDeviceId, mappedCameraId] =
3292 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3293 if (firstDeviceId == kInvalidDeviceId) {
3294 firstDeviceId = cameraOwnerDeviceId;
3295 } else if (firstDeviceId != cameraOwnerDeviceId) {
3296 // Found an invalid combination which contains cameras with different device id's,
3297 // hence discard it.
3298 validCombination.clear();
3299 break;
3300 }
3301 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003302 }
3303 if (validCombination.size() != 0) {
3304 concurrentCameraIds->push_back(std::move(validCombination));
3305 }
3306 }
3307 return Status::ok();
3308}
3309
3310Status CameraService::isConcurrentSessionConfigurationSupported(
3311 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003312 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003313 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003314 if (!isSupported) {
3315 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3316 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3317 }
3318
3319 if (!mInitialized) {
3320 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3321 return STATUS_ERROR(ERROR_DISCONNECTED,
3322 "Camera subsystem is not available");
3323 }
3324
Biswarup Pal7d072862024-04-17 15:24:47 +00003325 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3326 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003327 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3328 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003329 if (!cameraIdOptional.has_value()) {
3330 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003331 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003332 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3333 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3334 }
3335 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3336 }
3337
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003338 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003339 int callingPid = getCallingPid();
3340 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003341 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003342 hasPermissionsForCamera(callingPid, callingUid,
3343 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003344 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003345 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003346 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3347 "android.permission.CAMERA needed to call"
3348 "isConcurrentSessionConfigurationSupported");
3349 }
3350
3351 status_t res =
3352 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003353 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3354 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003355 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003356 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003357 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003358 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3359 "support %s (%d)", strerror(-res), res);
3360 }
3361 return Status::ok();
3362}
3363
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003364Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3365 /*out*/
3366 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003367 return addListenerHelper(listener, cameraStatuses);
3368}
3369
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003370binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3371 std::vector<hardware::CameraStatus>* cameraStatuses) {
3372 return addListenerHelper(listener, cameraStatuses, false, true);
3373}
3374
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003375Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3376 /*out*/
3377 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003378 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003379 ATRACE_CALL();
3380
Igor Murashkinbfc99152013-02-27 12:55:20 -08003381 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003382
Ruben Brunk3450ba72015-06-16 11:00:37 -07003383 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003384 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003385 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003386 }
3387
Austin Borger22c5c852024-03-08 13:31:36 -08003388 auto clientPid = getCallingPid();
3389 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003390 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003391
Igor Murashkinbfc99152013-02-27 12:55:20 -08003392 Mutex::Autolock lock(mServiceLock);
3393
Ruben Brunkcc776712015-02-17 20:18:47 -08003394 {
3395 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003396 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003397 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003398 ALOGW("%s: Tried to add listener %p which was already subscribed",
3399 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003400 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003401 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003402 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003403
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003404 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003405 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3406 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003407 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003408 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003409 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003410 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003411 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3412 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3413 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003414 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003415 // The listener still needs to be added to the list of listeners, regardless of what
3416 // permissions the listener process has / whether it is a vendor listener. Since it might be
3417 // eligible to listen to other camera ids.
3418 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003419 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003420 }
3421
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003422 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003423 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003424 Mutex::Autolock lock(mCameraStatesLock);
3425 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003426 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3427 auto [deviceId, mappedCameraId] =
3428 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3429
3430 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003431 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003432 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3433 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003434 }
3435 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003436 // Remove the camera statuses that should be hidden from the client, we do
3437 // this after collecting the states in order to avoid holding
3438 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3439 // the same time.
3440 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3441 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003442 std::string cameraId = s.cameraId;
3443 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003444 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003445 if (!cameraIdOptional.has_value()) {
3446 std::string msg =
3447 fmt::sprintf(
3448 "Camera %s: Invalid camera id for device id %d",
3449 s.cameraId.c_str(), s.deviceId);
3450 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3451 return true;
3452 }
3453 cameraId = cameraIdOptional.value();
3454 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3455 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3456 ALOGE("%s: Invalid camera id %s, skipping status update",
3457 __FUNCTION__, s.cameraId.c_str());
3458 return true;
3459 }
3460 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3461 clientUid);
3462 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003463
Biswarup Pal37a75182024-01-16 15:53:35 +00003464 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003465 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003466 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003467 // Add only default device cameras here, as virtual cameras currently don't support torch
3468 // anyway. Note that this is a simplification of the implementation here, and we should
3469 // change this when virtual cameras support torch.
3470 if (s.deviceId == kDefaultDeviceId) {
3471 idsChosenForCallback.insert(s.cameraId);
3472 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003473 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003474
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003475 /*
3476 * Immediately signal current torch status to this listener only
3477 * This may be a subset of all the devices, so don't include it in the response directly
3478 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003479 {
3480 Mutex::Autolock al(mTorchStatusMutex);
3481 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003482 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003483 // The camera id is visible to the client. Fine to send torch
3484 // callback.
3485 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003486 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3487 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003488 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003489 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003490 }
3491
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003492 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003493}
Ruben Brunkcc776712015-02-17 20:18:47 -08003494
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003495Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003496 ATRACE_CALL();
3497
Igor Murashkinbfc99152013-02-27 12:55:20 -08003498 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3499
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003500 if (listener == 0) {
3501 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003502 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003503 }
3504
Igor Murashkinbfc99152013-02-27 12:55:20 -08003505 Mutex::Autolock lock(mServiceLock);
3506
Ruben Brunkcc776712015-02-17 20:18:47 -08003507 {
3508 Mutex::Autolock lock(mStatusListenerLock);
3509 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003510 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003511 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003512 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003513 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003514 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003515 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003516 }
3517 }
3518
3519 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3520 __FUNCTION__, listener.get());
3521
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003522 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003523}
3524
Austin Borgered99f642023-06-01 16:51:35 -07003525Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003526
3527 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003528 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3529
3530 if (parameters == NULL) {
3531 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003532 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003533 }
3534
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003535 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003536
3537 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003538 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003539 // Error logged by caller
3540 return ret;
3541 }
3542
3543 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003544
Austin Borgered99f642023-06-01 16:51:35 -07003545 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003546
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003547 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003548}
3549
malikakash98260df2024-05-10 23:33:57 +00003550Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003551 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003552 ATRACE_CALL();
3553
Austin Borgered99f642023-06-01 16:51:35 -07003554 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003555
3556 switch (apiVersion) {
3557 case API_VERSION_1:
3558 case API_VERSION_2:
3559 break;
3560 default:
Austin Borgered99f642023-06-01 16:51:35 -07003561 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3562 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3563 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003564 }
3565
Austin Borger18b30a72022-10-27 12:20:29 -07003566 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003567 auto deviceVersionAndTransport =
3568 getDeviceVersion(cameraId,
3569 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3570 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003571 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003572 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3573 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3574 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003575 }
3576 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3577 int deviceVersion = deviceVersionAndTransport.first;
3578 switch (deviceVersion) {
3579 case CAMERA_DEVICE_API_VERSION_1_0:
3580 case CAMERA_DEVICE_API_VERSION_3_0:
3581 case CAMERA_DEVICE_API_VERSION_3_1:
3582 if (apiVersion == API_VERSION_2) {
3583 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003584 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003585 *isSupported = false;
3586 } else { // if (apiVersion == API_VERSION_1) {
3587 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003588 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003589 *isSupported = true;
3590 }
3591 break;
3592 case CAMERA_DEVICE_API_VERSION_3_2:
3593 case CAMERA_DEVICE_API_VERSION_3_3:
3594 case CAMERA_DEVICE_API_VERSION_3_4:
3595 case CAMERA_DEVICE_API_VERSION_3_5:
3596 case CAMERA_DEVICE_API_VERSION_3_6:
3597 case CAMERA_DEVICE_API_VERSION_3_7:
3598 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003599 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003600 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003601 break;
3602 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003603 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3604 deviceVersion, cameraId.c_str());
3605 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3606 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003607 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003608 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003609 } else {
3610 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003611 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003612 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003613}
3614
malikakash98260df2024-05-10 23:33:57 +00003615Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003616 /*out*/ bool *isSupported) {
3617 ATRACE_CALL();
3618
Austin Borgered99f642023-06-01 16:51:35 -07003619 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3620 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003621
3622 return Status::ok();
3623}
3624
Cliff Wud8cae102021-03-11 01:37:42 +08003625Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003626 const std::string& packageName, const std::string& internalCamId,
3627 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003628 const sp<ICameraInjectionCallback>& callback,
3629 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003630 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003631 ATRACE_CALL();
3632
Austin Borgered99f642023-06-01 16:51:35 -07003633 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003634 const int pid = getCallingPid();
3635 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003636 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3637 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003638 "Permission Denial: no permission to inject camera");
3639 }
3640
3641 // Do not allow any camera injection that injects or replaces a virtual camera.
3642 auto [deviceIdForInternalCamera, _] =
3643 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3644 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3645 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3646 "Cannot replace a virtual camera");
3647 }
3648 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3649 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3650 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3651 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3652 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003653 }
3654
3655 ALOGV(
3656 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3657 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003658 __FUNCTION__, packageName.c_str(),
3659 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003660
Cliff Wud3a05312021-04-26 23:07:31 +08003661 {
3662 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003663 mInjectionInternalCamId = internalCamId;
3664 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003665 mInjectionStatusListener->addListener(callback);
3666 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003667 status_t res = NO_ERROR;
3668 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3669 // If the client already exists, we can directly connect to the camera device through the
3670 // client's injectCamera(), otherwise we need to wait until the client is established
3671 // (execute connectHelper()) before injecting the camera to the camera device.
3672 if (clientDescriptor != nullptr) {
3673 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003674 sp<BasicClient> clientSp = clientDescriptor->getValue();
3675 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3676 if(res != OK) {
3677 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3678 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003679 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003680 }
3681 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003682 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003683 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3684 }
3685 } else {
3686 mInjectionInitPending = true;
3687 }
3688 }
Cliff Wud8cae102021-03-11 01:37:42 +08003689
Cliff Wud3a05312021-04-26 23:07:31 +08003690 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003691}
3692
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003693Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003694 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003695 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3696 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3697 return Status::ok();
3698}
3699
Ruben Brunkcc776712015-02-17 20:18:47 -08003700void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003701 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003702 for (auto& i : mActiveClientManager.getAll()) {
3703 auto clientSp = i->getValue();
3704 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003705 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003706 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003707 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003708 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003709 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003710}
3711
Ruben Brunkcc776712015-02-17 20:18:47 -08003712bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003713 bool ret = false;
3714 {
3715 // Acquire mServiceLock and prevent other clients from connecting
3716 std::unique_ptr<AutoConditionLock> lock =
3717 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003718
Ruben Brunkcc776712015-02-17 20:18:47 -08003719 std::vector<sp<BasicClient>> evicted;
3720 for (auto& i : mActiveClientManager.getAll()) {
3721 auto clientSp = i->getValue();
3722 if (clientSp.get() == nullptr) {
3723 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3724 mActiveClientManager.remove(i);
3725 continue;
3726 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003727 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003728 mActiveClientManager.remove(i);
3729 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003730
Ruben Brunkcc776712015-02-17 20:18:47 -08003731 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003732 clientSp->notifyError(
3733 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003734 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003735 }
3736 }
3737
Ruben Brunkcc776712015-02-17 20:18:47 -08003738 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3739 // other clients from connecting in mServiceLockWrapper if held
3740 mServiceLock.unlock();
3741
Ruben Brunk36597b22015-03-20 22:15:57 -07003742 // Do not clear caller identity, remote caller should be client proccess
3743
Ruben Brunkcc776712015-02-17 20:18:47 -08003744 for (auto& i : evicted) {
3745 if (i.get() != nullptr) {
3746 i->disconnect();
3747 ret = true;
3748 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003749 }
3750
Ruben Brunkcc776712015-02-17 20:18:47 -08003751 // Reacquire mServiceLock
3752 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003753
Ruben Brunkcc776712015-02-17 20:18:47 -08003754 } // lock is destroyed, allow further connect calls
3755
3756 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003757}
3758
Ruben Brunkcc776712015-02-17 20:18:47 -08003759std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003760 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003761 std::shared_ptr<CameraState> state;
3762 {
3763 Mutex::Autolock lock(mCameraStatesLock);
3764 auto iter = mCameraStates.find(cameraId);
3765 if (iter != mCameraStates.end()) {
3766 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003767 }
3768 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003769 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003770}
3771
Austin Borgered99f642023-06-01 16:51:35 -07003772sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003773 // Remove from active clients list
3774 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3775 if (clientDescriptorPtr == nullptr) {
3776 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003777 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003778 return sp<BasicClient>{nullptr};
3779 }
3780
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003781 sp<BasicClient> client = clientDescriptorPtr->getValue();
3782 if (client.get() != nullptr) {
3783 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3784 }
3785 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003786}
3787
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003788void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003789 // Acquire mServiceLock and prevent other clients from connecting
3790 std::unique_ptr<AutoConditionLock> lock =
3791 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3792
Ruben Brunk6267b532015-04-30 17:44:07 -07003793 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003794 for (size_t i = 0; i < newUserIds.size(); i++) {
3795 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003796 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003797 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003798 return;
3799 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003800 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003801 }
3802
Ruben Brunka8ca9152015-04-07 14:23:40 -07003803
Ruben Brunk6267b532015-04-30 17:44:07 -07003804 if (newAllowedUsers == mAllowedUsers) {
3805 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3806 return;
3807 }
3808
3809 logUserSwitch(mAllowedUsers, newAllowedUsers);
3810
3811 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003812
3813 // Current user has switched, evict all current clients.
3814 std::vector<sp<BasicClient>> evicted;
3815 for (auto& i : mActiveClientManager.getAll()) {
3816 auto clientSp = i->getValue();
3817
3818 if (clientSp.get() == nullptr) {
3819 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3820 continue;
3821 }
3822
Ruben Brunk6267b532015-04-30 17:44:07 -07003823 // Don't evict clients that are still allowed.
3824 uid_t clientUid = clientSp->getClientUid();
3825 userid_t clientUserId = multiuser_get_user_id(clientUid);
3826 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3827 continue;
3828 }
3829
Ruben Brunk36597b22015-03-20 22:15:57 -07003830 evicted.push_back(clientSp);
3831
Ruben Brunk36597b22015-03-20 22:15:57 -07003832 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003833 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003834
Ruben Brunk36597b22015-03-20 22:15:57 -07003835 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003836 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003837 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003838 " to user switch.", i->getKey().c_str(),
3839 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003840 i->getOwnerId(), i->getPriority().getScore(),
3841 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003842
3843 }
3844
3845 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3846 // blocking other clients from connecting in mServiceLockWrapper if held.
3847 mServiceLock.unlock();
3848
3849 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003850 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003851
3852 for (auto& i : evicted) {
3853 i->disconnect();
3854 }
3855
Austin Borger22c5c852024-03-08 13:31:36 -08003856 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003857
3858 // Reacquire mServiceLock
3859 mServiceLock.lock();
3860}
Ruben Brunkcc776712015-02-17 20:18:47 -08003861
Austin Borgered99f642023-06-01 16:51:35 -07003862void CameraService::logEvent(const std::string &event) {
3863 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003864 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003865 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003866 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003867 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003868 mEventLog.add(msg);
3869 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3870 // Error event not added to the dumpsys log before
3871 mEventLog.add(msg);
3872 sServiceErrorEventSet.insert(msg);
3873 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003874}
3875
Austin Borgered99f642023-06-01 16:51:35 -07003876void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3877 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003878 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003879 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3880 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003881}
3882
Austin Borgered99f642023-06-01 16:51:35 -07003883void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3884 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003885 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003886 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3887 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003888}
3889
Austin Borgered99f642023-06-01 16:51:35 -07003890void CameraService::logConnected(const std::string &cameraId, int clientPid,
3891 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003892 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003893 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3894 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003895}
3896
Austin Borgered99f642023-06-01 16:51:35 -07003897void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3898 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003899 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003900 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3901 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003902}
3903
Austin Borgered99f642023-06-01 16:51:35 -07003904void CameraService::logRejected(const std::string &cameraId, int clientPid,
3905 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003906 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003907 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3908 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003909}
3910
Austin Borgered99f642023-06-01 16:51:35 -07003911void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3912 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003913 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003914 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3915 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003916}
3917
Ruben Brunk6267b532015-04-30 17:44:07 -07003918void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3919 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003920 std::string newUsers = toString(newUserIds);
3921 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003922 if (oldUsers.size() == 0) {
3923 oldUsers = "<None>";
3924 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003925 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003926 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3927 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003928}
3929
Austin Borgered99f642023-06-01 16:51:35 -07003930void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003931 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003932 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003933}
3934
Austin Borgered99f642023-06-01 16:51:35 -07003935void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003936 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003937 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003938}
3939
Austin Borgered99f642023-06-01 16:51:35 -07003940void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003941 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003942 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003943}
3944
Austin Borgered99f642023-06-01 16:51:35 -07003945void CameraService::logServiceError(const std::string &msg, int errorCode) {
3946 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3947 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003948}
3949
Ruben Brunk36597b22015-03-20 22:15:57 -07003950status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3951 uint32_t flags) {
3952
Mathias Agopian65ab4712010-07-14 17:59:35 -07003953 // Permission checks
3954 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003955 case SHELL_COMMAND_TRANSACTION: {
3956 int in = data.readFileDescriptor();
3957 int out = data.readFileDescriptor();
3958 int err = data.readFileDescriptor();
3959 int argc = data.readInt32();
3960 Vector<String16> args;
3961 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
3962 args.add(data.readString16());
3963 }
3964 sp<IBinder> unusedCallback;
3965 sp<IResultReceiver> resultReceiver;
3966 status_t status;
3967 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
3968 return status;
3969 }
3970 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
3971 return status;
3972 }
3973 status = shellCommand(in, out, err, args);
3974 if (resultReceiver != nullptr) {
3975 resultReceiver->send(status);
3976 }
3977 return NO_ERROR;
3978 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003979 }
3980
3981 return BnCameraService::onTransact(code, data, reply, flags);
3982}
3983
Mathias Agopian65ab4712010-07-14 17:59:35 -07003984// We share the media players for shutter and recording sound for all clients.
3985// A reference count is kept to determine when we will actually release the
3986// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09003987sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
3988 sp<MediaPlayer> mp = new MediaPlayer();
3989 status_t error;
3990 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08003991 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09003992 error = mp->prepare();
3993 }
3994 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00003995 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09003996 mp->disconnect();
3997 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09003998 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003999 }
4000 return mp;
4001}
4002
username5755fea2018-12-27 09:48:08 +08004003void CameraService::increaseSoundRef() {
4004 Mutex::Autolock lock(mSoundLock);
4005 mSoundRef++;
4006}
4007
4008void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004009 ATRACE_CALL();
4010
username5755fea2018-12-27 09:48:08 +08004011 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4012 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4013 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4014 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4015 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4016 }
4017 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4018 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4019 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4020 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004021 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004022 }
4023 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4024 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4025 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4026 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4027 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004028 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004029}
4030
username5755fea2018-12-27 09:48:08 +08004031void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004032 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004033 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004034 if (--mSoundRef) return;
4035
4036 for (int i = 0; i < NUM_SOUNDS; i++) {
4037 if (mSoundPlayer[i] != 0) {
4038 mSoundPlayer[i]->disconnect();
4039 mSoundPlayer[i].clear();
4040 }
4041 }
4042}
4043
4044void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004045 ATRACE_CALL();
4046
Mathias Agopian65ab4712010-07-14 17:59:35 -07004047 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004048 if (kind < 0 || kind >= NUM_SOUNDS) {
4049 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4050 return;
4051 }
4052
Mathias Agopian65ab4712010-07-14 17:59:35 -07004053 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004054 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004055 sp<MediaPlayer> player = mSoundPlayer[kind];
4056 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004057 player->seekTo(0);
4058 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004059 }
4060}
4061
4062// ----------------------------------------------------------------------------
4063
4064CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004065 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004066 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004067 const std::string& clientPackageName, bool systemNativeClient,
4068 const std::optional<std::string>& clientFeatureId,
4069 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004070 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004071 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004072 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004073 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004074 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004075 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004076 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004077 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004078 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004079 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004080 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004081{
Austin Borger22c5c852024-03-08 13:31:36 -08004082 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004083 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004084
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004085 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086
username5755fea2018-12-27 09:48:08 +08004087 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004088
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004089 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004090}
4091
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092// tear down the client
4093CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004094 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004095 mDestructionStarted = true;
4096
username5755fea2018-12-27 09:48:08 +08004097 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004098 // unconditionally disconnect. function is idempotent
4099 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004100}
4101
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004102sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4103
Igor Murashkin634a5152013-02-20 17:15:11 -08004104CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004105 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004106 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004107 const std::string& clientPackageName, bool nativeClient,
4108 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004109 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004110 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004111 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004112 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004113 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004114 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4115 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004116 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004117 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004118 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004119 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004120 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004121 mRemoteBinder(remoteCallback),
4122 mOpsActive(false),
4123 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004124{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004125 if (sCameraService == nullptr) {
4126 sCameraService = cameraService;
4127 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004128
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004129 // There are 2 scenarios in which a client won't have AppOps operations
4130 // (both scenarios : native clients)
4131 // 1) It's an system native client*, the package name will be empty
4132 // and it will return from this function in the previous if condition
4133 // (This is the same as the previously existing behavior).
4134 // 2) It is a system native client, but its package name has been
4135 // modified for debugging, however it still must not use AppOps since
4136 // the package name is not a real one.
4137 //
4138 // * system native client - native client with UID < AID_APP_START. It
4139 // doesn't exclude clients not on the system partition.
4140 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004141 mAppOpsManager = std::make_unique<AppOpsManager>();
4142 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004143
Charles Chenf075f082024-03-04 23:32:55 +00004144 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004145}
4146
4147CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004148 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004149 mDestructionStarted = true;
4150}
4151
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004152binder::Status CameraService::BasicClient::disconnect() {
4153 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004154 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004155 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004156 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004157 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004158
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004159 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004160 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004161 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004162 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004163
4164 sp<IBinder> remote = getRemote();
4165 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004166 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004167 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004168
4169 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004170 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004171 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004172 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004173 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004174
Igor Murashkincba2c162013-03-20 15:56:31 -07004175 // client shouldn't be able to call into us anymore
4176 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004177
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004178 const auto& mActivityManager = getActivityManager();
4179 if (mActivityManager) {
4180 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004181 getCallingUid(),
4182 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004183 }
4184
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004185 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004186}
4187
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004188status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4189 // No dumping of clients directly over Binder,
4190 // must go through CameraService::dump
4191 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004192 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004193 return OK;
4194}
4195
Austin Borgered99f642023-06-01 16:51:35 -07004196status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004197 // Can't watch tags directly, must go through CameraService::startWatchingTags
4198 return OK;
4199}
4200
4201status_t CameraService::BasicClient::stopWatchingTags(int) {
4202 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4203 return OK;
4204}
4205
4206status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4207 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4208 return OK;
4209}
4210
Austin Borgered99f642023-06-01 16:51:35 -07004211std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004212 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004213}
4214
Emilian Peev8b64f282021-03-25 16:49:57 -07004215int CameraService::BasicClient::getCameraFacing() const {
4216 return mCameraFacing;
4217}
4218
4219int CameraService::BasicClient::getCameraOrientation() const {
4220 return mOrientation;
4221}
Ruben Brunkcc776712015-02-17 20:18:47 -08004222
4223int CameraService::BasicClient::getClientPid() const {
4224 return mClientPid;
4225}
4226
Ruben Brunk6267b532015-04-30 17:44:07 -07004227uid_t CameraService::BasicClient::getClientUid() const {
4228 return mClientUid;
4229}
4230
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004231bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4232 // Defaults to API2.
4233 return level == API_2;
4234}
4235
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004236status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004237 {
4238 Mutex::Autolock l(mAudioRestrictionLock);
4239 mAudioRestriction = mode;
4240 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004241 sCameraService->updateAudioRestriction();
4242 return OK;
4243}
4244
4245int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004246 return sCameraService->updateAudioRestriction();
4247}
4248
4249int32_t CameraService::BasicClient::getAudioRestriction() const {
4250 Mutex::Autolock l(mAudioRestrictionLock);
4251 return mAudioRestriction;
4252}
4253
4254bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4255 switch (mode) {
4256 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4257 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4258 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4259 return true;
4260 default:
4261 return false;
4262 }
4263}
4264
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004265status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4266 if (mode == AppOpsManager::MODE_ERRORED) {
4267 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004268 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004269 return PERMISSION_DENIED;
4270 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4271 // If the calling Uid is trusted (a native service), the AppOpsManager could
4272 // return MODE_IGNORED. Do not treat such case as error.
4273 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4274 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004275
4276 bool isCameraPrivacyEnabled;
4277 if (flags::camera_privacy_allowlist()) {
4278 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4279 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4280 } else {
4281 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004282 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004283 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004284 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4285 // We prefer to successfully open the camera and perform camera muting
4286 // or blocking in connectHelper as handleAppOpMode can be called before the
4287 // connection has been fully established and at that time camera muting
4288 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004289 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004290 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4291 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4292 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4293 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004294 // Return the same error as for device policy manager rejection
4295 return -EACCES;
4296 }
4297 }
4298 return OK;
4299}
4300
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004301status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004302 ATRACE_CALL();
4303
Igor Murashkine6800ce2013-03-04 17:25:57 -08004304 {
4305 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004306 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004307 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004308 if (mAppOpsManager != nullptr) {
4309 // Notify app ops that the camera is not available
4310 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004311
4312 if (flags::watch_foreground_changes()) {
4313 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4314 toString16(mClientPackageName),
4315 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4316 } else {
4317 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004318 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004319 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004320
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004321 // Just check for camera acccess here on open - delay startOp until
4322 // camera frames start streaming in startCameraStreamingOps
4323 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004324 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004325 status_t res = handleAppOpMode(mode);
4326 if (res != OK) {
4327 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004328 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004329 }
4330
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004331 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004332
4333 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004334 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004335
Austin Borgerdddb7552023-03-30 17:53:01 -07004336 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004337
Shuzhen Wang695044d2020-03-06 09:02:23 -08004338 // Notify listeners of camera open/close status
4339 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4340
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004341 return OK;
4342}
4343
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004344status_t CameraService::BasicClient::startCameraStreamingOps() {
4345 ATRACE_CALL();
4346
4347 if (!mOpsActive) {
4348 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4349 return INVALID_OPERATION;
4350 }
4351 if (mOpsStreaming) {
4352 ALOGV("%s: Streaming already active!", __FUNCTION__);
4353 return OK;
4354 }
4355
4356 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004357 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004358
4359 if (mAppOpsManager != nullptr) {
4360 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004361 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4362 toString16(mClientFeatureId),
4363 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004364 status_t res = handleAppOpMode(mode);
4365 if (res != OK) {
4366 return res;
4367 }
4368 }
4369
4370 mOpsStreaming = true;
4371
4372 return OK;
4373}
4374
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004375status_t CameraService::BasicClient::noteAppOp() {
4376 ATRACE_CALL();
4377
4378 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004379 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004380
4381 // noteAppOp is only used for when camera mute is not supported, in order
4382 // to trigger the sensor privacy "Unblock" dialog
4383 if (mAppOpsManager != nullptr) {
4384 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004385 toString16(mClientPackageName), toString16(mClientFeatureId),
4386 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004387 status_t res = handleAppOpMode(mode);
4388 if (res != OK) {
4389 return res;
4390 }
4391 }
4392
4393 return OK;
4394}
4395
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004396status_t CameraService::BasicClient::finishCameraStreamingOps() {
4397 ATRACE_CALL();
4398
4399 if (!mOpsActive) {
4400 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4401 return INVALID_OPERATION;
4402 }
4403 if (!mOpsStreaming) {
4404 ALOGV("%s: Streaming not active!", __FUNCTION__);
4405 return OK;
4406 }
4407
4408 if (mAppOpsManager != nullptr) {
4409 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004410 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004411 mOpsStreaming = false;
4412 }
4413
4414 return OK;
4415}
4416
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004417status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004418 ATRACE_CALL();
4419
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004420 if (mOpsStreaming) {
4421 // Make sure we've notified everyone about camera stopping
4422 finishCameraStreamingOps();
4423 }
4424
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004425 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004426 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004427 mOpsActive = false;
4428
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004429 // This function is called when a client disconnects. This should
4430 // release the camera, but actually only if it was in a proper
4431 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004432 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004433 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004434
Ruben Brunkcc776712015-02-17 20:18:47 -08004435 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004436 sCameraService->updateStatus(StatusInternal::PRESENT,
4437 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004438 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004439 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004440 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4441 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004442 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004443 mOpsCallback.clear();
4444
Austin Borgerdddb7552023-03-30 17:53:01 -07004445 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004446
Shuzhen Wang695044d2020-03-06 09:02:23 -08004447 // Notify listeners of camera open/close status
4448 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4449
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004450 return OK;
4451}
4452
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004453void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004454 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004455 if (mAppOpsManager == nullptr) {
4456 return;
4457 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004458 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004459 if (op != AppOpsManager::OP_CAMERA) {
4460 ALOGW("Unexpected app ops notification received: %d", op);
4461 return;
4462 }
4463
4464 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004465 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004466 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004467 ALOGV("checkOp returns: %d, %s ", res,
4468 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4469 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4470 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4471 "UNKNOWN");
4472
Shuzhen Wang64900852021-02-05 09:03:29 -08004473 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004474 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4475 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004476 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004477 } else if (res == AppOpsManager::MODE_IGNORED) {
4478 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004479
Austin Borgerca1e0062023-06-28 11:32:55 -07004480 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4481 // If not visible, but still active, then we want to block instead of muting the camera.
4482 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4483 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4484
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004485 bool isCameraPrivacyEnabled;
4486 if (flags::camera_privacy_allowlist()) {
4487 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4488 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4489 } else {
4490 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004491 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004492 }
4493
4494 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004495 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4496 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4497 isCameraPrivacyEnabled);
4498 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4499 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4500 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004501 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004502 if (flags::watch_foreground_changes()) {
4503 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4504 setCameraMute(true);
4505 } else {
4506 block();
4507 }
4508 } else {
4509 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4510 setCameraMute(true);
4511 } else if (!isUidActive
4512 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4513 block();
4514 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004515 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004516 }
Evan Severson09ab4002021-02-10 14:15:19 -08004517 } else if (res == AppOpsManager::MODE_ALLOWED) {
4518 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004519 }
4520}
4521
Svet Ganova453d0d2018-01-11 15:37:58 -08004522void CameraService::BasicClient::block() {
4523 ATRACE_CALL();
4524
4525 // Reset the client PID to allow server-initiated disconnect,
4526 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004527 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004528 CaptureResultExtras resultExtras; // a dummy result (invalid)
4529 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4530 disconnect();
4531}
4532
Mathias Agopian65ab4712010-07-14 17:59:35 -07004533// ----------------------------------------------------------------------------
4534
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004535void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004536 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004537 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004538 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4539 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4540 api1ErrorCode = CAMERA_ERROR_DISABLED;
4541 }
4542 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004543 } else {
4544 ALOGE("mRemoteCallback is NULL!!");
4545 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004546}
4547
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004548// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004549binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004550 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004551 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004552}
4553
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004554bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4555 return level == API_1;
4556}
4557
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004558CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4559 mClient(client) {
4560}
4561
4562void CameraService::Client::OpsCallback::opChanged(int32_t op,
4563 const String16& packageName) {
4564 sp<BasicClient> client = mClient.promote();
4565 if (client != NULL) {
4566 client->opChanged(op, packageName);
4567 }
4568}
4569
Mathias Agopian65ab4712010-07-14 17:59:35 -07004570// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004571// UidPolicy
4572// ----------------------------------------------------------------------------
4573
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004574void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004575 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004576 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004577
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004578 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004579 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004580 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004581 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004582 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4583 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004584 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004585 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004586 if (res == OK) {
4587 mRegistered = true;
4588 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004589 } else {
4590 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004591 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004592}
4593
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004594void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004595 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004596 return;
4597 }
4598
4599 registerWithActivityManager();
4600}
4601
4602void CameraService::UidPolicy::registerSelf() {
4603 // Use check service to see if the activity service is available
4604 // If not available then register for notifications, instead of blocking
4605 // till the service is ready
4606 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004607 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004608 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004609 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004610 } else {
4611 registerWithActivityManager();
4612 }
4613}
4614
Svet Ganova453d0d2018-01-11 15:37:58 -08004615void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004616 Mutex::Autolock _l(mUidLock);
4617
Steven Moreland2f348142019-07-02 15:59:07 -07004618 mAm.unregisterUidObserver(this);
4619 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004620 mRegistered = false;
4621 mActiveUids.clear();
4622 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004623}
4624
4625void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4626 onUidIdle(uid, disabled);
4627}
4628
4629void CameraService::UidPolicy::onUidActive(uid_t uid) {
4630 Mutex::Autolock _l(mUidLock);
4631 mActiveUids.insert(uid);
4632}
4633
4634void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4635 bool deleted = false;
4636 {
4637 Mutex::Autolock _l(mUidLock);
4638 if (mActiveUids.erase(uid) > 0) {
4639 deleted = true;
4640 }
4641 }
4642 if (deleted) {
4643 sp<CameraService> service = mService.promote();
4644 if (service != nullptr) {
4645 service->blockClientsForUid(uid);
4646 }
4647 }
4648}
4649
Emilian Peev53722fa2019-02-22 17:47:20 -08004650void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004651 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004652 bool procStateChange = false;
4653 {
4654 Mutex::Autolock _l(mUidLock);
4655 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4656 mMonitoredUids[uid].procState != procState) {
4657 mMonitoredUids[uid].procState = procState;
4658 procStateChange = true;
4659 }
4660 }
4661
4662 if (procStateChange) {
4663 sp<CameraService> service = mService.promote();
4664 if (service != nullptr) {
4665 service->notifyMonitoredUids();
4666 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004667 }
4668}
4669
Austin Borgerdddb7552023-03-30 17:53:01 -07004670/**
4671 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4672 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4673 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4674 * monitoredUids. If it is revised above some other monitoredUid, signal
4675 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4676 * foreground apps in split screen - state changes will capture all other cases.
4677 */
4678void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4679 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004680 {
4681 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004682 auto it = mMonitoredUids.find(uid);
4683
4684 if (it != mMonitoredUids.end()) {
4685 if (it->second.hasCamera) {
4686 for (auto &monitoredUid : mMonitoredUids) {
4687 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004688 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004689 notifyUidSet.emplace(monitoredUid.first);
4690 }
4691 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004692 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004693 notifyUidSet.emplace(uid);
4694 } else {
4695 for (auto &monitoredUid : mMonitoredUids) {
4696 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004697 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004698 notifyUidSet.emplace(uid);
4699 }
4700 }
4701 }
4702 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004703 }
4704 }
4705
Austin Borgerdddb7552023-03-30 17:53:01 -07004706 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004707 sp<CameraService> service = mService.promote();
4708 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004709 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004710 }
4711 }
4712}
4713
Austin Borgerdddb7552023-03-30 17:53:01 -07004714/**
4715 * Register a uid for monitoring, and note whether it owns a camera.
4716 */
4717void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004718 Mutex::Autolock _l(mUidLock);
4719 auto it = mMonitoredUids.find(uid);
4720 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004721 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004722 } else {
Austin Borger65577682022-02-17 00:25:43 +00004723 MonitoredUid monitoredUid;
4724 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004725 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004726 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004727 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004728 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004729 if (res != OK) {
4730 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4731 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004732 }
4733
4734 if (openCamera) {
4735 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004736 }
4737}
4738
Austin Borgerdddb7552023-03-30 17:53:01 -07004739/**
4740 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4741 */
4742void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004743 Mutex::Autolock _l(mUidLock);
4744 auto it = mMonitoredUids.find(uid);
4745 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004746 it->second.refCount--;
4747 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004748 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004749 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004750 if (res != OK) {
4751 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4752 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004753 } else if (closeCamera) {
4754 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004755 }
4756 } else {
4757 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4758 }
4759}
4760
Austin Borgered99f642023-06-01 16:51:35 -07004761bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004762 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004763 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004764}
4765
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004766static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4767static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004768
Austin Borgered99f642023-06-01 16:51:35 -07004769bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004770 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004771 // If activity manager is unreachable, assume everything is active
4772 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004773 return true;
4774 }
4775 auto it = mOverrideUids.find(uid);
4776 if (it != mOverrideUids.end()) {
4777 return it->second;
4778 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004779 bool active = mActiveUids.find(uid) != mActiveUids.end();
4780 if (!active) {
4781 // We want active UIDs to always access camera with their first attempt since
4782 // there is no guarantee the app is robustly written and would retry getting
4783 // the camera on failure. The inverse case is not a problem as we would take
4784 // camera away soon once we get the callback that the uid is no longer active.
4785 ActivityManager am;
4786 // Okay to access with a lock held as UID changes are dispatched without
4787 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004788 int64_t startTimeMillis = 0;
4789 do {
4790 // TODO: Fix this b/109950150!
4791 // Okay this is a hack. There is a race between the UID turning active and
4792 // activity being resumed. The proper fix is very risky, so we temporary add
4793 // some polling which should happen pretty rarely anyway as the race is hard
4794 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004795 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004796 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004797 if (active) {
4798 break;
4799 }
4800 if (startTimeMillis <= 0) {
4801 startTimeMillis = uptimeMillis();
4802 }
4803 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004804 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004805 if (remainingTimeMillis <= 0) {
4806 break;
4807 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004808 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4809
4810 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004811 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004812 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004813 } while (true);
4814
Svet Ganov7b4ab782018-03-25 12:48:10 -07004815 if (active) {
4816 // Now that we found out the UID is actually active, cache that
4817 mActiveUids.insert(uid);
4818 }
4819 }
4820 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004821}
4822
Varun Shahb42f1eb2019-04-16 14:45:13 -07004823int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4824 Mutex::Autolock _l(mUidLock);
4825 return getProcStateLocked(uid);
4826}
4827
4828int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4829 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4830 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004831 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004832 }
4833 return procState;
4834}
4835
Austin Borgered99f642023-06-01 16:51:35 -07004836void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4837 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004838 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004839}
4840
Austin Borgered99f642023-06-01 16:51:35 -07004841void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004842 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004843}
4844
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004845void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4846 Mutex::Autolock _l(mUidLock);
4847 ALOGV("UidPolicy: ActivityManager has died");
4848 mRegistered = false;
4849 mActiveUids.clear();
4850}
4851
Austin Borgered99f642023-06-01 16:51:35 -07004852void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004853 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004854 bool wasActive = false;
4855 bool isActive = false;
4856 {
4857 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004858 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004859 mOverrideUids.erase(uid);
4860 if (insert) {
4861 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4862 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004863 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004864 }
4865 if (wasActive != isActive && !isActive) {
4866 sp<CameraService> service = mService.promote();
4867 if (service != nullptr) {
4868 service->blockClientsForUid(uid);
4869 }
4870 }
4871}
4872
4873// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004874// SensorPrivacyPolicy
4875// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004876
4877void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4878{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004879 Mutex::Autolock _l(mSensorPrivacyLock);
4880 if (mRegistered) {
4881 return;
4882 }
Evan Severson09ab4002021-02-10 14:15:19 -08004883 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004884 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004885 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004886 mSpm.addToggleSensorPrivacyListener(this);
4887 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004888 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004889 if (flags::camera_privacy_allowlist()) {
4890 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4891 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4892 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4893 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004894 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004895 if (res == OK) {
4896 mRegistered = true;
4897 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4898 }
4899}
4900
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004901void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4902 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004903 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004904 return;
4905 }
4906
4907 registerWithSensorPrivacyManager();
4908}
4909
4910void CameraService::SensorPrivacyPolicy::registerSelf() {
4911 // Use checkservice to see if the sensor_privacy service is available
4912 // If service is not available then register for notification
4913 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004914 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004915 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004916 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004917 } else {
4918 registerWithSensorPrivacyManager();
4919 }
4920}
4921
Michael Grooverd1d435a2018-12-18 17:39:42 -08004922void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4923 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004924 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004925 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004926 mSpm.removeToggleSensorPrivacyListener(this);
4927 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004928 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004929 mRegistered = false;
4930 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4931}
4932
4933bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004934 if (!mRegistered) {
4935 registerWithSensorPrivacyManager();
4936 }
4937
Michael Grooverd1d435a2018-12-18 17:39:42 -08004938 Mutex::Autolock _l(mSensorPrivacyLock);
4939 return mSensorPrivacyEnabled;
4940}
4941
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004942int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4943 if (!mRegistered) {
4944 registerWithSensorPrivacyManager();
4945 }
4946
4947 Mutex::Autolock _l(mSensorPrivacyLock);
4948 return mCameraPrivacyState;
4949}
4950
Evan Seversond0b69922022-01-27 10:47:34 -08004951bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004952 if (!hasCameraPrivacyFeature()) {
4953 return false;
4954 }
Evan Seversond0b69922022-01-27 10:47:34 -08004955 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004956}
4957
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004958bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4959 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004960 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004961 }
4962 return mSpm.isCameraPrivacyEnabled(packageName);
4963}
4964
Evan Seversond0b69922022-01-27 10:47:34 -08004965binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004966 int toggleType, int sensor, bool enabled) {
4967 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4968 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4969 {
4970 Mutex::Autolock _l(mSensorPrivacyLock);
4971 mSensorPrivacyEnabled = enabled;
4972 }
4973 // if sensor privacy is enabled then block all clients from accessing the camera
4974 if (enabled) {
4975 sp<CameraService> service = mService.promote();
4976 if (service != nullptr) {
4977 service->blockAllClients();
4978 }
4979 }
4980 }
4981 return binder::Status::ok();
4982}
4983
4984binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
4985 int, int sensor, int state) {
4986 if (!flags::camera_privacy_allowlist()
4987 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
4988 return binder::Status::ok();
4989 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08004990 {
4991 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004992 mCameraPrivacyState = state;
4993 }
4994 sp<CameraService> service = mService.promote();
4995 if (!service) {
4996 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08004997 }
4998 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004999 if (state == SensorPrivacyManager::ENABLED) {
5000 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005001 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005002 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005003 }
5004 return binder::Status::ok();
5005}
5006
5007void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5008 Mutex::Autolock _l(mSensorPrivacyLock);
5009 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5010 mRegistered = false;
5011}
5012
Evan Severson09ab4002021-02-10 14:15:19 -08005013bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005014 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5015 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5016 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5017 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5018 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005019}
5020
Michael Grooverd1d435a2018-12-18 17:39:42 -08005021// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005022// CameraState
5023// ----------------------------------------------------------------------------
5024
Austin Borgered99f642023-06-01 16:51:35 -07005025CameraService::CameraState::CameraState(const std::string& id, int cost,
5026 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005027 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005028 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005029 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005030
5031CameraService::CameraState::~CameraState() {}
5032
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005033CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005034 Mutex::Autolock lock(mStatusLock);
5035 return mStatus;
5036}
5037
Austin Borgered99f642023-06-01 16:51:35 -07005038std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005039 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005040 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005041 return res;
5042}
5043
Ruben Brunkcc776712015-02-17 20:18:47 -08005044CameraParameters CameraService::CameraState::getShimParams() const {
5045 return mShimParams;
5046}
5047
5048void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5049 mShimParams = params;
5050}
5051
5052int CameraService::CameraState::getCost() const {
5053 return mCost;
5054}
5055
Austin Borgered99f642023-06-01 16:51:35 -07005056std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005057 return mConflicting;
5058}
5059
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005060SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5061 return mSystemCameraKind;
5062}
5063
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005064bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5065 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5066 != mPhysicalCameras.end();
5067}
5068
Austin Borgered99f642023-06-01 16:51:35 -07005069bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005070 Mutex::Autolock lock(mStatusLock);
5071 auto result = mUnavailablePhysicalIds.insert(physicalId);
5072 return result.second;
5073}
5074
Austin Borgered99f642023-06-01 16:51:35 -07005075bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005076 Mutex::Autolock lock(mStatusLock);
5077 auto count = mUnavailablePhysicalIds.erase(physicalId);
5078 return count > 0;
5079}
5080
Austin Borgered99f642023-06-01 16:51:35 -07005081void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005082 Mutex::Autolock lock(mStatusLock);
5083 mClientPackage = clientPackage;
5084}
5085
Austin Borgered99f642023-06-01 16:51:35 -07005086std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005087 Mutex::Autolock lock(mStatusLock);
5088 return mClientPackage;
5089}
5090
Ruben Brunkcc776712015-02-17 20:18:47 -08005091// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005092// ClientEventListener
5093// ----------------------------------------------------------------------------
5094
5095void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005096 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005097 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005098 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005099 if (basicClient.get() != nullptr) {
5100 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005101 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005102 static_cast<int>(basicClient->getClientUid()));
5103 }
5104}
5105
5106void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005107 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005108 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005109 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005110 if (basicClient.get() != nullptr) {
5111 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005112 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005113 static_cast<int>(basicClient->getClientUid()));
5114 }
5115}
5116
Ruben Brunk99e69712015-05-26 17:25:07 -07005117// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005118// CameraClientManager
5119// ----------------------------------------------------------------------------
5120
Ruben Brunk99e69712015-05-26 17:25:07 -07005121CameraService::CameraClientManager::CameraClientManager() {
5122 setListener(std::make_shared<ClientEventListener>());
5123}
5124
Ruben Brunkcc776712015-02-17 20:18:47 -08005125CameraService::CameraClientManager::~CameraClientManager() {}
5126
5127sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005128 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005129 auto descriptor = get(id);
5130 if (descriptor == nullptr) {
5131 return sp<BasicClient>{nullptr};
5132 }
5133 return descriptor->getValue();
5134}
5135
Austin Borgered99f642023-06-01 16:51:35 -07005136std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005137 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005138 std::ostringstream ret;
5139 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005140 bool hasAny = false;
5141 for (auto& i : all) {
5142 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005143 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005144 int32_t cost = i->getCost();
5145 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005146 int32_t score = i->getPriority().getScore();
5147 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005148 auto conflicting = i->getConflicting();
5149 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005150 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005151 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005152 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005153 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005154 uid_t clientUid = clientSp->getClientUid();
5155 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005156 }
Austin Borgered99f642023-06-01 16:51:35 -07005157 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5158 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005159
Ruben Brunk6267b532015-04-30 17:44:07 -07005160 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005161 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005162 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005163 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005164 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005165 }
5166
Austin Borgered99f642023-06-01 16:51:35 -07005167 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005168 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005169 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005170 }
Austin Borgered99f642023-06-01 16:51:35 -07005171 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005172 }
Austin Borgered99f642023-06-01 16:51:35 -07005173 if (hasAny) ret << "\n";
5174 ret << "]\n";
5175 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005176}
5177
5178CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005179 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5180 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005181 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005182
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005183 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005184 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005185
Austin Borgered99f642023-06-01 16:51:35 -07005186 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005187 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5188 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005189}
5190
5191CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005192 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005193 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005194 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005195 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005196 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5197 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005198}
5199
5200// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005201// InjectionStatusListener
5202// ----------------------------------------------------------------------------
5203
5204void CameraService::InjectionStatusListener::addListener(
5205 const sp<ICameraInjectionCallback>& callback) {
5206 Mutex::Autolock lock(mListenerLock);
5207 if (mCameraInjectionCallback) return;
5208 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5209 if (res == OK) {
5210 mCameraInjectionCallback = callback;
5211 }
5212}
5213
5214void CameraService::InjectionStatusListener::removeListener() {
5215 Mutex::Autolock lock(mListenerLock);
5216 if (mCameraInjectionCallback == nullptr) {
5217 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5218 return;
5219 }
5220 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5221 mCameraInjectionCallback = nullptr;
5222}
5223
5224void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005225 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005226 if (mCameraInjectionCallback == nullptr) {
5227 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5228 return;
5229 }
Cliff Wud3a05312021-04-26 23:07:31 +08005230
5231 switch (err) {
5232 case -ENODEV:
5233 mCameraInjectionCallback->onInjectionError(
5234 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5235 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005236 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005237 break;
5238 case -EBUSY:
5239 mCameraInjectionCallback->onInjectionError(
5240 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5241 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005242 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005243 break;
5244 case DEAD_OBJECT:
5245 mCameraInjectionCallback->onInjectionError(
5246 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5247 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005248 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005249 break;
5250 case INVALID_OPERATION:
5251 mCameraInjectionCallback->onInjectionError(
5252 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5253 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005254 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005255 break;
5256 case UNKNOWN_TRANSACTION:
5257 mCameraInjectionCallback->onInjectionError(
5258 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5259 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005260 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005261 break;
5262 default:
5263 mCameraInjectionCallback->onInjectionError(
5264 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5265 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005266 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005267 }
Cliff Wud8cae102021-03-11 01:37:42 +08005268}
5269
5270void CameraService::InjectionStatusListener::binderDied(
5271 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005272 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5273 auto parent = mParent.promote();
5274 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005275 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5276 if (clientDescriptor != nullptr) {
5277 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5278 baseClientPtr->stopInjection();
5279 }
Cliff Wu3b268182021-07-06 15:44:43 +08005280 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005281 }
5282}
5283
5284// ----------------------------------------------------------------------------
5285// CameraInjectionSession
5286// ----------------------------------------------------------------------------
5287
5288binder::Status CameraService::CameraInjectionSession::stopInjection() {
5289 Mutex::Autolock lock(mInjectionSessionLock);
5290 auto parent = mParent.promote();
5291 if (parent == nullptr) {
5292 ALOGE("CameraInjectionSession: Parent is gone");
5293 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5294 "Camera service encountered error");
5295 }
Cliff Wud3a05312021-04-26 23:07:31 +08005296
5297 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005298 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5299 if (clientDescriptor != nullptr) {
5300 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5301 res = baseClientPtr->stopInjection();
5302 if (res != OK) {
5303 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5304 " ret != NO_ERROR: %d", res);
5305 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5306 "Camera session encountered error");
5307 }
5308 }
Cliff Wu3b268182021-07-06 15:44:43 +08005309 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005310 return binder::Status::ok();
5311}
5312
5313// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005314
5315static const int kDumpLockRetries = 50;
5316static const int kDumpLockSleep = 60000;
5317
5318static bool tryLock(Mutex& mutex)
5319{
5320 bool locked = false;
5321 for (int i = 0; i < kDumpLockRetries; ++i) {
5322 if (mutex.tryLock() == NO_ERROR) {
5323 locked = true;
5324 break;
5325 }
5326 usleep(kDumpLockSleep);
5327 }
5328 return locked;
5329}
5330
Rucha Katakwardf223072021-06-15 10:21:00 -07005331void CameraService::cacheDump() {
5332 if (mMemFd != -1) {
5333 const Vector<String16> args;
5334 ATRACE_CALL();
5335 // Acquiring service lock here will avoid the deadlock since
5336 // cacheDump will not be called during the second disconnect.
5337 Mutex::Autolock lock(mServiceLock);
5338
5339 Mutex::Autolock l(mCameraStatesLock);
5340 // Start collecting the info for open sessions and store it in temp file.
5341 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005342 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005343 auto clientDescriptor = mActiveClientManager.get(cameraId);
5344 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005345 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005346 // Log the current open session info before device is disconnected.
5347 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5348 }
5349 }
5350 }
5351}
5352
Mathias Agopian65ab4712010-07-14 17:59:35 -07005353status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005354 ATRACE_CALL();
5355
Austin Borgered99f642023-06-01 16:51:35 -07005356 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005357 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005358 getCallingPid(),
5359 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005360 return NO_ERROR;
5361 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005362 bool locked = tryLock(mServiceLock);
5363 // failed to lock - CameraService is probably deadlocked
5364 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005365 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005366 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005367
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005368 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005369 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005370
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005371 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005372 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005373
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005374 if (locked) mServiceLock.unlock();
5375 return NO_ERROR;
5376 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005377 dprintf(fd, "\n== Service global info: ==\n\n");
5378 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005379 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005380 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5381 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005382 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5383 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5384 }
Austin Borgered99f642023-06-01 16:51:35 -07005385 std::string activeClientString = mActiveClientManager.toString();
5386 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5387 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005388 if (mStreamUseCaseOverrides.size() > 0) {
5389 dprintf(fd, "Active stream use case overrides:");
5390 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5391 dprintf(fd, " %" PRId64, useCaseOverride);
5392 }
5393 dprintf(fd, "\n");
5394 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005395
5396 dumpEventLog(fd);
5397
5398 bool stateLocked = tryLock(mCameraStatesLock);
5399 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005400 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005401 }
5402
Emilian Peevbd8c5032018-02-14 23:05:40 +00005403 int argSize = args.size();
5404 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005405 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005406 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005407 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005408 }
5409 break;
5410 }
5411 }
5412
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005413 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005414 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005415
Austin Borgered99f642023-06-01 16:51:35 -07005416 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005417
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005418 CameraParameters p = state.second->getShimParams();
5419 if (!p.isEmpty()) {
5420 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5421 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005422 }
5423
5424 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005425 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005426 // log the current open session info
5427 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005428 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005429 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005430 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005431
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005432 }
5433
5434 if (stateLocked) mCameraStatesLock.unlock();
5435
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005436 if (locked) mServiceLock.unlock();
5437
Emilian Peevf53f66e2017-04-11 14:29:43 +01005438 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005439
5440 dprintf(fd, "\n== Vendor tags: ==\n\n");
5441
5442 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5443 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005444 sp<VendorTagDescriptorCache> cache =
5445 VendorTagDescriptorCache::getGlobalVendorTagCache();
5446 if (cache == NULL) {
5447 dprintf(fd, "No vendor tags.\n");
5448 } else {
5449 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5450 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005451 } else {
5452 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5453 }
5454
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005455 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005456 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005457 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005458
5459 // Process dump arguments, if any
5460 int n = args.size();
5461 String16 verboseOption("-v");
5462 String16 unreachableOption("--unreachable");
5463 for (int i = 0; i < n; i++) {
5464 if (args[i] == verboseOption) {
5465 // change logging level
5466 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005467 std::string levelStr = toStdString(args[i+1]);
5468 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005469 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005470 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005471 } else if (args[i] == unreachableOption) {
5472 // Dump memory analysis
5473 // TODO - should limit be an argument parameter?
5474 UnreachableMemoryInfo info;
5475 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5476 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005477 dprintf(fd, "\n== Unable to dump unreachable memory. "
5478 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005479 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005480 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005481 std::string s = info.ToString(/*log_contents*/ true);
5482 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005483 }
5484 }
5485 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005486
5487 bool serviceLocked = tryLock(mServiceLock);
5488
5489 // Dump info from previous open sessions.
5490 // Reposition the offset to beginning of the file before reading
5491
5492 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5493 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5494 ssize_t size_read;
5495 char buf[4096];
5496 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5497 // Read data from file to a small buffer and write it to fd.
5498 write(fd, buf, size_read);
5499 if (size_read == -1) {
5500 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5501 break;
5502 }
5503 }
5504 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5505 } else {
5506 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5507 }
5508
5509 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005510 return NO_ERROR;
5511}
5512
Rucha Katakwardf223072021-06-15 10:21:00 -07005513void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005514 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005515 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005516 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005517 getFormattedCurrentTime().c_str(),
5518 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005519 dprintf(fd, " Client priority score: %d state: %d\n",
5520 clientDescriptor->getPriority().getScore(),
5521 clientDescriptor->getPriority().getState());
5522 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5523
5524 auto client = clientDescriptor->getValue();
5525 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005526 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005527
5528 client->dumpClient(fd, args);
5529}
5530
Austin Borgered99f642023-06-01 16:51:35 -07005531void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005532 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005533 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005534}
5535
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005536void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005537 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005538
5539 Mutex::Autolock l(mLogLock);
5540 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005541 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005542 }
5543
5544 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005545 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005546 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005547 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005548 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005549 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005550}
5551
Austin Borgered99f642023-06-01 16:51:35 -07005552void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005553 Mutex::Autolock lock(mLogLock);
5554 if (!isClientWatchedLocked(client)) { return; }
5555
5556 std::vector<std::string> dumpVector;
5557 client->dumpWatchedEventsToVector(dumpVector);
5558
5559 if (dumpVector.empty()) { return; }
5560
Austin Borgered99f642023-06-01 16:51:35 -07005561 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005562
Austin Borgered99f642023-06-01 16:51:35 -07005563 std::string currentTime = getFormattedCurrentTime();
5564 dumpString << "Cached @ ";
5565 dumpString << currentTime;
5566 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005567
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005568 size_t i = dumpVector.size();
5569
5570 // Store the string in reverse order (latest last)
5571 while (i > 0) {
5572 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005573 dumpString << cameraId;
5574 dumpString << ":";
5575 dumpString << client->getPackageName();
5576 dumpString << " ";
5577 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005578 }
5579
Austin Borgered99f642023-06-01 16:51:35 -07005580 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005581}
5582
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005583void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005584 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005585 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5586 if (mTorchClientMap[i] == who) {
5587 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005588 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005589 status_t res = mFlashlight->setTorchMode(cameraId, false);
5590 if (res) {
5591 ALOGE("%s: torch client died but couldn't turn off torch: "
5592 "%s (%d)", __FUNCTION__, strerror(-res), res);
5593 return;
5594 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005595 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005596 break;
5597 }
5598 }
5599}
5600
Ruben Brunkcc776712015-02-17 20:18:47 -08005601/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005602
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005603 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005604 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5605 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005606 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005607 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005608 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005609
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005610 // check torch client
5611 handleTorchClientBinderDied(who);
5612
5613 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005614 if(!evictClientIdByRemote(who)) {
5615 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005616 return;
5617 }
5618
Ruben Brunkcc776712015-02-17 20:18:47 -08005619 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5620 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005621}
5622
Austin Borgered99f642023-06-01 16:51:35 -07005623void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005624 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005625}
5626
Austin Borgered99f642023-06-01 16:51:35 -07005627void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005628 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005629 // Do not lock mServiceLock here or can get into a deadlock from
5630 // connect() -> disconnect -> updateStatus
5631
5632 auto state = getCameraState(cameraId);
5633
5634 if (state == nullptr) {
5635 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005636 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005637 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005638 }
5639
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005640 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5641 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5642 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005643 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005644 return;
5645 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005646
Biswarup Pal37a75182024-01-16 15:53:35 +00005647 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5648 CameraMetadata cameraInfo;
5649 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005650 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005651 if (res != OK) {
5652 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5653 __FUNCTION__, cameraId.c_str());
5654 } else {
5655 int32_t deviceId = getDeviceId(cameraInfo);
5656 if (deviceId != kDefaultDeviceId) {
5657 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5658 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5659 static_cast<camera_metadata_enum_android_lens_facing_t>(
5660 lensFacingEntry.data.u8[0]);
5661 std::string mappedCameraId;
5662 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5663 mappedCameraId = kVirtualDeviceBackCameraId;
5664 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5665 mappedCameraId = kVirtualDeviceFrontCameraId;
5666 } else {
5667 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5668 __func__);
5669 }
5670 if (!mappedCameraId.empty()) {
5671 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5672 }
5673 }
5674 }
5675 }
5676
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005677 // Collect the logical cameras without holding mStatusLock in updateStatus
5678 // as that can lead to a deadlock(b/162192331).
5679 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005680 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005681 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005682 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005683 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005684 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005685 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5686 auto [deviceId, mappedCameraId] =
5687 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005688
Biswarup Pal37a75182024-01-16 15:53:35 +00005689 if (status != StatusInternal::ENUMERATING) {
5690 // Update torch status if it has a flash unit.
5691 Mutex::Autolock al(mTorchStatusMutex);
5692 TorchModeStatus torchStatus;
5693 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5694 NAME_NOT_FOUND) {
5695 TorchModeStatus newTorchStatus =
5696 status == StatusInternal::PRESENT ?
5697 TorchModeStatus::AVAILABLE_OFF :
5698 TorchModeStatus::NOT_AVAILABLE;
5699 if (torchStatus != newTorchStatus) {
5700 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5701 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005702 }
5703 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005704
Biswarup Pal37a75182024-01-16 15:53:35 +00005705 Mutex::Autolock lock(mStatusListenerLock);
5706 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5707 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005708
Biswarup Pal37a75182024-01-16 15:53:35 +00005709 for (auto& listener : mListenerList) {
5710 bool isVendorListener = listener->isVendorListener();
5711 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5712 listener->getListenerPid(), listener->getListenerUid())) {
5713 ALOGV("Skipping discovery callback for system-only camera device %s",
5714 cameraId.c_str());
5715 continue;
5716 }
5717
5718 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5719 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005720 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005721 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005722 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5723 ret.exceptionCode());
5724 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005725 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005726}
5727
Austin Borgered99f642023-06-01 16:51:35 -07005728void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5729 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005730 auto state = getCameraState(cameraId);
5731 if (state == nullptr) {
5732 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005733 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005734 return;
5735 }
5736 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005737 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005738 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005739 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005740 }
5741
Biswarup Pal37a75182024-01-16 15:53:35 +00005742 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5743 auto [deviceId, mappedCameraId] =
5744 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5745
Shuzhen Wang695044d2020-03-06 09:02:23 -08005746 Mutex::Autolock lock(mStatusListenerLock);
5747
5748 for (const auto& it : mListenerList) {
5749 if (!it->isOpenCloseCallbackAllowed()) {
5750 continue;
5751 }
5752
5753 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005754 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005755 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5756 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005757 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005758 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005759 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005760
5761 it->handleBinderStatus(ret,
5762 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5763 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005764 }
5765}
5766
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005767template<class Func>
5768void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005769 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005770 std::initializer_list<StatusInternal> rejectSourceStates,
5771 Func onStatusUpdatedLocked) {
5772 Mutex::Autolock lock(mStatusLock);
5773 StatusInternal oldStatus = mStatus;
5774 mStatus = status;
5775
5776 if (oldStatus == status) {
5777 return;
5778 }
5779
5780 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005781 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005782
5783 if (oldStatus == StatusInternal::NOT_PRESENT &&
5784 (status != StatusInternal::PRESENT &&
5785 status != StatusInternal::ENUMERATING)) {
5786
5787 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5788 __FUNCTION__);
5789 mStatus = oldStatus;
5790 return;
5791 }
5792
5793 /**
5794 * Sometimes we want to conditionally do a transition.
5795 * For example if a client disconnects, we want to go to PRESENT
5796 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5797 */
5798 for (auto& rejectStatus : rejectSourceStates) {
5799 if (oldStatus == rejectStatus) {
5800 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005801 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005802 mStatus = oldStatus;
5803 return;
5804 }
5805 }
5806
5807 onStatusUpdatedLocked(cameraId, status);
5808}
5809
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005810status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005811 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005812 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005813 if (!status) {
5814 return BAD_VALUE;
5815 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005816 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5817 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005818 // invalid camera ID or the camera doesn't have a flash unit
5819 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005820 }
5821
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005822 *status = mTorchStatusMap.valueAt(index);
5823 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005824}
5825
Austin Borgered99f642023-06-01 16:51:35 -07005826status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005827 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005828 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5829 if (index == NAME_NOT_FOUND) {
5830 return BAD_VALUE;
5831 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005832 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005833
5834 return OK;
5835}
5836
Austin Borgered99f642023-06-01 16:51:35 -07005837std::list<std::string> CameraService::getLogicalCameras(
5838 const std::string& physicalCameraId) {
5839 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005840 Mutex::Autolock lock(mCameraStatesLock);
5841 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005842 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5843 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005844 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005845 }
5846 return retList;
5847}
5848
5849void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005850 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005851 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005852 // mStatusListenerLock is expected to be locked
5853 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005854 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005855 // Note: we check only the deviceKind of the physical camera id
5856 // since, logical camera ids and their physical camera ids are
5857 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005858 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5859 listener->getListenerPid(), listener->getListenerUid())) {
5860 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005861 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005862 continue;
5863 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005864 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005865 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005866 listener->handleBinderStatus(ret,
5867 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5868 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5869 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005870 }
5871 }
5872}
5873
Svet Ganova453d0d2018-01-11 15:37:58 -08005874void CameraService::blockClientsForUid(uid_t uid) {
5875 const auto clients = mActiveClientManager.getAll();
5876 for (auto& current : clients) {
5877 if (current != nullptr) {
5878 const auto basicClient = current->getValue();
5879 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5880 basicClient->block();
5881 }
5882 }
5883 }
5884}
5885
Michael Grooverd1d435a2018-12-18 17:39:42 -08005886void CameraService::blockAllClients() {
5887 const auto clients = mActiveClientManager.getAll();
5888 for (auto& current : clients) {
5889 if (current != nullptr) {
5890 const auto basicClient = current->getValue();
5891 if (basicClient.get() != nullptr) {
5892 basicClient->block();
5893 }
5894 }
5895 }
5896}
5897
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005898void CameraService::blockPrivacyEnabledClients() {
5899 const auto clients = mActiveClientManager.getAll();
5900 for (auto& current : clients) {
5901 if (current != nullptr) {
5902 const auto basicClient = current->getValue();
5903 if (basicClient.get() != nullptr) {
5904 std::string pkgName = basicClient->getPackageName();
5905 bool cameraPrivacyEnabled =
5906 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5907 if (cameraPrivacyEnabled) {
5908 basicClient->block();
5909 }
5910 }
5911 }
5912 }
5913}
5914
Svet Ganova453d0d2018-01-11 15:37:58 -08005915// NOTE: This is a remote API - make sure all args are validated
5916status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005917 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005918 return PERMISSION_DENIED;
5919 }
5920 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5921 return BAD_VALUE;
5922 }
Austin Borgered99f642023-06-01 16:51:35 -07005923 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005924 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005925 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005926 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005927 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005928 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005929 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005930 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005931 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005932 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005933 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005934 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005935 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005936 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005937 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005938 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005939 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005940 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005941 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005942 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005943 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005944 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005945 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005946 handleClearStreamUseCaseOverrides();
5947 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005948 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005949 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005950 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005951 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005952 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005953 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005954 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005955 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005956 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005957 }
5958 printHelp(err);
5959 return BAD_VALUE;
5960}
5961
5962status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005963 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005964
Svet Ganova453d0d2018-01-11 15:37:58 -08005965 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005966 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005967 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005968 } else if ((args[2] != toString16("idle"))) {
5969 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005970 return BAD_VALUE;
5971 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005972
5973 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005974 if (args.size() >= 5 && args[3] == toString16("--user")) {
5975 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005976 }
5977
5978 uid_t uid;
5979 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
5980 return BAD_VALUE;
5981 }
5982
5983 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08005984 return NO_ERROR;
5985}
5986
5987status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07005988 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07005989
5990 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005991 if (args.size() >= 4 && args[2] == toString16("--user")) {
5992 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07005993 }
5994
5995 uid_t uid;
5996 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005997 return BAD_VALUE;
5998 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005999
6000 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006001 return NO_ERROR;
6002}
6003
6004status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006005 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006006
6007 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006008 if (args.size() >= 4 && args[2] == toString16("--user")) {
6009 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006010 }
6011
6012 uid_t uid;
6013 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006014 return BAD_VALUE;
6015 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006016
6017 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006018 return dprintf(out, "active\n");
6019 } else {
6020 return dprintf(out, "idle\n");
6021 }
6022}
6023
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006024status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006025 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006026 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6027 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6028 Mutex::Autolock lock(mServiceLock);
6029
6030 mOverrideRotateAndCropMode = rotateValue;
6031
6032 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6033
6034 const auto clients = mActiveClientManager.getAll();
6035 for (auto& current : clients) {
6036 if (current != nullptr) {
6037 const auto basicClient = current->getValue();
6038 if (basicClient.get() != nullptr) {
6039 basicClient->setRotateAndCropOverride(rotateValue);
6040 }
6041 }
6042 }
6043
6044 return OK;
6045}
6046
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006047status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6048 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006049 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006050 if ((*end != '\0') ||
6051 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6052 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6053 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6054 return BAD_VALUE;
6055 }
6056
6057 Mutex::Autolock lock(mServiceLock);
6058 mOverrideAutoframingMode = autoframingValue;
6059
6060 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6061
6062 const auto clients = mActiveClientManager.getAll();
6063 for (auto& current : clients) {
6064 if (current != nullptr) {
6065 const auto basicClient = current->getValue();
6066 if (basicClient.get() != nullptr) {
6067 basicClient->setAutoframingOverride(autoframingValue);
6068 }
6069 }
6070 }
6071
6072 return OK;
6073}
6074
Ravneetaeb20dc2022-03-30 05:33:03 +00006075status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006076 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006077
6078 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6079
6080 Mutex::Autolock lock(mServiceLock);
6081
6082 mCameraServiceWatchdogEnabled = enableWatchdog;
6083
6084 const auto clients = mActiveClientManager.getAll();
6085 for (auto& current : clients) {
6086 if (current != nullptr) {
6087 const auto basicClient = current->getValue();
6088 if (basicClient.get() != nullptr) {
6089 basicClient->setCameraServiceWatchdog(enableWatchdog);
6090 }
6091 }
6092 }
6093
6094 return OK;
6095}
6096
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006097status_t CameraService::handleGetRotateAndCrop(int out) {
6098 Mutex::Autolock lock(mServiceLock);
6099
6100 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6101}
6102
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006103status_t CameraService::handleGetAutoframing(int out) {
6104 Mutex::Autolock lock(mServiceLock);
6105
6106 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6107}
6108
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006109status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6110 char *endPtr;
6111 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006112 std::string maskString = toStdString(args[1]);
6113 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006114
6115 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006116 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006117 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6118
6119 Mutex::Autolock lock(mServiceLock);
6120
6121 mImageDumpMask = maskValue;
6122
6123 return OK;
6124}
6125
6126status_t CameraService::handleGetImageDumpMask(int out) {
6127 Mutex::Autolock lock(mServiceLock);
6128
6129 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6130}
6131
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006132status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006133 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006134 if (errno != 0) return BAD_VALUE;
6135
6136 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6137 Mutex::Autolock lock(mServiceLock);
6138
6139 mOverrideCameraMuteMode = (muteValue == 1);
6140
6141 const auto clients = mActiveClientManager.getAll();
6142 for (auto& current : clients) {
6143 if (current != nullptr) {
6144 const auto basicClient = current->getValue();
6145 if (basicClient.get() != nullptr) {
6146 if (basicClient->supportsCameraMute()) {
6147 basicClient->setCameraMute(mOverrideCameraMuteMode);
6148 }
6149 }
6150 }
6151 }
6152
6153 return OK;
6154}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006155
Shuzhen Wang16610a62022-12-15 22:38:07 -08006156status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6157 std::vector<int64_t> useCasesOverride;
6158 for (size_t i = 1; i < args.size(); i++) {
6159 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006160 std::string arg = toStdString(args[i]);
6161 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006162 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006163 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006164 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006165 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006166 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006167 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006168 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006169 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006170 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006171 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006172 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006173 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006174 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6175 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006176 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006177 return BAD_VALUE;
6178 }
6179 useCasesOverride.push_back(useCase);
6180 }
6181
6182 Mutex::Autolock lock(mServiceLock);
6183 mStreamUseCaseOverrides = std::move(useCasesOverride);
6184
6185 return OK;
6186}
6187
6188void CameraService::handleClearStreamUseCaseOverrides() {
6189 Mutex::Autolock lock(mServiceLock);
6190 mStreamUseCaseOverrides.clear();
6191}
6192
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006193status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6194 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006195 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006196 if ((*end != '\0') ||
6197 (zoomOverrideValue != -1 &&
6198 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6199 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6200 return BAD_VALUE;
6201 }
6202
6203 Mutex::Autolock lock(mServiceLock);
6204 mZoomOverrideValue = zoomOverrideValue;
6205
6206 const auto clients = mActiveClientManager.getAll();
6207 for (auto& current : clients) {
6208 if (current != nullptr) {
6209 const auto basicClient = current->getValue();
6210 if (basicClient.get() != nullptr) {
6211 if (basicClient->supportsZoomOverride()) {
6212 basicClient->setZoomOverride(mZoomOverrideValue);
6213 }
6214 }
6215 }
6216 }
6217
6218 return OK;
6219}
6220
Avichal Rakesh84147132021-11-11 17:47:11 -08006221status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006222 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006223 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006224 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006225 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006226 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006227 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006228 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006229 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006230 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006231 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006232 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006233 dprintf(outFd, "Camera service watch commands:\n"
6234 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6235 " starts watching the provided tags for clients with provided package\n"
6236 " recognizes tag shorthands like '3a'\n"
6237 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006238 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006239 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006240 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006241 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006242 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006243 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006244 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006245}
6246
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006247status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6248 Mutex::Autolock lock(mLogLock);
6249 size_t tagsIdx; // index of '-m'
6250 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006251 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006252 if (tagsIdx < args.size() - 1) {
6253 tags = args[tagsIdx + 1];
6254 } else {
6255 dprintf(outFd, "No tags provided.\n");
6256 return BAD_VALUE;
6257 }
6258
6259 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006260 // watch all clients if no clients are provided
6261 String16 clients = toString16(kWatchAllClientsFlag);
6262 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006263 clientsIdx++);
6264 if (clientsIdx < args.size() - 1) {
6265 clients = args[clientsIdx + 1];
6266 }
Austin Borgered99f642023-06-01 16:51:35 -07006267 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006268
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006269 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006270 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006271
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006272 bool serviceLock = tryLock(mServiceLock);
6273 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006274 auto cameraClients = mActiveClientManager.getAll();
6275 for (const auto &clientDescriptor: cameraClients) {
6276 if (clientDescriptor == nullptr) { continue; }
6277 sp<BasicClient> client = clientDescriptor->getValue();
6278 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006279
6280 if (isClientWatchedLocked(client.get())) {
6281 client->startWatchingTags(mMonitorTags, outFd);
6282 numWatchedClients++;
6283 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006284 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006285 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6286
6287 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006288 return OK;
6289}
6290
6291status_t CameraService::stopWatchingTags(int outFd) {
6292 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006293 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006294 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006295
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006296 mWatchedClientPackages.clear();
6297 mWatchedClientsDumpCache.clear();
6298
6299 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006300 auto cameraClients = mActiveClientManager.getAll();
6301 for (const auto &clientDescriptor : cameraClients) {
6302 if (clientDescriptor == nullptr) { continue; }
6303 sp<BasicClient> client = clientDescriptor->getValue();
6304 if (client.get() == nullptr) { continue; }
6305 client->stopWatchingTags(outFd);
6306 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006307 dprintf(outFd, "Stopped watching all clients.\n");
6308 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006309 return OK;
6310}
6311
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006312status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6313 Mutex::Autolock lock(mLogLock);
6314 size_t clearedSize = mWatchedClientsDumpCache.size();
6315 mWatchedClientsDumpCache.clear();
6316 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6317 return OK;
6318}
6319
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006320status_t CameraService::printWatchedTags(int outFd) {
6321 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006322 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006323
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006324 bool printedSomething = false; // tracks if any monitoring information was printed
6325 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006326
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006327 bool serviceLock = tryLock(mServiceLock);
6328 // get all watched clients that are currently connected
6329 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6330 if (clientDescriptor == nullptr) { continue; }
6331
6332 sp<BasicClient> client = clientDescriptor->getValue();
6333 if (client.get() == nullptr) { continue; }
6334 if (!isClientWatchedLocked(client.get())) { continue; }
6335
6336 std::vector<std::string> dumpVector;
6337 client->dumpWatchedEventsToVector(dumpVector);
6338
6339 size_t printIdx = dumpVector.size();
6340 if (printIdx == 0) {
6341 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006342 }
6343
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006344 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006345 const std::string &cameraId = clientDescriptor->getKey();
6346 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006347 while(printIdx > 0) {
6348 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006349 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006350 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006351 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006352 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006353 printedSomething = true;
6354
6355 connectedMonitoredClients.emplace(client->getPackageName());
6356 }
6357 if (serviceLock) { mServiceLock.unlock(); }
6358
6359 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6360 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006361 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006362 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6363 continue;
6364 }
6365
Austin Borgered99f642023-06-01 16:51:35 -07006366 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006367 dprintf(outFd, "%s\n", kv.second.c_str());
6368 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006369 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006370
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006371 if (!printedSomething) {
6372 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006373 }
6374
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006375 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006376}
6377
Avichal Rakesh84147132021-11-11 17:47:11 -08006378// Print all events in vector `events' that came after lastPrintedEvent
6379void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006380 const std::string &cameraId,
6381 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006382 const std::vector<std::string> &events,
6383 const std::string &lastPrintedEvent) {
6384 if (events.empty()) { return; }
6385
6386 // index of lastPrintedEvent in events.
6387 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6388 size_t lastPrintedIdx;
6389 for (lastPrintedIdx = 0;
6390 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6391 lastPrintedIdx++);
6392
6393 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6394
Avichal Rakesh84147132021-11-11 17:47:11 -08006395 // print events in chronological order (latest event last)
6396 size_t idxToPrint = lastPrintedIdx;
6397 do {
6398 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006399 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6400 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006401 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006402}
6403
6404// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6405// command should be interrupted if the user presses the return key, or if user loses any way to
6406// signal interrupt.
6407// If timeoutMs == 0, this function will always return false
6408bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6409 struct timeval startTime;
6410 int startTimeError = gettimeofday(&startTime, nullptr);
6411 if (startTimeError) {
6412 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6413 return true;
6414 }
6415
6416 const nfds_t numFds = 1;
6417 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6418
6419 struct timeval currTime;
6420 char buffer[2];
6421 while(true) {
6422 int currTimeError = gettimeofday(&currTime, nullptr);
6423 if (currTimeError) {
6424 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6425 return true;
6426 }
6427
6428 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6429 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6430 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6431
6432 if (remainingTimeMs <= 0) {
6433 // No user interrupt within timeoutMs, don't interrupt watch command
6434 return false;
6435 }
6436
6437 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6438 if (numFdsUpdated < 0) {
6439 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6440 return true;
6441 }
6442
6443 if (numFdsUpdated == 0) {
6444 // No user input within timeoutMs, don't interrupt watch command
6445 return false;
6446 }
6447
6448 if (!(pollFd.revents & POLLIN)) {
6449 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6450 return true;
6451 }
6452
6453 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6454 if (sizeRead < 0) {
6455 dprintf(outFd, "Error reading user input. Exiting.\n");
6456 return true;
6457 }
6458
6459 if (sizeRead == 0) {
6460 // Reached end of input fd (can happen if input is piped)
6461 // User has no way to signal an interrupt, so interrupt here
6462 return true;
6463 }
6464
6465 if (buffer[0] == '\n') {
6466 // User pressed return, interrupt watch command.
6467 return true;
6468 }
6469 }
6470}
6471
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006472status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6473 int inFd, int outFd) {
6474 // Figure out refresh interval, if present in args
6475 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006476 if (args.size() > 2) {
6477 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006478 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006479 intervalIdx++);
6480
6481 size_t intervalValIdx = intervalIdx + 1;
6482 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006483 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006484 if (errno) { return BAD_VALUE; }
6485 }
6486 }
6487
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006488 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6489 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006490
Avichal Rakesh84147132021-11-11 17:47:11 -08006491 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006492 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006493
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006494 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006495 bool serviceLock = tryLock(mServiceLock);
6496 auto cameraClients = mActiveClientManager.getAll();
6497 if (serviceLock) { mServiceLock.unlock(); }
6498
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006499 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006500 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006501 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006502
6503 sp<BasicClient> client = clientDescriptor->getValue();
6504 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006505 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006506
Austin Borgered99f642023-06-01 16:51:35 -07006507 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006508 // This also initializes the map entries with an empty string
6509 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6510
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006511 std::vector<std::string> latestEvents;
6512 client->dumpWatchedEventsToVector(latestEvents);
6513
6514 if (!latestEvents.empty()) {
6515 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006516 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006517 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006518 latestEvents,
6519 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006520 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006521 }
6522 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006523 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006524 break;
6525 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006526 }
6527 return OK;
6528}
6529
Austin Borgered99f642023-06-01 16:51:35 -07006530void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006531 mWatchedClientPackages.clear();
6532
Austin Borgered99f642023-06-01 16:51:35 -07006533 std::istringstream iss(clients);
6534 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006535
Austin Borgered99f642023-06-01 16:51:35 -07006536 while (std::getline(iss, nextClient, ',')) {
6537 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006538 // Don't need to track any other package if 'all' is present
6539 mWatchedClientPackages.clear();
6540 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6541 break;
6542 }
6543
6544 // track package names
6545 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006546 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006547}
6548
Svet Ganova453d0d2018-01-11 15:37:58 -08006549status_t CameraService::printHelp(int out) {
6550 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006551 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6552 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6553 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006554 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6555 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6556 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006557 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6558 " Valid values 0=false, 1=true, 2=auto\n"
6559 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006560 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6561 " Valid values 0=OFF, 1=ON for JPEG\n"
6562 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006563 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006564 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6565 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6566 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6567 " on. In case the number of usecases is smaller than the number of streams, the\n"
6568 " last use case is assigned to all the remaining streams. In case of multiple\n"
6569 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6570 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6571 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6572 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006573 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6574 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006575 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6576 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006577 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006578 " help print this message\n");
6579}
6580
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006581bool CameraService::isClientWatched(const BasicClient *client) {
6582 Mutex::Autolock lock(mLogLock);
6583 return isClientWatchedLocked(client);
6584}
6585
6586bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6587 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6588 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6589}
6590
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006591int32_t CameraService::updateAudioRestriction() {
6592 Mutex::Autolock lock(mServiceLock);
6593 return updateAudioRestrictionLocked();
6594}
6595
6596int32_t CameraService::updateAudioRestrictionLocked() {
6597 int32_t mode = 0;
6598 // iterate through all active client
6599 for (const auto& i : mActiveClientManager.getAll()) {
6600 const auto clientSp = i->getValue();
6601 mode |= clientSp->getAudioRestriction();
6602 }
6603
6604 bool modeChanged = (mAudioRestriction != mode);
6605 mAudioRestriction = mode;
6606 if (modeChanged) {
6607 mAppOps.setCameraAudioRestriction(mode);
6608 }
6609 return mode;
6610}
6611
Austin Borgered99f642023-06-01 16:51:35 -07006612status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006613 sp<BasicClient> clientSp) {
6614 std::unique_ptr<AutoConditionLock> lock =
6615 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6616 status_t res = NO_ERROR;
6617 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006618 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006619 mInjectionStatusListener->notifyInjectionError(
6620 externalCamId, UNKNOWN_TRANSACTION);
6621 clientSp->notifyError(
6622 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6623 CaptureResultExtras());
6624
6625 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6626 // other clients from connecting in mServiceLockWrapper if held
6627 mServiceLock.unlock();
6628
6629 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006630 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006631 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006632 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006633
6634 // Reacquire mServiceLock
6635 mServiceLock.lock();
6636 }
6637
6638 return res;
6639}
6640
Cliff Wud3a05312021-04-26 23:07:31 +08006641void CameraService::clearInjectionParameters() {
6642 {
6643 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006644 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006645 mInjectionInternalCamId = "";
6646 }
6647 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006648 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006649}
6650
Biswarup Pal37a75182024-01-16 15:53:35 +00006651} // namespace android