blob: fe749965dae6decf508c876e518b7a243d3b1100 [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 }
Yi Kong3ac211f2024-08-12 07:31:44 +08001545 return 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;
Austin Borger7d2b9232024-07-22 14:17:14 -07001614
Austin Borgerb01a8702024-07-22 16:20:34 -07001615 int callingPid = getCallingPid();
1616 logConnectionAttempt(callingPid, kServiceName, cameraIdStr, API_1);
Austin Borger7d2b9232024-07-22 14:17:14 -07001617
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001618 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001619 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001620 kServiceName, /*systemNativeClient*/ false, {}, uid, callingPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001621 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00001622 /*targetSdkVersion*/ __ANDROID_API_FUTURE__,
1623 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_OVERRIDE_TO_PORTRAIT,
Austin Borger7d2b9232024-07-22 14:17:14 -07001624 /*forceSlowJpegMode*/false, cameraIdStr, /*isNonSystemNdk*/ false, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001625 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001626 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001627 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001628 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001629}
1630
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001631Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001632 /*out*/
1633 CameraParameters* parameters) {
1634
1635 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1636
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001637 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001638
1639 if (parameters == NULL) {
1640 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001641 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001642 }
1643
malikakash98260df2024-05-10 23:33:57 +00001644 std::string cameraIdStr = std::to_string(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08001645
1646 // Check if we already have parameters
1647 {
1648 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001649 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001650 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001651 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001652 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001653 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001654 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001655 }
1656 CameraParameters p = cameraState->getShimParams();
1657 if (!p.isEmpty()) {
1658 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001659 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001660 }
1661 }
1662
Austin Borger22c5c852024-03-08 13:31:36 -08001663 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001664 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001665 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001666 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001667 // Error already logged by callee
1668 return ret;
1669 }
1670
1671 // Check for parameters again
1672 {
1673 // Scope for service lock
1674 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001675 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001676 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001677 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001678 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001679 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001680 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001681 CameraParameters p = cameraState->getShimParams();
1682 if (!p.isEmpty()) {
1683 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001684 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001685 }
1686 }
1687
Ruben Brunkcc776712015-02-17 20:18:47 -08001688 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1689 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001690 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001691}
1692
Austin Borgered99f642023-06-01 16:51:35 -07001693Status CameraService::validateConnectLocked(const std::string& cameraId,
Austin Borgerb01a8702024-07-22 16:20:34 -07001694 const std::string& clientName8, int clientUid, int clientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001695
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001696#ifdef __BRILLO__
1697 UNUSED(clientName8);
1698 UNUSED(clientUid);
1699 UNUSED(clientPid);
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001700#else
Austin Borger6e831c42024-07-22 13:07:56 -07001701 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001702 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001703 return allowed;
1704 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001705#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001706
Austin Borger22c5c852024-03-08 13:31:36 -08001707 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001708
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001709 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001710 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1711 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001712 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001713 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001714 }
1715
Ruben Brunkcc776712015-02-17 20:18:47 -08001716 if (getCameraState(cameraId) == nullptr) {
1717 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001718 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001719 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001720 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001721 }
1722
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001723 status_t err = checkIfDeviceIsUsable(cameraId);
1724 if (err != NO_ERROR) {
1725 switch(err) {
1726 case -ENODEV:
1727 case -EBUSY:
1728 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001729 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001730 default:
1731 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001732 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001733 }
1734 }
1735 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001736}
1737
Austin Borgerb01a8702024-07-22 16:20:34 -07001738Status CameraService::errorNotTrusted(int clientPid, int clientUid, const std::string& cameraId,
1739 const std::string& clientName, bool isPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001740 int callingPid = getCallingPid();
1741 int callingUid = getCallingUid();
Austin Borgerb01a8702024-07-22 16:20:34 -07001742 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1743 "(don't trust %s %d)", callingPid, callingUid, isPid ? "clientPid" : "clientUid",
1744 isPid ? clientPid : clientUid);
1745 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)",
1748 getCallingPid(), getCallingUid(), cameraId.c_str(),
1749 clientName.c_str(), clientPid, clientUid);
1750}
Mathias Agopian65ab4712010-07-14 17:59:35 -07001751
Austin Borgerb01a8702024-07-22 16:20:34 -07001752Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1753 const std::string& clientName, int clientUid, int clientPid) const {
1754 int callingPid = getCallingPid();
1755 int callingUid = getCallingUid();
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001756
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001757 if (shouldRejectSystemCameraConnection(cameraId)) {
1758 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1759 cameraId.c_str());
1760 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001761 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001762 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001763 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1764 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001765 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001766 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001767 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001768 }
1769
Biswarup Pale506e732024-03-27 13:46:20 +00001770 // Get the device id that owns this camera.
1771 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1772
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001773 // If it's not calling from cameraserver, check the permission if the
1774 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1775 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001776 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001777 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001778 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001779 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001780 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001781 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1782 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001783 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001784 }
1785
Svet Ganova453d0d2018-01-11 15:37:58 -08001786 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001787 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001788 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001789 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1790 clientPid, clientUid);
1791 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001792 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1793 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001794 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001795 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001796 }
1797
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001798 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1799 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1800 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1801 if ((!isAutomotivePrivilegedClient(callingUid) ||
1802 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1803 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001804 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1805 return STATUS_ERROR_FMT(ERROR_DISABLED,
1806 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001807 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001808 }
1809
Austin Borger6e831c42024-07-22 13:07:56 -07001810 userid_t clientUserId = multiuser_get_user_id(clientUid);
1811
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07001812 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
1813 // connected to camera service directly.
Wu-cheng Lia3355432011-05-20 14:54:25 +08001814
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001815 // For non-system clients : Only allow clients who are being used by the current foreground
1816 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08001817 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08001818 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07001819 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
1820 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07001821 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001822 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1823 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07001824 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07001825 }
1826
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001827 if (flags::camera_hsum_permission()) {
1828 // If the System User tries to access the camera when the device is running in
1829 // headless system user mode, ensure that client has the required permission
1830 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07001831 if (isHeadlessSystemUserMode()
1832 && (clientUserId == USER_SYSTEM)
1833 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Austin Borger6e831c42024-07-22 13:07:56 -07001834 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", callingPid, clientUid);
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001835 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1836 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
1837 User without camera headless system user permission",
Austin Borger6e831c42024-07-22 13:07:56 -07001838 clientName.c_str(), callingPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07001839 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07001840 }
1841
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001842 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001843}
1844
Austin Borgered99f642023-06-01 16:51:35 -07001845status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08001846 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001847 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08001848 if (cameraState == nullptr) {
1849 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001850 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001851 return -ENODEV;
1852 }
1853
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001854 StatusInternal currentStatus = cameraState->getStatus();
1855 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07001857 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001858 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001859 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001860 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07001861 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07001862 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07001863 }
Igor Murashkincba2c162013-03-20 15:56:31 -07001864
Ruben Brunkcc776712015-02-17 20:18:47 -08001865 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08001866}
1867
Ruben Brunkcc776712015-02-17 20:18:47 -08001868void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001869 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08001870
Ruben Brunkcc776712015-02-17 20:18:47 -08001871 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001872 auto clientDescriptor =
1873 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08001874 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08001875 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
1876
1877 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07001878 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08001879
1880 if (evicted.size() > 0) {
1881 // This should never happen - clients should already have been removed in disconnect
1882 for (auto& i : evicted) {
1883 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07001884 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001885 }
1886
1887 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
1888 __FUNCTION__);
1889 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07001890
1891 // And register a death notification for the client callback. Do
1892 // this last to avoid Binder policy where a nested Binder
1893 // transaction might be pre-empted to service the client death
1894 // notification if the client process dies before linkToDeath is
1895 // invoked.
1896 sp<IBinder> remoteCallback = client->getRemote();
1897 if (remoteCallback != nullptr) {
1898 remoteCallback->linkToDeath(this);
1899 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001900}
1901
Austin Borgered99f642023-06-01 16:51:35 -07001902status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
1903 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
1904 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08001905 /*out*/
1906 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07001907 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001908 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08001909 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07001910 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08001911 DescriptorPtr clientDescriptor;
1912 {
1913 if (effectiveApiLevel == API_1) {
1914 // If we are using API1, any existing client for this camera ID with the same remote
1915 // should be returned rather than evicted to allow MediaRecorder to work properly.
1916
1917 auto current = mActiveClientManager.get(cameraId);
1918 if (current != nullptr) {
1919 auto clientSp = current->getValue();
1920 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001921 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07001922 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001923 " API level, evicting prior client...");
1924 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001925 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07001926 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08001927 *client = clientSp;
1928 return NO_ERROR;
1929 }
1930 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001931 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08001932 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08001933
Ruben Brunkcc776712015-02-17 20:18:47 -08001934 // Get state for the given cameraId
1935 auto state = getCameraState(cameraId);
1936 if (state == nullptr) {
1937 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07001938 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001939 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07001940 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07001941 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001942
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001943 sp<IServiceManager> sm = defaultServiceManager();
1944 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08001945 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001946 // If processinfo service is not available and the client is automotive privileged
1947 // client used for safety critical uses cases such as rear-view and surround-view which
1948 // needs to be available before android boot completes, then use the hardcoded values
1949 // for the process state and priority score. As this scenario is before android system
1950 // services are up and client is native client, hence using NATIVE_ADJ as the priority
1951 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
1952 // visible on the top.
1953 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1954 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1955 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
1956 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
1957 } else {
1958 // Get current active client PIDs
1959 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
1960 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00001961
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07001962 std::vector<int> priorityScores(ownerPids.size());
1963 std::vector<int> states(ownerPids.size());
1964
1965 // Get priority scores of all active PIDs
1966 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
1967 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
1968 if (err != OK) {
1969 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
1970 return err;
1971 }
1972
1973 // Update all active clients' priorities
1974 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
1975 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
1976 pidToPriorityMap.emplace(ownerPids[i],
1977 resource_policy::ClientPriority(priorityScores[i], states[i],
1978 /* isVendorClient won't get copied over*/ false,
1979 /* oomScoreOffset won't get copied over*/ 0));
1980 }
1981 mActiveClientManager.updatePriorities(pidToPriorityMap);
1982
1983 int32_t actualScore = priorityScores[priorityScores.size() - 1];
1984 int32_t actualState = states[states.size() - 1];
1985
1986 // Make descriptor for incoming client. We store the oomScoreOffset
1987 // since we might need it later on new handleEvictionsLocked and
1988 // ProcessInfoService would not take that into account.
1989 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
1990 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
1991 state->getConflicting(), actualScore, clientPid, actualState,
1992 oomScoreOffset, systemNativeClient);
1993 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001994
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07001995 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
1996
Ruben Brunkcc776712015-02-17 20:18:47 -08001997 // Find clients that would be evicted
1998 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
1999
2000 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2001 // background, so we cannot do evictions
2002 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2003 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2004 " priority).", clientPid);
2005
2006 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002007 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002008 auto incompatibleClients =
2009 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2010
Austin Borgered99f642023-06-01 16:51:35 -07002011 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2012 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2013 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002014 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002015
2016 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002017 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002018 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002019 i->getKey().c_str(),
2020 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002021 i->getOwnerId(), i->getPriority().getScore(),
2022 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002023 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002024 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2025 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002026 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002027 }
2028
2029 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002030 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002031 mEventLog.add(msg);
2032
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002033 auto current = mActiveClientManager.get(cameraId);
2034 if (current != nullptr) {
2035 return -EBUSY; // CAMERA_IN_USE
2036 } else {
2037 return -EUSERS; // MAX_CAMERAS_IN_USE
2038 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 }
2040
2041 for (auto& i : evicted) {
2042 sp<BasicClient> clientSp = i->getValue();
2043 if (clientSp.get() == nullptr) {
2044 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2045
2046 // TODO: Remove this
2047 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2048 __FUNCTION__);
2049 mActiveClientManager.remove(i);
2050 continue;
2051 }
2052
2053 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002054 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002055 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002056
Ruben Brunkcc776712015-02-17 20:18:47 -08002057 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002058 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002059 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2060 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002061 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002062 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002063 i->getPriority().getState(), cameraId.c_str(),
2064 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002065 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002066
2067 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002068 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002069 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002070 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002071 }
2072
Ruben Brunkcc776712015-02-17 20:18:47 -08002073 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2074 // other clients from connecting in mServiceLockWrapper if held
2075 mServiceLock.unlock();
2076
2077 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002078 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002079
2080 // Destroy evicted clients
2081 for (auto& i : evictedClients) {
2082 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002083 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002084 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002085
Austin Borger22c5c852024-03-08 13:31:36 -08002086 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002087
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002088 for (const auto& i : evictedClients) {
2089 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002090 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002091 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2092 if (ret == TIMED_OUT) {
2093 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002094 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2095 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002096 return -EBUSY;
2097 }
2098 if (ret != NO_ERROR) {
2099 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002100 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2101 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002102 return ret;
2103 }
2104 }
2105
2106 evictedClients.clear();
2107
Ruben Brunkcc776712015-02-17 20:18:47 -08002108 // Once clients have been disconnected, relock
2109 mServiceLock.lock();
2110
2111 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2112 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2113 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002114 }
2115
Ruben Brunkcc776712015-02-17 20:18:47 -08002116 *partial = clientDescriptor;
2117 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002118}
2119
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002120Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002121 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002122 int api1CameraId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002123 int targetSdkVersion,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002124 int rotationOverride,
Chengfei Taobe683db2023-01-31 18:52:49 +00002125 bool forceSlowJpegMode,
Austin Borger65e64642024-06-11 15:58:23 -07002126 const AttributionSourceState& clientAttribution,
Biswarup Pal37a75182024-01-16 15:53:35 +00002127 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002128 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002129 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002130 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002131 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002132
Austin Borger65e64642024-06-11 15:58:23 -07002133 std::string cameraIdStr =
2134 cameraIdIntToStr(api1CameraId, clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002135 if (cameraIdStr.empty()) {
2136 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002137 api1CameraId, clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002138 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2139 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2140 }
malikakashedb38962023-09-06 00:03:35 +00002141
Austin Borger7d2b9232024-07-22 14:17:14 -07002142 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
2143 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2144 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2145 clientPackageNameMaybe);
2146 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraIdStr, API_1);
2147
Austin Borgerb01a8702024-07-22 16:20:34 -07002148 int clientUid = clientAttribution.uid;
2149 int clientPid = clientAttribution.pid;
2150
2151 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2152 // need a way to guarantee the caller identity early.
2153
2154 // Check if we can trust clientUid
2155 if (!resolveClientUid(clientUid)) {
2156 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2157 /* isPid=*/ false);
2158 }
2159
2160 // Check if we can trust clientUid
2161 if (!resolveClientPid(clientPid)) {
2162 return errorNotTrusted(clientPid, clientUid, cameraIdStr, clientPackageName,
2163 /* isPid= */ true);
2164 }
2165
Ruben Brunkcc776712015-02-17 20:18:47 -08002166 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002167 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
Austin Borger7d2b9232024-07-22 14:17:14 -07002168 clientPackageName, /*systemNativeClient*/ false, {},
Austin Borgerb01a8702024-07-22 16:20:34 -07002169 clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002170 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borger7d2b9232024-07-22 14:17:14 -07002171 rotationOverride, forceSlowJpegMode, cameraIdStr, isNonSystemNdk, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002172
Biswarup Pal37a75182024-01-16 15:53:35 +00002173 if (!ret.isOk()) {
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002174 logRejected(cameraIdStr, getCallingPid(), clientAttribution.packageName.value_or(""),
2175 toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002176 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002177 }
2178
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002179 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002180
2181 const sp<IServiceManager> sm(defaultServiceManager());
2182 const auto& mActivityManager = getActivityManager();
2183 if (mActivityManager) {
2184 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002185 getCallingUid(),
2186 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002187 }
2188
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002189 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002190}
2191
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002192bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2193 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002194 // If the client is not a vendor client, don't add listener if
2195 // a) the camera is a publicly hidden secure camera OR
2196 // b) the camera is a system only camera and the client doesn't
2197 // have android.permission.SYSTEM_CAMERA permissions.
2198 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2199 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002200 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002201 return true;
2202 }
2203 return false;
2204}
2205
Austin Borgered99f642023-06-01 16:51:35 -07002206bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002207 // Rules for rejection:
2208 // 1) If cameraserver tries to access this camera device, accept the
2209 // connection.
2210 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002211 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002212 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2213 // and the serving thread is a non hwbinder thread, the client must have
2214 // android.permission.SYSTEM_CAMERA permissions to connect.
2215
Austin Borger22c5c852024-03-08 13:31:36 -08002216 int cPid = getCallingPid();
2217 int cUid = getCallingUid();
2218 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002219 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2220 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002221 // This isn't a known camera ID, so it's not a system camera
2222 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2223 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002224 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002225
2226 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002227 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002228 return false;
2229 }
2230 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002231 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002232 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2233 return true;
2234 }
2235 // (3) Here we only check for permissions if it is a system only camera device. This is since
2236 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2237 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2238 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002239 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002240 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002241 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2242 cameraId.c_str());
2243 return true;
2244 }
2245
2246 return false;
2247}
2248
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002249Status CameraService::connectDevice(
2250 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002251 const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002252 int oomScoreOffset, int targetSdkVersion,
2253 int rotationOverride, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002254 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002255 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002256 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002257 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002258 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002259 sp<CameraDeviceClient> client = nullptr;
Austin Borger7d2b9232024-07-22 14:17:14 -07002260 std::string clientPackageNameMaybe = clientAttribution.packageName.value_or("");
Austin Borger22c5c852024-03-08 13:31:36 -08002261 int callingPid = getCallingPid();
2262 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002263 bool systemNativeClient = false;
Austin Borger7d2b9232024-07-22 14:17:14 -07002264 if (callerHasSystemUid() && (clientPackageNameMaybe.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002265 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borger7d2b9232024-07-22 14:17:14 -07002266 clientPackageNameMaybe = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002267 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002268 }
Austin Borger249e6592024-03-10 22:28:11 -07002269
Austin Borger65e64642024-06-11 15:58:23 -07002270 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2271 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002272 if (!cameraIdOptional.has_value()) {
2273 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002274 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002275 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2276 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2277 }
2278 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002279
Austin Borger7d2b9232024-07-22 14:17:14 -07002280 bool isNonSystemNdk = clientPackageNameMaybe.size() == 0;
2281 std::string clientPackageName = resolvePackageName(clientAttribution.uid,
2282 clientPackageNameMaybe);
2283 logConnectionAttempt(clientAttribution.pid, clientPackageName, cameraId, API_2);
2284
Austin Borgerb01a8702024-07-22 16:20:34 -07002285 userid_t clientUserId = multiuser_get_user_id(clientAttribution.uid);
2286 if (clientAttribution.uid == USE_CALLING_UID) {
2287 clientUserId = multiuser_get_user_id(callingUid);
2288 }
2289
2290 // Resolve the client identity. In the near future, we will no longer rely on USE_CALLING_*, and
2291 // need a way to guarantee the caller identity early.
2292
2293 int clientUid = clientAttribution.uid;
2294 int clientPid = callingPid;
2295 // Check if we can trust clientUid
2296 if (!resolveClientUid(clientUid)) {
2297 return errorNotTrusted(clientPid, clientUid, cameraId, clientPackageName,
2298 /* isPid= */ false);
2299 }
2300
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002301 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002302 std::string msg =
2303 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
Austin Borger7d2b9232024-07-22 14:17:14 -07002304 "camera id %s", clientPackageName.c_str(), callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002305 cameraId.c_str());
2306 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2307 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002308 }
2309
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002310 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2311 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002312 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2313 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002314 std::string msg = "Camera disabled by device policy";
2315 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2316 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002317 }
2318
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002319 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002320 if (oomScoreOffset > 0
2321 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002322 callingUid)
2323 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002324 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002325 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borger7d2b9232024-07-22 14:17:14 -07002326 clientPackageName.c_str(), callingPid, cameraId.c_str());
Austin Borgered99f642023-06-01 16:51:35 -07002327 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2328 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002329 }
2330
Austin Borgered99f642023-06-01 16:51:35 -07002331 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
Austin Borger7d2b9232024-07-22 14:17:14 -07002332 cameraId, /*api1CameraId*/-1, clientPackageName, systemNativeClient,
Austin Borgerb01a8702024-07-22 16:20:34 -07002333 clientAttribution.attributionTag, clientUid, clientPid, API_2,
Austin Borgerd1ad6c62024-07-01 11:28:31 -07002334 /*shimUpdateOnly*/ false, oomScoreOffset, targetSdkVersion, rotationOverride,
Austin Borger7d2b9232024-07-22 14:17:14 -07002335 /*forceSlowJpegMode*/false, unresolvedCameraId, isNonSystemNdk, /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002336
Biswarup Pal37a75182024-01-16 15:53:35 +00002337 if (!ret.isOk()) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002338 logRejected(cameraId, callingPid, clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002339 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002340 }
2341
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002342 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002343 Mutex::Autolock lock(mServiceLock);
2344
2345 // Clear the previous cached logs and reposition the
2346 // file offset to beginning of the file to log new data.
2347 // If either truncate or lseek fails, close the previous file and create a new one.
2348 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2349 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2350 // Close the previous memfd.
2351 close(mMemFd);
2352 // If failure to wipe the data, then create a new file and
2353 // assign the new value to mMemFd.
2354 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2355 if (mMemFd == -1) {
2356 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2357 }
2358 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002359 const sp<IServiceManager> sm(defaultServiceManager());
2360 const auto& mActivityManager = getActivityManager();
2361 if (mActivityManager) {
2362 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002363 callingUid,
2364 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002365 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002366 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002367}
2368
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002369bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2370 int callingPid, int callingUid) {
2371 if (!isAutomotiveDevice()) {
2372 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2373 }
2374
2375 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2376 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2377 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2378 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2379 "using camera %s", callingUid, cam_id.c_str());
2380 return false;
2381 }
2382
2383 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2384 return true;
2385 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2386 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002387 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2388 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002389 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2390 return false;
2391 } else {
2392 return true;
2393 }
2394 }
2395 return false;
2396}
2397
Austin Borger7d2b9232024-07-22 14:17:14 -07002398std::string CameraService::getPackageNameFromUid(int clientUid) const {
Austin Borgered99f642023-06-01 16:51:35 -07002399 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002400
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002401 sp<IPermissionController> permCtrl;
2402 if (flags::cache_permission_services()) {
2403 permCtrl = getPermissionController();
2404 } else {
2405 sp<IServiceManager> sm = defaultServiceManager();
2406#pragma clang diagnostic push
2407#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2408 // Using deprecated function to preserve functionality until the
2409 // cache_permission_services flag is removed.
2410 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2411#pragma clang diagnostic pop
2412 if (binder == 0) {
2413 ALOGE("Cannot get permission service");
2414 permCtrl = nullptr;
2415 } else {
2416 permCtrl = interface_cast<IPermissionController>(binder);
2417 }
2418 }
2419
2420 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002421 // Return empty package name and the further interaction
2422 // with camera will likely fail
2423 return packageName;
2424 }
2425
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002426 Vector<String16> packages;
2427
2428 permCtrl->getPackagesForUid(clientUid, packages);
2429
2430 if (packages.isEmpty()) {
2431 ALOGE("No packages for calling UID %d", clientUid);
2432 // Return empty package name and the further interaction
2433 // with camera will likely fail
2434 return packageName;
2435 }
2436
2437 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002438 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002439
2440 return packageName;
2441}
2442
Austin Borger7d2b9232024-07-22 14:17:14 -07002443void CameraService::logConnectionAttempt(int clientPid, const std::string& clientPackageName,
2444 const std::string& cameraId, apiLevel effectiveApiLevel) const {
2445 int packagePid = (clientPid == USE_CALLING_PID) ?
2446 getCallingPid() : clientPid;
2447 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
2448 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
2449 static_cast<int>(effectiveApiLevel));
2450}
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002451
Austin Borger7d2b9232024-07-22 14:17:14 -07002452std::string CameraService::resolvePackageName(int clientUid,
2453 const std::string& clientPackageNameMaybe) const {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002454 if (clientPackageNameMaybe.size() <= 0) {
Austin Borger7d2b9232024-07-22 14:17:14 -07002455 int packageUid = (clientUid == USE_CALLING_UID) ?
2456 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002457 // NDK calls don't come with package names, but we need one for various cases.
2458 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2459 // do exist. For all authentication cases, all packages under the same UID get the
2460 // same permissions, so picking any associated package name is sufficient. For some
2461 // other cases, this may give inaccurate names for clients in logs.
Austin Borger7d2b9232024-07-22 14:17:14 -07002462 return getPackageNameFromUid(packageUid);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002463 } else {
Austin Borger7d2b9232024-07-22 14:17:14 -07002464 return clientPackageNameMaybe;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002465 }
Austin Borger7d2b9232024-07-22 14:17:14 -07002466}
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002467
Austin Borger7d2b9232024-07-22 14:17:14 -07002468template<class CALLBACK, class CLIENT>
2469Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2470 int api1CameraId, const std::string& clientPackageName, bool systemNativeClient,
2471 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
2472 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
2473 int rotationOverride, bool forceSlowJpegMode,
2474 const std::string& originalCameraId, bool isNonSystemNdk, /*out*/sp<CLIENT>& device) {
2475 binder::Status ret = binder::Status::ok();
2476
2477 int packageUid = (clientUid == USE_CALLING_UID) ?
2478 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002479 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger7d2b9232024-07-22 14:17:14 -07002480 getCallingPid() : clientPid;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002481
Shuzhen Wang316781a2020-08-18 18:11:01 -07002482 nsecs_t openTimeNs = systemTime();
2483
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002484 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002485 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002486 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002487
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002488 {
2489 // Acquire mServiceLock and prevent other clients from connecting
2490 std::unique_ptr<AutoConditionLock> lock =
2491 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2492
2493 if (lock == nullptr) {
2494 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2495 , clientPid);
2496 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2497 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002498 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002499 }
2500
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002501 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002502 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Austin Borger6e831c42024-07-22 13:07:56 -07002503 /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002504 return ret;
2505 }
2506
2507 // Check the shim parameters after acquiring lock, if they have already been updated and
2508 // we were doing a shim update, return immediately
2509 if (shimUpdateOnly) {
2510 auto cameraState = getCameraState(cameraId);
2511 if (cameraState != nullptr) {
2512 if (!cameraState->getShimParams().isEmpty()) return ret;
2513 }
2514 }
2515
2516 status_t err;
2517
2518 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002519 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Austin Borger6e831c42024-07-22 13:07:56 -07002520 if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002521 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2522 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002523 switch (err) {
2524 case -ENODEV:
2525 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2526 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002527 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002528 case -EBUSY:
2529 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2530 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002531 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002532 case -EUSERS:
2533 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2534 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002535 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002536 default:
2537 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2538 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002539 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002540 }
2541 }
2542
2543 if (clientTmp.get() != nullptr) {
2544 // Handle special case for API1 MediaRecorder where the existing client is returned
2545 device = static_cast<CLIENT*>(clientTmp.get());
2546 return ret;
2547 }
2548
2549 // give flashlight a chance to close devices if necessary.
2550 mFlashlight->prepareDeviceOpen(cameraId);
2551
Austin Borger18b30a72022-10-27 12:20:29 -07002552 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002553 auto deviceVersionAndTransport =
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002554 getDeviceVersion(cameraId, rotationOverride, /*out*/&portraitRotation,
Austin Borger18b30a72022-10-27 12:20:29 -07002555 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002556 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002557 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002558 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002559 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002560 }
2561
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002562 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002563 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002564 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002565
Austin Borger6e831c42024-07-22 13:07:56 -07002566 // Only use passed in clientPid to check permission. Use calling PID as the client PID
2567 // that's connected to camera service directly.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002568 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002569 clientFeatureId, cameraId, api1CameraId, facing,
Austin Borger7d2b9232024-07-22 14:17:14 -07002570 orientation, getCallingPid(), clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002571 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002572 rotationOverride, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002573 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002574 return ret;
2575 }
2576 client = static_cast<CLIENT*>(tmp.get());
2577
2578 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2579 __FUNCTION__);
2580
Austin Borgered99f642023-06-01 16:51:35 -07002581 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002582 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002583 if (err != OK) {
2584 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002585 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002586 mServiceLock.unlock();
2587 client->disconnect();
2588 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002589 switch(err) {
2590 case BAD_VALUE:
2591 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002592 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002593 case -EBUSY:
2594 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002595 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002596 case -EUSERS:
2597 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2598 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002599 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002600 case PERMISSION_DENIED:
2601 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002602 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002603 case -EACCES:
2604 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002605 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002606 case -ENODEV:
2607 default:
2608 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002609 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002610 strerror(-err), err);
2611 }
2612 }
2613
2614 // Update shim paremeters for legacy clients
2615 if (effectiveApiLevel == API_1) {
2616 // Assume we have always received a Client subclass for API1
2617 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2618 String8 rawParams = shimClient->getParameters();
2619 CameraParameters params(rawParams);
2620
2621 auto cameraState = getCameraState(cameraId);
2622 if (cameraState != nullptr) {
2623 cameraState->setShimParams(params);
2624 } else {
2625 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002626 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002627 }
2628 }
2629
Ravneetaeb20dc2022-03-30 05:33:03 +00002630 // Enable/disable camera service watchdog
2631 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2632
Emilian Peev6d45db82024-01-18 20:11:54 +00002633 CameraMetadata chars;
2634 bool rotateAndCropSupported = true;
2635 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002636 &chars, rotationOverride);
Emilian Peev6d45db82024-01-18 20:11:54 +00002637 if (err == OK) {
2638 auto availableRotateCropEntry = chars.find(
2639 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2640 if (availableRotateCropEntry.count <= 1) {
2641 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002642 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002643 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002644 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2645 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002646 }
2647
Emilian Peev6d45db82024-01-18 20:11:54 +00002648 if (rotateAndCropSupported) {
2649 // Set rotate-and-crop override behavior
2650 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2651 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002652 } else if (rotationOverride != hardware::ICameraService::ROTATION_OVERRIDE_NONE &&
2653 portraitRotation != 0) {
Emilian Peev6d45db82024-01-18 20:11:54 +00002654 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2655 switch (portraitRotation) {
2656 case 90:
2657 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2658 break;
2659 case 180:
2660 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2661 break;
2662 case 270:
2663 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2664 break;
2665 default:
2666 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2667 break;
2668 }
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00002669 // Here we're communicating to the client the chosen rotate
2670 // and crop mode to send to the HAL
Emilian Peev6d45db82024-01-18 20:11:54 +00002671 client->setRotateAndCropOverride(rotateAndCropMode);
2672 } else {
2673 client->setRotateAndCropOverride(
2674 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2675 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2676 }
2677 }
2678
2679 bool autoframingSupported = true;
2680 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2681 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2682 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2683 autoframingSupported = false;
2684 }
2685
2686 if (autoframingSupported) {
2687 // Set autoframing override behaviour
2688 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2689 client->setAutoframingOverride(mOverrideAutoframingMode);
2690 } else {
2691 client->setAutoframingOverride(
2692 mCameraServiceProxyWrapper->getAutoframingOverride(
2693 clientPackageName));
2694 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002695 }
2696
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002697 bool isCameraPrivacyEnabled;
2698 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002699 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002700 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2701 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2702 } else {
2703 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002704 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002705 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002706
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002707 if (client->supportsCameraMute()) {
2708 client->setCameraMute(
2709 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2710 } else if (isCameraPrivacyEnabled) {
2711 // no camera mute supported, but privacy is on! => disconnect
2712 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2713 client->getPackageName().c_str(), cameraId.c_str());
2714 // Do not hold mServiceLock while disconnecting clients, but
2715 // retain the condition blocking other clients from connecting
2716 // in mServiceLockWrapper if held.
2717 mServiceLock.unlock();
2718 // Clear caller identity temporarily so client disconnect PID
2719 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002720 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002721 // Note AppOp to trigger the "Unblock" dialog
2722 client->noteAppOp();
2723 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002724 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002725 // Reacquire mServiceLock
2726 mServiceLock.lock();
2727
2728 return STATUS_ERROR_FMT(ERROR_DISABLED,
2729 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002730 }
2731
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002732 if (shimUpdateOnly) {
2733 // If only updating legacy shim parameters, immediately disconnect client
2734 mServiceLock.unlock();
2735 client->disconnect();
2736 mServiceLock.lock();
2737 } else {
2738 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002739 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002740 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002741
2742 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002743 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002744 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002745 } // lock is destroyed, allow further connect calls
2746
2747 // Important: release the mutex here so the client can call back into the service from its
2748 // destructor (can be at the end of the call)
2749 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002750
2751 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002752 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002753 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002754
Cliff Wud3a05312021-04-26 23:07:31 +08002755 {
2756 Mutex::Autolock lock(mInjectionParametersLock);
2757 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2758 mInjectionInitPending = false;
2759 status_t res = NO_ERROR;
2760 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2761 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002762 sp<BasicClient> clientSp = clientDescriptor->getValue();
2763 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2764 if(res != OK) {
2765 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2766 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002767 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002768 }
2769 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002770 if (res != OK) {
2771 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2772 }
2773 } else {
2774 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002775 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002776 res = NO_INIT;
2777 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2778 }
2779 }
2780 }
2781
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002782 return ret;
2783}
2784
Austin Borgered99f642023-06-01 16:51:35 -07002785status_t CameraService::addOfflineClient(const std::string &cameraId,
2786 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002787 if (offlineClient.get() == nullptr) {
2788 return BAD_VALUE;
2789 }
2790
2791 {
2792 // Acquire mServiceLock and prevent other clients from connecting
2793 std::unique_ptr<AutoConditionLock> lock =
2794 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2795
2796 if (lock == nullptr) {
2797 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2798 , __FUNCTION__, offlineClient->getClientPid());
2799 return TIMED_OUT;
2800 }
2801
2802 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2803 if (onlineClientDesc.get() == nullptr) {
2804 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2805 cameraId.c_str());
2806 return BAD_VALUE;
2807 }
2808
2809 // Offline clients do not evict or conflict with other online devices. Resource sharing
2810 // conflicts are handled by the camera provider which will either succeed or fail before
2811 // reaching this method.
2812 const auto& onlinePriority = onlineClientDesc->getPriority();
2813 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2814 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002815 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002816 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002817 // native clients don't have offline processing support.
2818 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002819 if (offlineClientDesc == nullptr) {
2820 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2821 return BAD_VALUE;
2822 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002823
2824 // Allow only one offline device per camera
2825 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2826 if (!incompatibleClients.empty()) {
2827 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2828 return BAD_VALUE;
2829 }
2830
Austin Borgered99f642023-06-01 16:51:35 -07002831 std::string monitorTags = isClientWatched(offlineClient.get())
2832 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002833 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002834 if (err != OK) {
2835 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2836 return err;
2837 }
2838
2839 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2840 if (evicted.size() > 0) {
2841 for (auto& i : evicted) {
2842 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002843 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002844 }
2845
2846 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2847 "properly", __FUNCTION__);
2848
2849 return BAD_VALUE;
2850 }
2851
2852 logConnectedOffline(offlineClientDesc->getKey(),
2853 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002854 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002855
2856 sp<IBinder> remoteCallback = offlineClient->getRemote();
2857 if (remoteCallback != nullptr) {
2858 remoteCallback->linkToDeath(this);
2859 }
2860 } // lock is destroyed, allow further connect calls
2861
2862 return OK;
2863}
2864
Austin Borgered99f642023-06-01 16:51:35 -07002865Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Austin Borger65e64642024-06-11 15:58:23 -07002866 int32_t torchStrength, const sp<IBinder>& clientBinder,
2867 const AttributionSourceState& clientAttribution, int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002868 Mutex::Autolock lock(mServiceLock);
2869
2870 ATRACE_CALL();
2871 if (clientBinder == nullptr) {
2872 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
2873 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
2874 "Torch client binder in null.");
2875 }
2876
Austin Borger22c5c852024-03-08 13:31:36 -08002877 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07002878 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
2879 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00002880 if (!cameraIdOptional.has_value()) {
2881 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07002882 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00002883 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2884 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2885 }
2886 std::string cameraId = cameraIdOptional.value();
2887
Austin Borgered99f642023-06-01 16:51:35 -07002888 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08002889 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07002890 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002891 }
2892
2893 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07002894 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002895 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07002896 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002897 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002898 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002899 }
2900
2901 StatusInternal cameraStatus = state->getStatus();
2902 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
2903 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07002904 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08002905 (int)cameraStatus);
2906 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002907 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002908 }
2909
2910 {
2911 Mutex::Autolock al(mTorchStatusMutex);
2912 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07002913 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08002914 if (err != OK) {
2915 if (err == NAME_NOT_FOUND) {
2916 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002917 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002918 }
2919 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07002920 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002921 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2922 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07002923 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08002924 }
2925
2926 if (status == TorchModeStatus::NOT_AVAILABLE) {
2927 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
2928 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07002929 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002930 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2931 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07002932 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002933 } else {
2934 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07002935 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002936 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2937 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07002938 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002939 }
2940 }
2941 }
2942
2943 {
2944 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002945 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002946 }
2947 // Check if the current torch strength level is same as the new one.
2948 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07002949 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002950
Austin Borgered99f642023-06-01 16:51:35 -07002951 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002952
2953 if (err != OK) {
2954 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07002955 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08002956 switch (err) {
2957 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07002958 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
2959 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002960 errorCode = ERROR_ILLEGAL_ARGUMENT;
2961 break;
2962 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07002963 msg = fmt::sprintf("Camera \"%s\" is in use",
2964 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002965 errorCode = ERROR_CAMERA_IN_USE;
2966 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002967 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07002968 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08002969 "valid range.", torchStrength);
2970 errorCode = ERROR_ILLEGAL_ARGUMENT;
2971 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08002972 default:
Austin Borgered99f642023-06-01 16:51:35 -07002973 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08002974 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08002975 }
Austin Borgered99f642023-06-01 16:51:35 -07002976 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2977 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08002978 }
2979
2980 {
2981 // update the link to client's death
2982 // Store the last client that turns on each camera's torch mode.
2983 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07002984 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08002985 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07002986 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08002987 } else {
2988 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
2989 mTorchClientMap.replaceValueAt(index, clientBinder);
2990 }
2991 clientBinder->linkToDeath(this);
2992 }
2993
Austin Borger22c5c852024-03-08 13:31:36 -08002994 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08002995 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07002996 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08002997 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07002998 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08002999 }
3000 return Status::ok();
3001}
3002
malikakash73125c62023-07-21 22:44:34 +00003003Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Austin Borger65e64642024-06-11 15:58:23 -07003004 const sp<IBinder>& clientBinder, const AttributionSourceState& clientAttribution,
3005 int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003006 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003007
3008 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003009 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003010 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003011 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3012 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003013 }
3014
Austin Borger22c5c852024-03-08 13:31:36 -08003015 int uid = getCallingUid();
Austin Borger65e64642024-06-11 15:58:23 -07003016 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId,
3017 clientAttribution.deviceId, devicePolicy);
Biswarup Pal37a75182024-01-16 15:53:35 +00003018 if (!cameraIdOptional.has_value()) {
3019 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003020 unresolvedCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00003021 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3022 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3023 }
3024 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003025
Austin Borgered99f642023-06-01 16:51:35 -07003026 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003027 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003028 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003029 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003030 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003031 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003032 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003033 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003034 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003035 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003036 }
3037
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003038 StatusInternal cameraStatus = state->getStatus();
3039 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003040 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003041 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3042 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003043 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003044 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003045 }
3046
3047 {
3048 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003049 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003050 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003051 if (err != OK) {
3052 if (err == NAME_NOT_FOUND) {
3053 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003054 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003055 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003056 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003057 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003058 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003059 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003060 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003061 }
3062
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003063 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003064 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003065 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003066 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003067 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3068 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003069 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003070 } else {
3071 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003072 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003073 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3074 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003075 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003076 }
3077 }
3078 }
3079
Ruben Brunk99e69712015-05-26 17:25:07 -07003080 {
3081 // Update UID map - this is used in the torch status changed callbacks, so must be done
3082 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003083 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003084 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003085 }
3086
Austin Borgered99f642023-06-01 16:51:35 -07003087 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003088
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003089 if (err != OK) {
3090 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003091 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003092 switch (err) {
3093 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003094 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3095 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003096 errorCode = ERROR_ILLEGAL_ARGUMENT;
3097 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003098 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003099 msg = fmt::sprintf("Camera \"%s\" is in use",
3100 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003101 errorCode = ERROR_CAMERA_IN_USE;
3102 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003103 default:
Austin Borgered99f642023-06-01 16:51:35 -07003104 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003105 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003106 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003107 errorCode = ERROR_INVALID_OPERATION;
3108 }
Austin Borgered99f642023-06-01 16:51:35 -07003109 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3110 logServiceError(msg, errorCode);
3111 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003112 }
3113
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003114 {
3115 // update the link to client's death
3116 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003117 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003118 if (enabled) {
3119 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003120 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003121 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003122 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003123 mTorchClientMap.replaceValueAt(index, clientBinder);
3124 }
3125 clientBinder->linkToDeath(this);
3126 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003127 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003128 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003129 }
3130
Austin Borger22c5c852024-03-08 13:31:36 -08003131 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003132 std::string torchState = enabled ? "on" : "off";
3133 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3134 torchState.c_str(), clientPid);
3135 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003136 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003137}
3138
Austin Borgered99f642023-06-01 16:51:35 -07003139void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3140 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3141 mTorchUidMap[cameraId].first = uid;
3142 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003143 } else {
3144 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003145 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003146 }
3147}
3148
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003149Status CameraService::notifySystemEvent(int32_t eventId,
3150 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003151 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003152 const int selfPid = getpid();
3153
3154 // Permission checks
3155 if (pid != selfPid) {
3156 // Ensure we're being called by system_server, or similar process with
3157 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003158 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003159 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003160 ALOGE("Permission Denial: cannot send updates to camera service about system"
3161 " events from pid=%d, uid=%d", pid, uid);
3162 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003163 "No permission to send updates to camera service about system events"
3164 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003165 }
3166 }
3167
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003168 ATRACE_CALL();
3169
Ruben Brunk36597b22015-03-20 22:15:57 -07003170 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003171 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003172 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003173 // from a system server crash
3174 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003175 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003176 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003177 break;
3178 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003179 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3180 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003181 if (args.size() != 1) {
3182 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3183 "USB Device Event requires 1 argument");
3184 }
3185
Valentin Iftime29e2e152021-08-13 15:17:33 +02003186 // Notify CameraProviderManager for lazy HALs
3187 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3188 std::to_string(args[0]));
3189 break;
3190 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003191 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003192 default: {
3193 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3194 eventId);
3195 break;
3196 }
3197 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003198 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003199}
3200
Emilian Peev53722fa2019-02-22 17:47:20 -08003201void CameraService::notifyMonitoredUids() {
3202 Mutex::Autolock lock(mStatusListenerLock);
3203
3204 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003205 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003206 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3207 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003208 }
3209}
3210
Austin Borgerdddb7552023-03-30 17:53:01 -07003211void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3212 Mutex::Autolock lock(mStatusListenerLock);
3213
3214 for (const auto& it : mListenerList) {
3215 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3216 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3217 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3218 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3219 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3220 }
3221 }
3222}
3223
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003224Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003225 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003226 const int selfPid = getpid();
3227
3228 // Permission checks
3229 if (pid != selfPid) {
3230 // Ensure we're being called by system_server, or similar process with
3231 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003232 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003233 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003234 ALOGE("Permission Denial: cannot send updates to camera service about device"
3235 " state changes from pid=%d, uid=%d", pid, uid);
3236 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3237 "No permission to send updates to camera service about device state"
3238 " changes from pid=%d, uid=%d", pid, uid);
3239 }
3240 }
3241
3242 ATRACE_CALL();
3243
Austin Borger18b30a72022-10-27 12:20:29 -07003244 {
3245 Mutex::Autolock lock(mServiceLock);
3246 mDeviceState = newState;
3247 }
3248
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003249 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003250
3251 return Status::ok();
3252}
3253
Emilian Peev8b64f282021-03-25 16:49:57 -07003254Status CameraService::notifyDisplayConfigurationChange() {
3255 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003256 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003257 const int selfPid = getpid();
3258
3259 // Permission checks
3260 if (callingPid != selfPid) {
3261 // Ensure we're being called by system_server, or similar process with
3262 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003263 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003264 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003265 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3266 " changes from pid=%d, uid=%d", callingPid, uid);
3267 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3268 "No permission to send updates to camera service about orientation"
3269 " changes from pid=%d, uid=%d", callingPid, uid);
3270 }
3271 }
3272
3273 Mutex::Autolock lock(mServiceLock);
3274
3275 // Don't do anything if rotate-and-crop override via cmd is active
3276 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3277
3278 const auto clients = mActiveClientManager.getAll();
3279 for (auto& current : clients) {
3280 if (current != nullptr) {
3281 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003282 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3283 basicClient->setRotateAndCropOverride(
3284 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3285 basicClient->getPackageName(),
3286 basicClient->getCameraFacing(),
3287 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003288 }
3289 }
3290 }
3291
3292 return Status::ok();
3293}
3294
3295Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003296 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3297 ATRACE_CALL();
3298 if (!concurrentCameraIds) {
3299 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3301 }
3302
3303 if (!mInitialized) {
3304 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003305 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003306 return STATUS_ERROR(ERROR_DISCONNECTED,
3307 "Camera subsystem is not available");
3308 }
3309 // First call into the provider and get the set of concurrent camera
3310 // combinations
3311 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003312 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003313 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003314 std::vector<std::pair<std::string, int32_t>> validCombination;
3315 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003316 for (auto &cameraId : combination) {
3317 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003318 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003319 if (state == nullptr) {
3320 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3321 continue;
3322 }
3323 StatusInternal status = state->getStatus();
3324 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3325 continue;
3326 }
Austin Borgered99f642023-06-01 16:51:35 -07003327 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003328 continue;
3329 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003330 auto [cameraOwnerDeviceId, mappedCameraId] =
3331 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3332 if (firstDeviceId == kInvalidDeviceId) {
3333 firstDeviceId = cameraOwnerDeviceId;
3334 } else if (firstDeviceId != cameraOwnerDeviceId) {
3335 // Found an invalid combination which contains cameras with different device id's,
3336 // hence discard it.
3337 validCombination.clear();
3338 break;
3339 }
3340 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003341 }
3342 if (validCombination.size() != 0) {
3343 concurrentCameraIds->push_back(std::move(validCombination));
3344 }
3345 }
3346 return Status::ok();
3347}
3348
3349Status CameraService::isConcurrentSessionConfigurationSupported(
3350 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Austin Borger65e64642024-06-11 15:58:23 -07003351 int targetSdkVersion, const AttributionSourceState& clientAttribution, int32_t devicePolicy,
Biswarup Pal7d072862024-04-17 15:24:47 +00003352 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003353 if (!isSupported) {
3354 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3355 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3356 }
3357
3358 if (!mInitialized) {
3359 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3360 return STATUS_ERROR(ERROR_DISCONNECTED,
3361 "Camera subsystem is not available");
3362 }
3363
Biswarup Pal7d072862024-04-17 15:24:47 +00003364 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3365 std::optional<std::string> cameraIdOptional =
Austin Borger65e64642024-06-11 15:58:23 -07003366 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId,
3367 clientAttribution.deviceId, devicePolicy);
Biswarup Pal7d072862024-04-17 15:24:47 +00003368 if (!cameraIdOptional.has_value()) {
3369 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Austin Borger65e64642024-06-11 15:58:23 -07003370 cameraIdAndSessionConfiguration.mCameraId.c_str(), clientAttribution.deviceId);
Biswarup Pal7d072862024-04-17 15:24:47 +00003371 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3372 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3373 }
3374 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3375 }
3376
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003377 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003378 int callingPid = getCallingPid();
3379 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003380 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003381 hasPermissionsForCamera(callingPid, callingUid,
3382 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
Austin Borger65e64642024-06-11 15:58:23 -07003383 ? kDefaultDeviceId : clientAttribution.deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003384 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003385 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3386 "android.permission.CAMERA needed to call"
3387 "isConcurrentSessionConfigurationSupported");
3388 }
3389
3390 status_t res =
3391 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003392 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3393 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003394 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003395 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003396 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003397 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3398 "support %s (%d)", strerror(-res), res);
3399 }
3400 return Status::ok();
3401}
3402
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003403Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3404 /*out*/
3405 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003406 return addListenerHelper(listener, cameraStatuses);
3407}
3408
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003409binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3410 std::vector<hardware::CameraStatus>* cameraStatuses) {
3411 return addListenerHelper(listener, cameraStatuses, false, true);
3412}
3413
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003414Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3415 /*out*/
3416 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003417 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003418 ATRACE_CALL();
3419
Igor Murashkinbfc99152013-02-27 12:55:20 -08003420 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003421
Ruben Brunk3450ba72015-06-16 11:00:37 -07003422 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003423 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003424 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003425 }
3426
Austin Borger22c5c852024-03-08 13:31:36 -08003427 auto clientPid = getCallingPid();
3428 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003429 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003430
Igor Murashkinbfc99152013-02-27 12:55:20 -08003431 Mutex::Autolock lock(mServiceLock);
3432
Ruben Brunkcc776712015-02-17 20:18:47 -08003433 {
3434 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003435 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003436 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003437 ALOGW("%s: Tried to add listener %p which was already subscribed",
3438 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003439 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003440 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003441 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003442
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003443 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003444 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3445 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003446 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003447 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003448 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003449 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003450 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3451 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3452 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003453 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003454 // The listener still needs to be added to the list of listeners, regardless of what
3455 // permissions the listener process has / whether it is a vendor listener. Since it might be
3456 // eligible to listen to other camera ids.
3457 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003458 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003459 }
3460
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003461 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003462 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003463 Mutex::Autolock lock(mCameraStatesLock);
3464 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003465 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3466 auto [deviceId, mappedCameraId] =
3467 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3468
3469 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003470 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003471 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3472 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003473 }
3474 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003475 // Remove the camera statuses that should be hidden from the client, we do
3476 // this after collecting the states in order to avoid holding
3477 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3478 // the same time.
3479 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3480 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003481 std::string cameraId = s.cameraId;
3482 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
malikakash98260df2024-05-10 23:33:57 +00003483 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM);
Biswarup Pal37a75182024-01-16 15:53:35 +00003484 if (!cameraIdOptional.has_value()) {
3485 std::string msg =
3486 fmt::sprintf(
3487 "Camera %s: Invalid camera id for device id %d",
3488 s.cameraId.c_str(), s.deviceId);
3489 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3490 return true;
3491 }
3492 cameraId = cameraIdOptional.value();
3493 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3494 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3495 ALOGE("%s: Invalid camera id %s, skipping status update",
3496 __FUNCTION__, s.cameraId.c_str());
3497 return true;
3498 }
3499 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3500 clientUid);
3501 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003502
Biswarup Pal37a75182024-01-16 15:53:35 +00003503 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003504 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003505 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003506 // Add only default device cameras here, as virtual cameras currently don't support torch
3507 // anyway. Note that this is a simplification of the implementation here, and we should
3508 // change this when virtual cameras support torch.
3509 if (s.deviceId == kDefaultDeviceId) {
3510 idsChosenForCallback.insert(s.cameraId);
3511 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003512 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003513
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003514 /*
3515 * Immediately signal current torch status to this listener only
3516 * This may be a subset of all the devices, so don't include it in the response directly
3517 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003518 {
3519 Mutex::Autolock al(mTorchStatusMutex);
3520 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003521 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003522 // The camera id is visible to the client. Fine to send torch
3523 // callback.
3524 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003525 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3526 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003527 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003528 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003529 }
3530
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003531 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003532}
Ruben Brunkcc776712015-02-17 20:18:47 -08003533
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003534Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003535 ATRACE_CALL();
3536
Igor Murashkinbfc99152013-02-27 12:55:20 -08003537 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3538
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003539 if (listener == 0) {
3540 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003541 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003542 }
3543
Igor Murashkinbfc99152013-02-27 12:55:20 -08003544 Mutex::Autolock lock(mServiceLock);
3545
Ruben Brunkcc776712015-02-17 20:18:47 -08003546 {
3547 Mutex::Autolock lock(mStatusListenerLock);
3548 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003549 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003550 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003551 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003552 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003553 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003554 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003555 }
3556 }
3557
3558 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3559 __FUNCTION__, listener.get());
3560
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003561 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003562}
3563
Austin Borgered99f642023-06-01 16:51:35 -07003564Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003565
3566 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003567 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3568
3569 if (parameters == NULL) {
3570 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003571 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003572 }
3573
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003574 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003575
3576 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003577 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003578 // Error logged by caller
3579 return ret;
3580 }
3581
3582 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003583
Austin Borgered99f642023-06-01 16:51:35 -07003584 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003585
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003586 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003587}
3588
malikakash98260df2024-05-10 23:33:57 +00003589Status CameraService::supportsCameraApi(const std::string& cameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003590 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003591 ATRACE_CALL();
3592
Austin Borgered99f642023-06-01 16:51:35 -07003593 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003594
3595 switch (apiVersion) {
3596 case API_VERSION_1:
3597 case API_VERSION_2:
3598 break;
3599 default:
Austin Borgered99f642023-06-01 16:51:35 -07003600 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3601 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3602 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003603 }
3604
Austin Borger18b30a72022-10-27 12:20:29 -07003605 int portraitRotation;
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00003606 auto deviceVersionAndTransport =
3607 getDeviceVersion(cameraId,
3608 /*rotationOverride*/hardware::ICameraService::ROTATION_OVERRIDE_NONE,
3609 &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003610 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003611 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3612 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3613 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003614 }
3615 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3616 int deviceVersion = deviceVersionAndTransport.first;
3617 switch (deviceVersion) {
3618 case CAMERA_DEVICE_API_VERSION_1_0:
3619 case CAMERA_DEVICE_API_VERSION_3_0:
3620 case CAMERA_DEVICE_API_VERSION_3_1:
3621 if (apiVersion == API_VERSION_2) {
3622 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003623 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003624 *isSupported = false;
3625 } else { // if (apiVersion == API_VERSION_1) {
3626 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003627 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003628 *isSupported = true;
3629 }
3630 break;
3631 case CAMERA_DEVICE_API_VERSION_3_2:
3632 case CAMERA_DEVICE_API_VERSION_3_3:
3633 case CAMERA_DEVICE_API_VERSION_3_4:
3634 case CAMERA_DEVICE_API_VERSION_3_5:
3635 case CAMERA_DEVICE_API_VERSION_3_6:
3636 case CAMERA_DEVICE_API_VERSION_3_7:
3637 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003638 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003639 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003640 break;
3641 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003642 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3643 deviceVersion, cameraId.c_str());
3644 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3645 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003646 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003647 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003648 } else {
3649 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003650 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003651 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003652}
3653
malikakash98260df2024-05-10 23:33:57 +00003654Status CameraService::isHiddenPhysicalCamera(const std::string& cameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003655 /*out*/ bool *isSupported) {
3656 ATRACE_CALL();
3657
Austin Borgered99f642023-06-01 16:51:35 -07003658 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3659 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003660
3661 return Status::ok();
3662}
3663
Cliff Wud8cae102021-03-11 01:37:42 +08003664Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003665 const std::string& packageName, const std::string& internalCamId,
3666 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003667 const sp<ICameraInjectionCallback>& callback,
3668 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003669 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003670 ATRACE_CALL();
3671
Austin Borgered99f642023-06-01 16:51:35 -07003672 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003673 const int pid = getCallingPid();
3674 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003675 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3676 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003677 "Permission Denial: no permission to inject camera");
3678 }
3679
3680 // Do not allow any camera injection that injects or replaces a virtual camera.
3681 auto [deviceIdForInternalCamera, _] =
3682 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3683 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3684 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3685 "Cannot replace a virtual camera");
3686 }
3687 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3688 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3689 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3690 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3691 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003692 }
3693
3694 ALOGV(
3695 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3696 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003697 __FUNCTION__, packageName.c_str(),
3698 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003699
Cliff Wud3a05312021-04-26 23:07:31 +08003700 {
3701 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003702 mInjectionInternalCamId = internalCamId;
3703 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003704 mInjectionStatusListener->addListener(callback);
3705 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003706 status_t res = NO_ERROR;
3707 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3708 // If the client already exists, we can directly connect to the camera device through the
3709 // client's injectCamera(), otherwise we need to wait until the client is established
3710 // (execute connectHelper()) before injecting the camera to the camera device.
3711 if (clientDescriptor != nullptr) {
3712 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003713 sp<BasicClient> clientSp = clientDescriptor->getValue();
3714 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3715 if(res != OK) {
3716 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3717 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003718 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003719 }
3720 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003721 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003722 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3723 }
3724 } else {
3725 mInjectionInitPending = true;
3726 }
3727 }
Cliff Wud8cae102021-03-11 01:37:42 +08003728
Cliff Wud3a05312021-04-26 23:07:31 +08003729 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003730}
3731
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003732Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003733 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003734 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3735 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3736 return Status::ok();
3737}
3738
Ruben Brunkcc776712015-02-17 20:18:47 -08003739void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003740 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003741 for (auto& i : mActiveClientManager.getAll()) {
3742 auto clientSp = i->getValue();
3743 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003744 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003745 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003746 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003747 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003748 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003749}
3750
Ruben Brunkcc776712015-02-17 20:18:47 -08003751bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003752 bool ret = false;
3753 {
3754 // Acquire mServiceLock and prevent other clients from connecting
3755 std::unique_ptr<AutoConditionLock> lock =
3756 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003757
Ruben Brunkcc776712015-02-17 20:18:47 -08003758 std::vector<sp<BasicClient>> evicted;
3759 for (auto& i : mActiveClientManager.getAll()) {
3760 auto clientSp = i->getValue();
3761 if (clientSp.get() == nullptr) {
3762 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3763 mActiveClientManager.remove(i);
3764 continue;
3765 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003766 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003767 mActiveClientManager.remove(i);
3768 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003769
Ruben Brunkcc776712015-02-17 20:18:47 -08003770 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003771 clientSp->notifyError(
3772 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003773 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003774 }
3775 }
3776
Ruben Brunkcc776712015-02-17 20:18:47 -08003777 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3778 // other clients from connecting in mServiceLockWrapper if held
3779 mServiceLock.unlock();
3780
Ruben Brunk36597b22015-03-20 22:15:57 -07003781 // Do not clear caller identity, remote caller should be client proccess
3782
Ruben Brunkcc776712015-02-17 20:18:47 -08003783 for (auto& i : evicted) {
3784 if (i.get() != nullptr) {
3785 i->disconnect();
3786 ret = true;
3787 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003788 }
3789
Ruben Brunkcc776712015-02-17 20:18:47 -08003790 // Reacquire mServiceLock
3791 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003792
Ruben Brunkcc776712015-02-17 20:18:47 -08003793 } // lock is destroyed, allow further connect calls
3794
3795 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003796}
3797
Ruben Brunkcc776712015-02-17 20:18:47 -08003798std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003799 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003800 std::shared_ptr<CameraState> state;
3801 {
3802 Mutex::Autolock lock(mCameraStatesLock);
3803 auto iter = mCameraStates.find(cameraId);
3804 if (iter != mCameraStates.end()) {
3805 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003806 }
3807 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003808 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003809}
3810
Austin Borgered99f642023-06-01 16:51:35 -07003811sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003812 // Remove from active clients list
3813 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3814 if (clientDescriptorPtr == nullptr) {
3815 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003816 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003817 return sp<BasicClient>{nullptr};
3818 }
3819
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003820 sp<BasicClient> client = clientDescriptorPtr->getValue();
3821 if (client.get() != nullptr) {
3822 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3823 }
3824 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003825}
3826
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003827void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003828 // Acquire mServiceLock and prevent other clients from connecting
3829 std::unique_ptr<AutoConditionLock> lock =
3830 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3831
Ruben Brunk6267b532015-04-30 17:44:07 -07003832 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003833 for (size_t i = 0; i < newUserIds.size(); i++) {
3834 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003835 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003836 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003837 return;
3838 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003839 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003840 }
3841
Ruben Brunka8ca9152015-04-07 14:23:40 -07003842
Ruben Brunk6267b532015-04-30 17:44:07 -07003843 if (newAllowedUsers == mAllowedUsers) {
3844 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3845 return;
3846 }
3847
3848 logUserSwitch(mAllowedUsers, newAllowedUsers);
3849
3850 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003851
3852 // Current user has switched, evict all current clients.
3853 std::vector<sp<BasicClient>> evicted;
3854 for (auto& i : mActiveClientManager.getAll()) {
3855 auto clientSp = i->getValue();
3856
3857 if (clientSp.get() == nullptr) {
3858 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3859 continue;
3860 }
3861
Ruben Brunk6267b532015-04-30 17:44:07 -07003862 // Don't evict clients that are still allowed.
3863 uid_t clientUid = clientSp->getClientUid();
3864 userid_t clientUserId = multiuser_get_user_id(clientUid);
3865 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3866 continue;
3867 }
3868
Ruben Brunk36597b22015-03-20 22:15:57 -07003869 evicted.push_back(clientSp);
3870
Ruben Brunk36597b22015-03-20 22:15:57 -07003871 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003872 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003873
Ruben Brunk36597b22015-03-20 22:15:57 -07003874 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003875 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003876 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003877 " to user switch.", i->getKey().c_str(),
3878 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003879 i->getOwnerId(), i->getPriority().getScore(),
3880 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07003881
3882 }
3883
3884 // Do not hold mServiceLock while disconnecting clients, but retain the condition
3885 // blocking other clients from connecting in mServiceLockWrapper if held.
3886 mServiceLock.unlock();
3887
3888 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08003889 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07003890
3891 for (auto& i : evicted) {
3892 i->disconnect();
3893 }
3894
Austin Borger22c5c852024-03-08 13:31:36 -08003895 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07003896
3897 // Reacquire mServiceLock
3898 mServiceLock.lock();
3899}
Ruben Brunkcc776712015-02-17 20:18:47 -08003900
Austin Borgered99f642023-06-01 16:51:35 -07003901void CameraService::logEvent(const std::string &event) {
3902 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07003903 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07003904 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07003905 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07003906 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07003907 mEventLog.add(msg);
3908 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
3909 // Error event not added to the dumpsys log before
3910 mEventLog.add(msg);
3911 sServiceErrorEventSet.insert(msg);
3912 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07003913}
3914
Austin Borgered99f642023-06-01 16:51:35 -07003915void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
3916 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003917 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003918 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3919 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003920}
3921
Austin Borgered99f642023-06-01 16:51:35 -07003922void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
3923 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003924 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003925 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
3926 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003927}
3928
Austin Borgered99f642023-06-01 16:51:35 -07003929void CameraService::logConnected(const std::string &cameraId, int clientPid,
3930 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003931 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003932 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
3933 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003934}
3935
Austin Borgered99f642023-06-01 16:51:35 -07003936void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
3937 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003938 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003939 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
3940 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08003941}
3942
Austin Borgered99f642023-06-01 16:51:35 -07003943void CameraService::logRejected(const std::string &cameraId, int clientPid,
3944 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003945 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07003946 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
3947 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003948}
3949
Austin Borgered99f642023-06-01 16:51:35 -07003950void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
3951 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003952 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07003953 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3954 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07003955}
3956
Ruben Brunk6267b532015-04-30 17:44:07 -07003957void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
3958 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07003959 std::string newUsers = toString(newUserIds);
3960 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08003961 if (oldUsers.size() == 0) {
3962 oldUsers = "<None>";
3963 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07003964 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07003965 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
3966 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003967}
3968
Austin Borgered99f642023-06-01 16:51:35 -07003969void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003970 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003971 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003972}
3973
Austin Borgered99f642023-06-01 16:51:35 -07003974void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003975 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003976 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07003977}
3978
Austin Borgered99f642023-06-01 16:51:35 -07003979void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07003980 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07003981 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07003982}
3983
Austin Borgered99f642023-06-01 16:51:35 -07003984void CameraService::logServiceError(const std::string &msg, int errorCode) {
3985 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
3986 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07003987}
3988
Ruben Brunk36597b22015-03-20 22:15:57 -07003989status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
3990 uint32_t flags) {
3991
Mathias Agopian65ab4712010-07-14 17:59:35 -07003992 // Permission checks
3993 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08003994 case SHELL_COMMAND_TRANSACTION: {
3995 int in = data.readFileDescriptor();
3996 int out = data.readFileDescriptor();
3997 int err = data.readFileDescriptor();
3998 int argc = data.readInt32();
3999 Vector<String16> args;
4000 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4001 args.add(data.readString16());
4002 }
4003 sp<IBinder> unusedCallback;
4004 sp<IResultReceiver> resultReceiver;
4005 status_t status;
4006 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4007 return status;
4008 }
4009 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4010 return status;
4011 }
4012 status = shellCommand(in, out, err, args);
4013 if (resultReceiver != nullptr) {
4014 resultReceiver->send(status);
4015 }
4016 return NO_ERROR;
4017 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004018 }
4019
4020 return BnCameraService::onTransact(code, data, reply, flags);
4021}
4022
Mathias Agopian65ab4712010-07-14 17:59:35 -07004023// We share the media players for shutter and recording sound for all clients.
4024// A reference count is kept to determine when we will actually release the
4025// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004026sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4027 sp<MediaPlayer> mp = new MediaPlayer();
4028 status_t error;
4029 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004030 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004031 error = mp->prepare();
4032 }
4033 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004034 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004035 mp->disconnect();
4036 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004037 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004038 }
4039 return mp;
4040}
4041
username5755fea2018-12-27 09:48:08 +08004042void CameraService::increaseSoundRef() {
4043 Mutex::Autolock lock(mSoundLock);
4044 mSoundRef++;
4045}
4046
4047void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004048 ATRACE_CALL();
4049
username5755fea2018-12-27 09:48:08 +08004050 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4051 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4052 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4053 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4054 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4055 }
4056 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4057 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4058 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4059 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004060 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004061 }
4062 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4063 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4064 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4065 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4066 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004067 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004068}
4069
username5755fea2018-12-27 09:48:08 +08004070void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004071 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004072 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004073 if (--mSoundRef) return;
4074
4075 for (int i = 0; i < NUM_SOUNDS; i++) {
4076 if (mSoundPlayer[i] != 0) {
4077 mSoundPlayer[i]->disconnect();
4078 mSoundPlayer[i].clear();
4079 }
4080 }
4081}
4082
4083void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004084 ATRACE_CALL();
4085
Mathias Agopian65ab4712010-07-14 17:59:35 -07004086 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004087 if (kind < 0 || kind >= NUM_SOUNDS) {
4088 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4089 return;
4090 }
4091
Mathias Agopian65ab4712010-07-14 17:59:35 -07004092 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004093 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004094 sp<MediaPlayer> player = mSoundPlayer[kind];
4095 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004096 player->seekTo(0);
4097 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004098 }
4099}
4100
4101// ----------------------------------------------------------------------------
4102
4103CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004104 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004105 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004106 const std::string& clientPackageName, bool systemNativeClient,
4107 const std::optional<std::string>& clientFeatureId,
4108 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004109 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004110 int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004111 int servicePid, int rotationOverride) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004112 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004113 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004114 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004115 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004116 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004117 clientPid, clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004118 servicePid, rotationOverride),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004119 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004120{
Austin Borger22c5c852024-03-08 13:31:36 -08004121 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004122 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004123
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004124 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004125
username5755fea2018-12-27 09:48:08 +08004126 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004127
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004128 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004129}
4130
Mathias Agopian65ab4712010-07-14 17:59:35 -07004131// tear down the client
4132CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004133 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004134 mDestructionStarted = true;
4135
username5755fea2018-12-27 09:48:08 +08004136 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004137 // unconditionally disconnect. function is idempotent
4138 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004139}
4140
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004141sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4142
Igor Murashkin634a5152013-02-20 17:15:11 -08004143CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004144 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004145 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004146 const std::string& clientPackageName, bool nativeClient,
4147 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004148 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004149 int servicePid, int rotationOverride):
Austin Borger249e6592024-03-10 22:28:11 -07004150 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004151 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004152 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004153 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4154 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004155 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004156 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004157 mDisconnected(false), mUidIsTrusted(false),
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00004158 mRotationOverride(rotationOverride),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004159 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004160 mRemoteBinder(remoteCallback),
4161 mOpsActive(false),
4162 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004163{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004164 if (sCameraService == nullptr) {
4165 sCameraService = cameraService;
4166 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004167
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004168 // There are 2 scenarios in which a client won't have AppOps operations
4169 // (both scenarios : native clients)
4170 // 1) It's an system native client*, the package name will be empty
4171 // and it will return from this function in the previous if condition
4172 // (This is the same as the previously existing behavior).
4173 // 2) It is a system native client, but its package name has been
4174 // modified for debugging, however it still must not use AppOps since
4175 // the package name is not a real one.
4176 //
4177 // * system native client - native client with UID < AID_APP_START. It
4178 // doesn't exclude clients not on the system partition.
4179 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004180 mAppOpsManager = std::make_unique<AppOpsManager>();
4181 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004182
Charles Chenf075f082024-03-04 23:32:55 +00004183 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004184}
4185
4186CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004187 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004188 mDestructionStarted = true;
4189}
4190
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004191binder::Status CameraService::BasicClient::disconnect() {
4192 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004193 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004194 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004195 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004196 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004197
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004198 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004199 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004200 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004201 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004202
4203 sp<IBinder> remote = getRemote();
4204 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004205 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004206 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004207
4208 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004209 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004210 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004211 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004212 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004213
Igor Murashkincba2c162013-03-20 15:56:31 -07004214 // client shouldn't be able to call into us anymore
4215 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004216
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004217 const auto& mActivityManager = getActivityManager();
4218 if (mActivityManager) {
4219 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004220 getCallingUid(),
4221 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004222 }
4223
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004224 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004225}
4226
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004227status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4228 // No dumping of clients directly over Binder,
4229 // must go through CameraService::dump
4230 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004231 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004232 return OK;
4233}
4234
Austin Borgered99f642023-06-01 16:51:35 -07004235status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004236 // Can't watch tags directly, must go through CameraService::startWatchingTags
4237 return OK;
4238}
4239
4240status_t CameraService::BasicClient::stopWatchingTags(int) {
4241 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4242 return OK;
4243}
4244
4245status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4246 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4247 return OK;
4248}
4249
Austin Borgered99f642023-06-01 16:51:35 -07004250std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004251 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004252}
4253
Emilian Peev8b64f282021-03-25 16:49:57 -07004254int CameraService::BasicClient::getCameraFacing() const {
4255 return mCameraFacing;
4256}
4257
4258int CameraService::BasicClient::getCameraOrientation() const {
4259 return mOrientation;
4260}
Ruben Brunkcc776712015-02-17 20:18:47 -08004261
4262int CameraService::BasicClient::getClientPid() const {
4263 return mClientPid;
4264}
4265
Ruben Brunk6267b532015-04-30 17:44:07 -07004266uid_t CameraService::BasicClient::getClientUid() const {
4267 return mClientUid;
4268}
4269
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004270bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4271 // Defaults to API2.
4272 return level == API_2;
4273}
4274
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004275status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004276 {
4277 Mutex::Autolock l(mAudioRestrictionLock);
4278 mAudioRestriction = mode;
4279 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004280 sCameraService->updateAudioRestriction();
4281 return OK;
4282}
4283
4284int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004285 return sCameraService->updateAudioRestriction();
4286}
4287
4288int32_t CameraService::BasicClient::getAudioRestriction() const {
4289 Mutex::Autolock l(mAudioRestrictionLock);
4290 return mAudioRestriction;
4291}
4292
4293bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4294 switch (mode) {
4295 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4296 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4297 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4298 return true;
4299 default:
4300 return false;
4301 }
4302}
4303
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004304status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4305 if (mode == AppOpsManager::MODE_ERRORED) {
4306 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004307 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004308 return PERMISSION_DENIED;
4309 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4310 // If the calling Uid is trusted (a native service), the AppOpsManager could
4311 // return MODE_IGNORED. Do not treat such case as error.
4312 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4313 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004314
4315 bool isCameraPrivacyEnabled;
4316 if (flags::camera_privacy_allowlist()) {
4317 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4318 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4319 } else {
4320 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004321 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004322 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004323 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4324 // We prefer to successfully open the camera and perform camera muting
4325 // or blocking in connectHelper as handleAppOpMode can be called before the
4326 // connection has been fully established and at that time camera muting
4327 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004328 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004329 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4330 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4331 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4332 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004333 // Return the same error as for device policy manager rejection
4334 return -EACCES;
4335 }
4336 }
4337 return OK;
4338}
4339
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004340status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004341 ATRACE_CALL();
4342
Igor Murashkine6800ce2013-03-04 17:25:57 -08004343 {
4344 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004345 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004346 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004347 if (mAppOpsManager != nullptr) {
4348 // Notify app ops that the camera is not available
4349 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004350
Austin Borger5755d9b2024-09-09 11:15:44 -07004351 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4352 toString16(mClientPackageName),
4353 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004354
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004355 // Just check for camera acccess here on open - delay startOp until
4356 // camera frames start streaming in startCameraStreamingOps
4357 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004358 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004359 status_t res = handleAppOpMode(mode);
4360 if (res != OK) {
4361 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004362 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004363 }
4364
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004365 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004366
4367 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004368 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004369
Austin Borgerdddb7552023-03-30 17:53:01 -07004370 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004371
Shuzhen Wang695044d2020-03-06 09:02:23 -08004372 // Notify listeners of camera open/close status
4373 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4374
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004375 return OK;
4376}
4377
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004378status_t CameraService::BasicClient::startCameraStreamingOps() {
4379 ATRACE_CALL();
4380
4381 if (!mOpsActive) {
4382 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4383 return INVALID_OPERATION;
4384 }
4385 if (mOpsStreaming) {
4386 ALOGV("%s: Streaming already active!", __FUNCTION__);
4387 return OK;
4388 }
4389
4390 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004391 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004392
4393 if (mAppOpsManager != nullptr) {
4394 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004395 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4396 toString16(mClientFeatureId),
4397 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004398 status_t res = handleAppOpMode(mode);
4399 if (res != OK) {
4400 return res;
4401 }
4402 }
4403
4404 mOpsStreaming = true;
4405
4406 return OK;
4407}
4408
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004409status_t CameraService::BasicClient::noteAppOp() {
4410 ATRACE_CALL();
4411
4412 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004413 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004414
4415 // noteAppOp is only used for when camera mute is not supported, in order
4416 // to trigger the sensor privacy "Unblock" dialog
4417 if (mAppOpsManager != nullptr) {
4418 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004419 toString16(mClientPackageName), toString16(mClientFeatureId),
4420 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004421 status_t res = handleAppOpMode(mode);
4422 if (res != OK) {
4423 return res;
4424 }
4425 }
4426
4427 return OK;
4428}
4429
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004430status_t CameraService::BasicClient::finishCameraStreamingOps() {
4431 ATRACE_CALL();
4432
4433 if (!mOpsActive) {
4434 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4435 return INVALID_OPERATION;
4436 }
4437 if (!mOpsStreaming) {
4438 ALOGV("%s: Streaming not active!", __FUNCTION__);
4439 return OK;
4440 }
4441
4442 if (mAppOpsManager != nullptr) {
4443 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004444 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004445 mOpsStreaming = false;
4446 }
4447
4448 return OK;
4449}
4450
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004451status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004452 ATRACE_CALL();
4453
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004454 if (mOpsStreaming) {
4455 // Make sure we've notified everyone about camera stopping
4456 finishCameraStreamingOps();
4457 }
4458
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004459 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004460 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004461 mOpsActive = false;
4462
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004463 // This function is called when a client disconnects. This should
4464 // release the camera, but actually only if it was in a proper
4465 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004466 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004467 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004468
Ruben Brunkcc776712015-02-17 20:18:47 -08004469 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004470 sCameraService->updateStatus(StatusInternal::PRESENT,
4471 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004472 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004473 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004474 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4475 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004476 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004477 mOpsCallback.clear();
4478
Austin Borgerdddb7552023-03-30 17:53:01 -07004479 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004480
Shuzhen Wang695044d2020-03-06 09:02:23 -08004481 // Notify listeners of camera open/close status
4482 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4483
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004484 return OK;
4485}
4486
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004487void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004488 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004489 if (mAppOpsManager == nullptr) {
4490 return;
4491 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004492 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004493 if (op != AppOpsManager::OP_CAMERA) {
4494 ALOGW("Unexpected app ops notification received: %d", op);
4495 return;
4496 }
4497
4498 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004499 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004500 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004501 ALOGV("checkOp returns: %d, %s ", res,
4502 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4503 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4504 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4505 "UNKNOWN");
4506
Shuzhen Wang64900852021-02-05 09:03:29 -08004507 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004508 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4509 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004510 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004511 } else if (res == AppOpsManager::MODE_IGNORED) {
4512 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004513
Austin Borgerca1e0062023-06-28 11:32:55 -07004514 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4515 // If not visible, but still active, then we want to block instead of muting the camera.
4516 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4517 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4518
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004519 bool isCameraPrivacyEnabled;
4520 if (flags::camera_privacy_allowlist()) {
4521 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4522 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4523 } else {
4524 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004525 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004526 }
4527
4528 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004529 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4530 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4531 isCameraPrivacyEnabled);
4532 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4533 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4534 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004535 if (!mUidIsTrusted) {
Austin Borger5755d9b2024-09-09 11:15:44 -07004536 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4537 setCameraMute(true);
Austin Borgerca1e0062023-06-28 11:32:55 -07004538 } else {
Austin Borger5755d9b2024-09-09 11:15:44 -07004539 block();
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004540 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004541 }
Evan Severson09ab4002021-02-10 14:15:19 -08004542 } else if (res == AppOpsManager::MODE_ALLOWED) {
4543 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004544 }
4545}
4546
Svet Ganova453d0d2018-01-11 15:37:58 -08004547void CameraService::BasicClient::block() {
4548 ATRACE_CALL();
4549
4550 // Reset the client PID to allow server-initiated disconnect,
4551 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004552 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004553 CaptureResultExtras resultExtras; // a dummy result (invalid)
4554 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4555 disconnect();
4556}
4557
Mathias Agopian65ab4712010-07-14 17:59:35 -07004558// ----------------------------------------------------------------------------
4559
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004560void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004561 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004562 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004563 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4564 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4565 api1ErrorCode = CAMERA_ERROR_DISABLED;
4566 }
4567 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004568 } else {
4569 ALOGE("mRemoteCallback is NULL!!");
4570 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004571}
4572
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004573// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004574binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004575 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004576 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004577}
4578
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004579bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4580 return level == API_1;
4581}
4582
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004583CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4584 mClient(client) {
4585}
4586
4587void CameraService::Client::OpsCallback::opChanged(int32_t op,
4588 const String16& packageName) {
4589 sp<BasicClient> client = mClient.promote();
4590 if (client != NULL) {
4591 client->opChanged(op, packageName);
4592 }
4593}
4594
Mathias Agopian65ab4712010-07-14 17:59:35 -07004595// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004596// UidPolicy
4597// ----------------------------------------------------------------------------
4598
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004599void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004600 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004601 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004602
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004603 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004604 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004605 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004606 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004607 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4608 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004609 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004610 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004611 if (res == OK) {
4612 mRegistered = true;
4613 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004614 } else {
4615 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004616 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004617}
4618
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004619void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004620 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004621 return;
4622 }
4623
4624 registerWithActivityManager();
4625}
4626
4627void CameraService::UidPolicy::registerSelf() {
4628 // Use check service to see if the activity service is available
4629 // If not available then register for notifications, instead of blocking
4630 // till the service is ready
4631 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004632 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004633 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004634 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004635 } else {
4636 registerWithActivityManager();
4637 }
4638}
4639
Svet Ganova453d0d2018-01-11 15:37:58 -08004640void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004641 Mutex::Autolock _l(mUidLock);
4642
Steven Moreland2f348142019-07-02 15:59:07 -07004643 mAm.unregisterUidObserver(this);
4644 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004645 mRegistered = false;
4646 mActiveUids.clear();
4647 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004648}
4649
4650void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4651 onUidIdle(uid, disabled);
4652}
4653
4654void CameraService::UidPolicy::onUidActive(uid_t uid) {
4655 Mutex::Autolock _l(mUidLock);
4656 mActiveUids.insert(uid);
4657}
4658
4659void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4660 bool deleted = false;
4661 {
4662 Mutex::Autolock _l(mUidLock);
4663 if (mActiveUids.erase(uid) > 0) {
4664 deleted = true;
4665 }
4666 }
4667 if (deleted) {
4668 sp<CameraService> service = mService.promote();
4669 if (service != nullptr) {
4670 service->blockClientsForUid(uid);
4671 }
4672 }
4673}
4674
Emilian Peev53722fa2019-02-22 17:47:20 -08004675void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004676 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004677 bool procStateChange = false;
4678 {
4679 Mutex::Autolock _l(mUidLock);
4680 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4681 mMonitoredUids[uid].procState != procState) {
4682 mMonitoredUids[uid].procState = procState;
4683 procStateChange = true;
4684 }
4685 }
4686
4687 if (procStateChange) {
4688 sp<CameraService> service = mService.promote();
4689 if (service != nullptr) {
4690 service->notifyMonitoredUids();
4691 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004692 }
4693}
4694
Austin Borgerdddb7552023-03-30 17:53:01 -07004695/**
4696 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4697 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4698 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4699 * monitoredUids. If it is revised above some other monitoredUid, signal
4700 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4701 * foreground apps in split screen - state changes will capture all other cases.
4702 */
4703void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4704 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004705 {
4706 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004707 auto it = mMonitoredUids.find(uid);
4708
4709 if (it != mMonitoredUids.end()) {
4710 if (it->second.hasCamera) {
4711 for (auto &monitoredUid : mMonitoredUids) {
4712 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004713 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004714 notifyUidSet.emplace(monitoredUid.first);
4715 }
4716 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004717 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004718 notifyUidSet.emplace(uid);
4719 } else {
4720 for (auto &monitoredUid : mMonitoredUids) {
4721 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004722 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004723 notifyUidSet.emplace(uid);
4724 }
4725 }
4726 }
4727 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004728 }
4729 }
4730
Austin Borgerdddb7552023-03-30 17:53:01 -07004731 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004732 sp<CameraService> service = mService.promote();
4733 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004734 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004735 }
4736 }
4737}
4738
Austin Borgerdddb7552023-03-30 17:53:01 -07004739/**
4740 * Register a uid for monitoring, and note whether it owns a camera.
4741 */
4742void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
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++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004747 } else {
Austin Borger65577682022-02-17 00:25:43 +00004748 MonitoredUid monitoredUid;
4749 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004750 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004751 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004752 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004753 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004754 if (res != OK) {
4755 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4756 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004757 }
4758
4759 if (openCamera) {
4760 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004761 }
4762}
4763
Austin Borgerdddb7552023-03-30 17:53:01 -07004764/**
4765 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4766 */
4767void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004768 Mutex::Autolock _l(mUidLock);
4769 auto it = mMonitoredUids.find(uid);
4770 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004771 it->second.refCount--;
4772 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004773 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004774 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004775 if (res != OK) {
4776 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4777 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004778 } else if (closeCamera) {
4779 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004780 }
4781 } else {
4782 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4783 }
4784}
4785
Austin Borgered99f642023-06-01 16:51:35 -07004786bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004787 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004788 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004789}
4790
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004791static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4792static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004793
Austin Borgered99f642023-06-01 16:51:35 -07004794bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004795 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004796 // If activity manager is unreachable, assume everything is active
4797 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004798 return true;
4799 }
4800 auto it = mOverrideUids.find(uid);
4801 if (it != mOverrideUids.end()) {
4802 return it->second;
4803 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004804 bool active = mActiveUids.find(uid) != mActiveUids.end();
4805 if (!active) {
4806 // We want active UIDs to always access camera with their first attempt since
4807 // there is no guarantee the app is robustly written and would retry getting
4808 // the camera on failure. The inverse case is not a problem as we would take
4809 // camera away soon once we get the callback that the uid is no longer active.
4810 ActivityManager am;
4811 // Okay to access with a lock held as UID changes are dispatched without
4812 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004813 int64_t startTimeMillis = 0;
4814 do {
4815 // TODO: Fix this b/109950150!
4816 // Okay this is a hack. There is a race between the UID turning active and
4817 // activity being resumed. The proper fix is very risky, so we temporary add
4818 // some polling which should happen pretty rarely anyway as the race is hard
4819 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004820 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004821 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004822 if (active) {
4823 break;
4824 }
4825 if (startTimeMillis <= 0) {
4826 startTimeMillis = uptimeMillis();
4827 }
4828 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004829 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004830 if (remainingTimeMillis <= 0) {
4831 break;
4832 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004833 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4834
4835 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004836 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004837 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004838 } while (true);
4839
Svet Ganov7b4ab782018-03-25 12:48:10 -07004840 if (active) {
4841 // Now that we found out the UID is actually active, cache that
4842 mActiveUids.insert(uid);
4843 }
4844 }
4845 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004846}
4847
Varun Shahb42f1eb2019-04-16 14:45:13 -07004848int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4849 Mutex::Autolock _l(mUidLock);
4850 return getProcStateLocked(uid);
4851}
4852
4853int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4854 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4855 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004856 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004857 }
4858 return procState;
4859}
4860
Austin Borgered99f642023-06-01 16:51:35 -07004861void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4862 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004863 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004864}
4865
Austin Borgered99f642023-06-01 16:51:35 -07004866void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004867 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08004868}
4869
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004870void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
4871 Mutex::Autolock _l(mUidLock);
4872 ALOGV("UidPolicy: ActivityManager has died");
4873 mRegistered = false;
4874 mActiveUids.clear();
4875}
4876
Austin Borgered99f642023-06-01 16:51:35 -07004877void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07004878 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004879 bool wasActive = false;
4880 bool isActive = false;
4881 {
4882 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004883 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004884 mOverrideUids.erase(uid);
4885 if (insert) {
4886 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
4887 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004888 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004889 }
4890 if (wasActive != isActive && !isActive) {
4891 sp<CameraService> service = mService.promote();
4892 if (service != nullptr) {
4893 service->blockClientsForUid(uid);
4894 }
4895 }
4896}
4897
4898// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08004899// SensorPrivacyPolicy
4900// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004901
4902void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
4903{
Michael Grooverd1d435a2018-12-18 17:39:42 -08004904 Mutex::Autolock _l(mSensorPrivacyLock);
4905 if (mRegistered) {
4906 return;
4907 }
Evan Severson09ab4002021-02-10 14:15:19 -08004908 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08004909 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004910 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004911 mSpm.addToggleSensorPrivacyListener(this);
4912 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004913 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004914 if (flags::camera_privacy_allowlist()) {
4915 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
4916 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
4917 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
4918 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004919 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004920 if (res == OK) {
4921 mRegistered = true;
4922 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
4923 }
4924}
4925
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004926void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
4927 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004928 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004929 return;
4930 }
4931
4932 registerWithSensorPrivacyManager();
4933}
4934
4935void CameraService::SensorPrivacyPolicy::registerSelf() {
4936 // Use checkservice to see if the sensor_privacy service is available
4937 // If service is not available then register for notification
4938 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004939 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004940 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004941 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004942 } else {
4943 registerWithSensorPrivacyManager();
4944 }
4945}
4946
Michael Grooverd1d435a2018-12-18 17:39:42 -08004947void CameraService::SensorPrivacyPolicy::unregisterSelf() {
4948 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08004949 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00004950 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004951 mSpm.removeToggleSensorPrivacyListener(this);
4952 }
Steven Moreland3cf67172020-01-29 11:44:22 -08004953 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08004954 mRegistered = false;
4955 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
4956}
4957
4958bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004959 if (!mRegistered) {
4960 registerWithSensorPrivacyManager();
4961 }
4962
Michael Grooverd1d435a2018-12-18 17:39:42 -08004963 Mutex::Autolock _l(mSensorPrivacyLock);
4964 return mSensorPrivacyEnabled;
4965}
4966
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004967int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
4968 if (!mRegistered) {
4969 registerWithSensorPrivacyManager();
4970 }
4971
4972 Mutex::Autolock _l(mSensorPrivacyLock);
4973 return mCameraPrivacyState;
4974}
4975
Evan Seversond0b69922022-01-27 10:47:34 -08004976bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08004977 if (!hasCameraPrivacyFeature()) {
4978 return false;
4979 }
Evan Seversond0b69922022-01-27 10:47:34 -08004980 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08004981}
4982
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004983bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
4984 if (!hasCameraPrivacyFeature()) {
Jyoti Bhayana5882b032024-04-26 11:18:58 -07004985 return false;
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004986 }
4987 return mSpm.isCameraPrivacyEnabled(packageName);
4988}
4989
Evan Seversond0b69922022-01-27 10:47:34 -08004990binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004991 int toggleType, int sensor, bool enabled) {
4992 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
4993 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
4994 {
4995 Mutex::Autolock _l(mSensorPrivacyLock);
4996 mSensorPrivacyEnabled = enabled;
4997 }
4998 // if sensor privacy is enabled then block all clients from accessing the camera
4999 if (enabled) {
5000 sp<CameraService> service = mService.promote();
5001 if (service != nullptr) {
5002 service->blockAllClients();
5003 }
5004 }
5005 }
5006 return binder::Status::ok();
5007}
5008
5009binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5010 int, int sensor, int state) {
5011 if (!flags::camera_privacy_allowlist()
5012 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5013 return binder::Status::ok();
5014 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005015 {
5016 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005017 mCameraPrivacyState = state;
5018 }
5019 sp<CameraService> service = mService.promote();
5020 if (!service) {
5021 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005022 }
5023 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005024 if (state == SensorPrivacyManager::ENABLED) {
5025 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005026 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005027 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005028 }
5029 return binder::Status::ok();
5030}
5031
5032void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5033 Mutex::Autolock _l(mSensorPrivacyLock);
5034 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5035 mRegistered = false;
5036}
5037
Evan Severson09ab4002021-02-10 14:15:19 -08005038bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005039 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5040 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5041 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5042 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5043 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005044}
5045
Michael Grooverd1d435a2018-12-18 17:39:42 -08005046// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005047// CameraState
5048// ----------------------------------------------------------------------------
5049
Austin Borgered99f642023-06-01 16:51:35 -07005050CameraService::CameraState::CameraState(const std::string& id, int cost,
5051 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005052 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005053 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005054 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005055
5056CameraService::CameraState::~CameraState() {}
5057
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005058CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005059 Mutex::Autolock lock(mStatusLock);
5060 return mStatus;
5061}
5062
Austin Borgered99f642023-06-01 16:51:35 -07005063std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005064 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005065 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005066 return res;
5067}
5068
Ruben Brunkcc776712015-02-17 20:18:47 -08005069CameraParameters CameraService::CameraState::getShimParams() const {
5070 return mShimParams;
5071}
5072
5073void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5074 mShimParams = params;
5075}
5076
5077int CameraService::CameraState::getCost() const {
5078 return mCost;
5079}
5080
Austin Borgered99f642023-06-01 16:51:35 -07005081std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005082 return mConflicting;
5083}
5084
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005085SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5086 return mSystemCameraKind;
5087}
5088
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005089bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5090 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5091 != mPhysicalCameras.end();
5092}
5093
Austin Borgered99f642023-06-01 16:51:35 -07005094bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005095 Mutex::Autolock lock(mStatusLock);
5096 auto result = mUnavailablePhysicalIds.insert(physicalId);
5097 return result.second;
5098}
5099
Austin Borgered99f642023-06-01 16:51:35 -07005100bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005101 Mutex::Autolock lock(mStatusLock);
5102 auto count = mUnavailablePhysicalIds.erase(physicalId);
5103 return count > 0;
5104}
5105
Austin Borgered99f642023-06-01 16:51:35 -07005106void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005107 Mutex::Autolock lock(mStatusLock);
5108 mClientPackage = clientPackage;
5109}
5110
Austin Borgered99f642023-06-01 16:51:35 -07005111std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005112 Mutex::Autolock lock(mStatusLock);
5113 return mClientPackage;
5114}
5115
Ruben Brunkcc776712015-02-17 20:18:47 -08005116// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005117// ClientEventListener
5118// ----------------------------------------------------------------------------
5119
5120void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005121 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005122 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005123 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005124 if (basicClient.get() != nullptr) {
5125 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005126 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005127 static_cast<int>(basicClient->getClientUid()));
5128 }
5129}
5130
5131void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005132 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005133 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005134 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005135 if (basicClient.get() != nullptr) {
5136 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005137 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005138 static_cast<int>(basicClient->getClientUid()));
5139 }
5140}
5141
Ruben Brunk99e69712015-05-26 17:25:07 -07005142// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005143// CameraClientManager
5144// ----------------------------------------------------------------------------
5145
Ruben Brunk99e69712015-05-26 17:25:07 -07005146CameraService::CameraClientManager::CameraClientManager() {
5147 setListener(std::make_shared<ClientEventListener>());
5148}
5149
Ruben Brunkcc776712015-02-17 20:18:47 -08005150CameraService::CameraClientManager::~CameraClientManager() {}
5151
5152sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005153 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005154 auto descriptor = get(id);
5155 if (descriptor == nullptr) {
5156 return sp<BasicClient>{nullptr};
5157 }
5158 return descriptor->getValue();
5159}
5160
Austin Borgered99f642023-06-01 16:51:35 -07005161std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005162 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005163 std::ostringstream ret;
5164 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005165 bool hasAny = false;
5166 for (auto& i : all) {
5167 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005168 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005169 int32_t cost = i->getCost();
5170 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005171 int32_t score = i->getPriority().getScore();
5172 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005173 auto conflicting = i->getConflicting();
5174 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005175 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005176 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005177 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005178 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005179 uid_t clientUid = clientSp->getClientUid();
5180 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005181 }
Austin Borgered99f642023-06-01 16:51:35 -07005182 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5183 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005184
Ruben Brunk6267b532015-04-30 17:44:07 -07005185 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005186 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005187 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005188 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005189 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005190 }
5191
Austin Borgered99f642023-06-01 16:51:35 -07005192 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005193 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005194 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005195 }
Austin Borgered99f642023-06-01 16:51:35 -07005196 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005197 }
Austin Borgered99f642023-06-01 16:51:35 -07005198 if (hasAny) ret << "\n";
5199 ret << "]\n";
Yi Kong3ac211f2024-08-12 07:31:44 +08005200 return ret.str();
Ruben Brunkcc776712015-02-17 20:18:47 -08005201}
5202
5203CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005204 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5205 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005206 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005207
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005208 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005209 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005210
Austin Borgered99f642023-06-01 16:51:35 -07005211 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005212 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5213 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005214}
5215
5216CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005217 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005218 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005219 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005220 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005221 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5222 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005223}
5224
5225// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005226// InjectionStatusListener
5227// ----------------------------------------------------------------------------
5228
5229void CameraService::InjectionStatusListener::addListener(
5230 const sp<ICameraInjectionCallback>& callback) {
5231 Mutex::Autolock lock(mListenerLock);
5232 if (mCameraInjectionCallback) return;
5233 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5234 if (res == OK) {
5235 mCameraInjectionCallback = callback;
5236 }
5237}
5238
5239void CameraService::InjectionStatusListener::removeListener() {
5240 Mutex::Autolock lock(mListenerLock);
5241 if (mCameraInjectionCallback == nullptr) {
5242 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5243 return;
5244 }
5245 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5246 mCameraInjectionCallback = nullptr;
5247}
5248
5249void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005250 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005251 if (mCameraInjectionCallback == nullptr) {
5252 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5253 return;
5254 }
Cliff Wud3a05312021-04-26 23:07:31 +08005255
5256 switch (err) {
5257 case -ENODEV:
5258 mCameraInjectionCallback->onInjectionError(
5259 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5260 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005261 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005262 break;
5263 case -EBUSY:
5264 mCameraInjectionCallback->onInjectionError(
5265 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5266 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005267 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005268 break;
5269 case DEAD_OBJECT:
5270 mCameraInjectionCallback->onInjectionError(
5271 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5272 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005273 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005274 break;
5275 case INVALID_OPERATION:
5276 mCameraInjectionCallback->onInjectionError(
5277 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5278 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005279 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005280 break;
5281 case UNKNOWN_TRANSACTION:
5282 mCameraInjectionCallback->onInjectionError(
5283 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5284 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005285 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005286 break;
5287 default:
5288 mCameraInjectionCallback->onInjectionError(
5289 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5290 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005291 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005292 }
Cliff Wud8cae102021-03-11 01:37:42 +08005293}
5294
5295void CameraService::InjectionStatusListener::binderDied(
5296 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005297 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5298 auto parent = mParent.promote();
5299 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005300 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5301 if (clientDescriptor != nullptr) {
5302 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5303 baseClientPtr->stopInjection();
5304 }
Cliff Wu3b268182021-07-06 15:44:43 +08005305 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005306 }
5307}
5308
5309// ----------------------------------------------------------------------------
5310// CameraInjectionSession
5311// ----------------------------------------------------------------------------
5312
5313binder::Status CameraService::CameraInjectionSession::stopInjection() {
5314 Mutex::Autolock lock(mInjectionSessionLock);
5315 auto parent = mParent.promote();
5316 if (parent == nullptr) {
5317 ALOGE("CameraInjectionSession: Parent is gone");
5318 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5319 "Camera service encountered error");
5320 }
Cliff Wud3a05312021-04-26 23:07:31 +08005321
5322 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005323 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5324 if (clientDescriptor != nullptr) {
5325 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5326 res = baseClientPtr->stopInjection();
5327 if (res != OK) {
5328 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5329 " ret != NO_ERROR: %d", res);
5330 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5331 "Camera session encountered error");
5332 }
5333 }
Cliff Wu3b268182021-07-06 15:44:43 +08005334 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005335 return binder::Status::ok();
5336}
5337
5338// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005339
5340static const int kDumpLockRetries = 50;
5341static const int kDumpLockSleep = 60000;
5342
5343static bool tryLock(Mutex& mutex)
5344{
5345 bool locked = false;
5346 for (int i = 0; i < kDumpLockRetries; ++i) {
5347 if (mutex.tryLock() == NO_ERROR) {
5348 locked = true;
5349 break;
5350 }
5351 usleep(kDumpLockSleep);
5352 }
5353 return locked;
5354}
5355
Rucha Katakwardf223072021-06-15 10:21:00 -07005356void CameraService::cacheDump() {
5357 if (mMemFd != -1) {
5358 const Vector<String16> args;
5359 ATRACE_CALL();
5360 // Acquiring service lock here will avoid the deadlock since
5361 // cacheDump will not be called during the second disconnect.
5362 Mutex::Autolock lock(mServiceLock);
5363
5364 Mutex::Autolock l(mCameraStatesLock);
5365 // Start collecting the info for open sessions and store it in temp file.
5366 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005367 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005368 auto clientDescriptor = mActiveClientManager.get(cameraId);
5369 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005370 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005371 // Log the current open session info before device is disconnected.
5372 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5373 }
5374 }
5375 }
5376}
5377
Mathias Agopian65ab4712010-07-14 17:59:35 -07005378status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005379 ATRACE_CALL();
5380
Austin Borgered99f642023-06-01 16:51:35 -07005381 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005382 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005383 getCallingPid(),
5384 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005385 return NO_ERROR;
5386 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005387 bool locked = tryLock(mServiceLock);
5388 // failed to lock - CameraService is probably deadlocked
5389 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005390 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005391 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005392
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005393 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005394 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005395
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005396 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005397 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005398
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005399 if (locked) mServiceLock.unlock();
5400 return NO_ERROR;
5401 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005402 dprintf(fd, "\n== Service global info: ==\n\n");
5403 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005404 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005405 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5406 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005407 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5408 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5409 }
Austin Borgered99f642023-06-01 16:51:35 -07005410 std::string activeClientString = mActiveClientManager.toString();
5411 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5412 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005413 if (mStreamUseCaseOverrides.size() > 0) {
5414 dprintf(fd, "Active stream use case overrides:");
5415 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5416 dprintf(fd, " %" PRId64, useCaseOverride);
5417 }
5418 dprintf(fd, "\n");
5419 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005420
5421 dumpEventLog(fd);
5422
5423 bool stateLocked = tryLock(mCameraStatesLock);
5424 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005425 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005426 }
5427
Emilian Peevbd8c5032018-02-14 23:05:40 +00005428 int argSize = args.size();
5429 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005430 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005431 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005432 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005433 }
5434 break;
5435 }
5436 }
5437
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005438 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005439 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005440
Austin Borgered99f642023-06-01 16:51:35 -07005441 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005442
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005443 CameraParameters p = state.second->getShimParams();
5444 if (!p.isEmpty()) {
5445 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5446 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005447 }
5448
5449 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005450 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005451 // log the current open session info
5452 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005453 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005454 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005455 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005456
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005457 }
5458
5459 if (stateLocked) mCameraStatesLock.unlock();
5460
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005461 if (locked) mServiceLock.unlock();
5462
Emilian Peevf53f66e2017-04-11 14:29:43 +01005463 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005464
5465 dprintf(fd, "\n== Vendor tags: ==\n\n");
5466
5467 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5468 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005469 sp<VendorTagDescriptorCache> cache =
5470 VendorTagDescriptorCache::getGlobalVendorTagCache();
5471 if (cache == NULL) {
5472 dprintf(fd, "No vendor tags.\n");
5473 } else {
5474 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5475 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005476 } else {
5477 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5478 }
5479
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005480 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005481 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005482 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005483
5484 // Process dump arguments, if any
5485 int n = args.size();
5486 String16 verboseOption("-v");
5487 String16 unreachableOption("--unreachable");
5488 for (int i = 0; i < n; i++) {
5489 if (args[i] == verboseOption) {
5490 // change logging level
5491 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005492 std::string levelStr = toStdString(args[i+1]);
5493 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005494 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005495 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005496 } else if (args[i] == unreachableOption) {
5497 // Dump memory analysis
5498 // TODO - should limit be an argument parameter?
5499 UnreachableMemoryInfo info;
5500 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5501 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005502 dprintf(fd, "\n== Unable to dump unreachable memory. "
5503 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005504 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005505 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005506 std::string s = info.ToString(/*log_contents*/ true);
5507 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005508 }
5509 }
5510 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005511
5512 bool serviceLocked = tryLock(mServiceLock);
5513
5514 // Dump info from previous open sessions.
5515 // Reposition the offset to beginning of the file before reading
5516
5517 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5518 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5519 ssize_t size_read;
5520 char buf[4096];
5521 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5522 // Read data from file to a small buffer and write it to fd.
5523 write(fd, buf, size_read);
5524 if (size_read == -1) {
5525 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5526 break;
5527 }
5528 }
5529 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5530 } else {
5531 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5532 }
5533
5534 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005535 return NO_ERROR;
5536}
5537
Rucha Katakwardf223072021-06-15 10:21:00 -07005538void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005539 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005540 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005541 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005542 getFormattedCurrentTime().c_str(),
5543 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005544 dprintf(fd, " Client priority score: %d state: %d\n",
5545 clientDescriptor->getPriority().getScore(),
5546 clientDescriptor->getPriority().getState());
5547 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5548
5549 auto client = clientDescriptor->getValue();
5550 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005551 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005552
5553 client->dumpClient(fd, args);
5554}
5555
Austin Borgered99f642023-06-01 16:51:35 -07005556void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005557 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005558 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005559}
5560
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005561void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005562 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005563
5564 Mutex::Autolock l(mLogLock);
5565 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005566 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005567 }
5568
5569 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005570 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005571 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005572 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005573 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005574 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005575}
5576
Austin Borgered99f642023-06-01 16:51:35 -07005577void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005578 Mutex::Autolock lock(mLogLock);
5579 if (!isClientWatchedLocked(client)) { return; }
5580
5581 std::vector<std::string> dumpVector;
5582 client->dumpWatchedEventsToVector(dumpVector);
5583
5584 if (dumpVector.empty()) { return; }
5585
Austin Borgered99f642023-06-01 16:51:35 -07005586 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005587
Austin Borgered99f642023-06-01 16:51:35 -07005588 std::string currentTime = getFormattedCurrentTime();
5589 dumpString << "Cached @ ";
5590 dumpString << currentTime;
5591 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005592
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005593 size_t i = dumpVector.size();
5594
5595 // Store the string in reverse order (latest last)
5596 while (i > 0) {
5597 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005598 dumpString << cameraId;
5599 dumpString << ":";
5600 dumpString << client->getPackageName();
5601 dumpString << " ";
5602 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005603 }
5604
Austin Borgered99f642023-06-01 16:51:35 -07005605 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005606}
5607
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005608void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005609 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005610 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5611 if (mTorchClientMap[i] == who) {
5612 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005613 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005614 status_t res = mFlashlight->setTorchMode(cameraId, false);
5615 if (res) {
5616 ALOGE("%s: torch client died but couldn't turn off torch: "
5617 "%s (%d)", __FUNCTION__, strerror(-res), res);
5618 return;
5619 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005620 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005621 break;
5622 }
5623 }
5624}
5625
Ruben Brunkcc776712015-02-17 20:18:47 -08005626/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005627
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005628 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005629 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5630 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005631 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005632 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005633 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005634
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005635 // check torch client
5636 handleTorchClientBinderDied(who);
5637
5638 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005639 if(!evictClientIdByRemote(who)) {
5640 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005641 return;
5642 }
5643
Ruben Brunkcc776712015-02-17 20:18:47 -08005644 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5645 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005646}
5647
Austin Borgered99f642023-06-01 16:51:35 -07005648void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005649 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005650}
5651
Austin Borgered99f642023-06-01 16:51:35 -07005652void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005653 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005654 // Do not lock mServiceLock here or can get into a deadlock from
5655 // connect() -> disconnect -> updateStatus
5656
5657 auto state = getCameraState(cameraId);
5658
5659 if (state == nullptr) {
5660 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005661 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005662 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005663 }
5664
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005665 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5666 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5667 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005668 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005669 return;
5670 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005671
Biswarup Pal37a75182024-01-16 15:53:35 +00005672 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5673 CameraMetadata cameraInfo;
5674 status_t res = mCameraProviderManager->getCameraCharacteristics(
Jayant Chowdhary81d81b02024-02-15 19:13:39 +00005675 cameraId, false, &cameraInfo, hardware::ICameraService::ROTATION_OVERRIDE_NONE);
Biswarup Pal37a75182024-01-16 15:53:35 +00005676 if (res != OK) {
5677 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5678 __FUNCTION__, cameraId.c_str());
5679 } else {
5680 int32_t deviceId = getDeviceId(cameraInfo);
5681 if (deviceId != kDefaultDeviceId) {
5682 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5683 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5684 static_cast<camera_metadata_enum_android_lens_facing_t>(
5685 lensFacingEntry.data.u8[0]);
5686 std::string mappedCameraId;
5687 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5688 mappedCameraId = kVirtualDeviceBackCameraId;
5689 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5690 mappedCameraId = kVirtualDeviceFrontCameraId;
5691 } else {
5692 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5693 __func__);
5694 }
5695 if (!mappedCameraId.empty()) {
5696 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5697 }
5698 }
5699 }
5700 }
5701
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005702 // Collect the logical cameras without holding mStatusLock in updateStatus
5703 // as that can lead to a deadlock(b/162192331).
5704 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005705 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005706 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005707 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005708 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005709 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005710 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5711 auto [deviceId, mappedCameraId] =
5712 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005713
Biswarup Pal37a75182024-01-16 15:53:35 +00005714 if (status != StatusInternal::ENUMERATING) {
5715 // Update torch status if it has a flash unit.
5716 Mutex::Autolock al(mTorchStatusMutex);
5717 TorchModeStatus torchStatus;
5718 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5719 NAME_NOT_FOUND) {
5720 TorchModeStatus newTorchStatus =
5721 status == StatusInternal::PRESENT ?
5722 TorchModeStatus::AVAILABLE_OFF :
5723 TorchModeStatus::NOT_AVAILABLE;
5724 if (torchStatus != newTorchStatus) {
5725 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5726 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005727 }
5728 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005729
Biswarup Pal37a75182024-01-16 15:53:35 +00005730 Mutex::Autolock lock(mStatusListenerLock);
5731 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5732 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005733
Biswarup Pal37a75182024-01-16 15:53:35 +00005734 for (auto& listener : mListenerList) {
5735 bool isVendorListener = listener->isVendorListener();
5736 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5737 listener->getListenerPid(), listener->getListenerUid())) {
5738 ALOGV("Skipping discovery callback for system-only camera device %s",
5739 cameraId.c_str());
5740 continue;
5741 }
5742
5743 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5744 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005745 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005746 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005747 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5748 ret.exceptionCode());
5749 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005750 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005751}
5752
Austin Borgered99f642023-06-01 16:51:35 -07005753void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5754 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005755 auto state = getCameraState(cameraId);
5756 if (state == nullptr) {
5757 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005758 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005759 return;
5760 }
5761 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005762 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005763 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005764 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005765 }
5766
Biswarup Pal37a75182024-01-16 15:53:35 +00005767 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5768 auto [deviceId, mappedCameraId] =
5769 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5770
Shuzhen Wang695044d2020-03-06 09:02:23 -08005771 Mutex::Autolock lock(mStatusListenerLock);
5772
5773 for (const auto& it : mListenerList) {
5774 if (!it->isOpenCloseCallbackAllowed()) {
5775 continue;
5776 }
5777
5778 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005779 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005780 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5781 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005782 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005783 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005784 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005785
5786 it->handleBinderStatus(ret,
5787 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5788 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005789 }
5790}
5791
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005792template<class Func>
5793void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005794 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005795 std::initializer_list<StatusInternal> rejectSourceStates,
5796 Func onStatusUpdatedLocked) {
5797 Mutex::Autolock lock(mStatusLock);
5798 StatusInternal oldStatus = mStatus;
5799 mStatus = status;
5800
5801 if (oldStatus == status) {
5802 return;
5803 }
5804
5805 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07005806 cameraId.c_str(), eToI(oldStatus), eToI(status));
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005807
5808 if (oldStatus == StatusInternal::NOT_PRESENT &&
5809 (status != StatusInternal::PRESENT &&
5810 status != StatusInternal::ENUMERATING)) {
5811
5812 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5813 __FUNCTION__);
5814 mStatus = oldStatus;
5815 return;
5816 }
5817
5818 /**
5819 * Sometimes we want to conditionally do a transition.
5820 * For example if a client disconnects, we want to go to PRESENT
5821 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5822 */
5823 for (auto& rejectStatus : rejectSourceStates) {
5824 if (oldStatus == rejectStatus) {
5825 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005826 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005827 mStatus = oldStatus;
5828 return;
5829 }
5830 }
5831
5832 onStatusUpdatedLocked(cameraId, status);
5833}
5834
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005835status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005836 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005837 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005838 if (!status) {
5839 return BAD_VALUE;
5840 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005841 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5842 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005843 // invalid camera ID or the camera doesn't have a flash unit
5844 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005845 }
5846
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005847 *status = mTorchStatusMap.valueAt(index);
5848 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005849}
5850
Austin Borgered99f642023-06-01 16:51:35 -07005851status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005852 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005853 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5854 if (index == NAME_NOT_FOUND) {
5855 return BAD_VALUE;
5856 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005857 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005858
5859 return OK;
5860}
5861
Austin Borgered99f642023-06-01 16:51:35 -07005862std::list<std::string> CameraService::getLogicalCameras(
5863 const std::string& physicalCameraId) {
5864 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08005865 Mutex::Autolock lock(mCameraStatesLock);
5866 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005867 if (state.second->containsPhysicalCamera(physicalCameraId)) {
5868 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08005869 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005870 }
5871 return retList;
5872}
5873
5874void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07005875 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00005876 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005877 // mStatusListenerLock is expected to be locked
5878 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005879 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005880 // Note: we check only the deviceKind of the physical camera id
5881 // since, logical camera ids and their physical camera ids are
5882 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005883 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
5884 listener->getListenerPid(), listener->getListenerUid())) {
5885 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07005886 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07005887 continue;
5888 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005889 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00005890 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07005891 listener->handleBinderStatus(ret,
5892 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
5893 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5894 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08005895 }
5896 }
5897}
5898
Svet Ganova453d0d2018-01-11 15:37:58 -08005899void CameraService::blockClientsForUid(uid_t uid) {
5900 const auto clients = mActiveClientManager.getAll();
5901 for (auto& current : clients) {
5902 if (current != nullptr) {
5903 const auto basicClient = current->getValue();
5904 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
5905 basicClient->block();
5906 }
5907 }
5908 }
5909}
5910
Michael Grooverd1d435a2018-12-18 17:39:42 -08005911void CameraService::blockAllClients() {
5912 const auto clients = mActiveClientManager.getAll();
5913 for (auto& current : clients) {
5914 if (current != nullptr) {
5915 const auto basicClient = current->getValue();
5916 if (basicClient.get() != nullptr) {
5917 basicClient->block();
5918 }
5919 }
5920 }
5921}
5922
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005923void CameraService::blockPrivacyEnabledClients() {
5924 const auto clients = mActiveClientManager.getAll();
5925 for (auto& current : clients) {
5926 if (current != nullptr) {
5927 const auto basicClient = current->getValue();
5928 if (basicClient.get() != nullptr) {
5929 std::string pkgName = basicClient->getPackageName();
5930 bool cameraPrivacyEnabled =
5931 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
5932 if (cameraPrivacyEnabled) {
5933 basicClient->block();
5934 }
5935 }
5936 }
5937 }
5938}
5939
Svet Ganova453d0d2018-01-11 15:37:58 -08005940// NOTE: This is a remote API - make sure all args are validated
5941status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07005942 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005943 return PERMISSION_DENIED;
5944 }
5945 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
5946 return BAD_VALUE;
5947 }
Austin Borgered99f642023-06-01 16:51:35 -07005948 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005949 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005950 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005951 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07005952 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005953 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07005954 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005955 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07005956 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005957 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07005958 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005959 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07005960 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00005961 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07005962 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005963 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07005964 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08005965 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07005966 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08005967 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07005968 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005969 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07005970 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08005971 handleClearStreamUseCaseOverrides();
5972 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07005973 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07005974 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07005975 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08005976 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07005977 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00005978 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07005979 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005980 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005981 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08005982 }
5983 printHelp(err);
5984 return BAD_VALUE;
5985}
5986
5987status_t CameraService::handleSetUidState(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
Svet Ganova453d0d2018-01-11 15:37:58 -08005990 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07005991 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005992 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07005993 } else if ((args[2] != toString16("idle"))) {
5994 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08005995 return BAD_VALUE;
5996 }
Nicholas Sauera3620332019-04-03 14:05:17 -07005997
5998 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07005999 if (args.size() >= 5 && args[3] == toString16("--user")) {
6000 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006001 }
6002
6003 uid_t uid;
6004 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6005 return BAD_VALUE;
6006 }
6007
6008 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006009 return NO_ERROR;
6010}
6011
6012status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006013 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006014
6015 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006016 if (args.size() >= 4 && args[2] == toString16("--user")) {
6017 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006018 }
6019
6020 uid_t uid;
6021 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006022 return BAD_VALUE;
6023 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006024
6025 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006026 return NO_ERROR;
6027}
6028
6029status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006030 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006031
6032 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006033 if (args.size() >= 4 && args[2] == toString16("--user")) {
6034 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006035 }
6036
6037 uid_t uid;
6038 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006039 return BAD_VALUE;
6040 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006041
6042 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006043 return dprintf(out, "active\n");
6044 } else {
6045 return dprintf(out, "idle\n");
6046 }
6047}
6048
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006049status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006050 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006051 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6052 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6053 Mutex::Autolock lock(mServiceLock);
6054
6055 mOverrideRotateAndCropMode = rotateValue;
6056
6057 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6058
6059 const auto clients = mActiveClientManager.getAll();
6060 for (auto& current : clients) {
6061 if (current != nullptr) {
6062 const auto basicClient = current->getValue();
6063 if (basicClient.get() != nullptr) {
6064 basicClient->setRotateAndCropOverride(rotateValue);
6065 }
6066 }
6067 }
6068
6069 return OK;
6070}
6071
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006072status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6073 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006074 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006075 if ((*end != '\0') ||
6076 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6077 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6078 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6079 return BAD_VALUE;
6080 }
6081
6082 Mutex::Autolock lock(mServiceLock);
6083 mOverrideAutoframingMode = autoframingValue;
6084
6085 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6086
6087 const auto clients = mActiveClientManager.getAll();
6088 for (auto& current : clients) {
6089 if (current != nullptr) {
6090 const auto basicClient = current->getValue();
6091 if (basicClient.get() != nullptr) {
6092 basicClient->setAutoframingOverride(autoframingValue);
6093 }
6094 }
6095 }
6096
6097 return OK;
6098}
6099
Ravneetaeb20dc2022-03-30 05:33:03 +00006100status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006101 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006102
6103 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6104
6105 Mutex::Autolock lock(mServiceLock);
6106
6107 mCameraServiceWatchdogEnabled = enableWatchdog;
6108
6109 const auto clients = mActiveClientManager.getAll();
6110 for (auto& current : clients) {
6111 if (current != nullptr) {
6112 const auto basicClient = current->getValue();
6113 if (basicClient.get() != nullptr) {
6114 basicClient->setCameraServiceWatchdog(enableWatchdog);
6115 }
6116 }
6117 }
6118
6119 return OK;
6120}
6121
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006122status_t CameraService::handleGetRotateAndCrop(int out) {
6123 Mutex::Autolock lock(mServiceLock);
6124
6125 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6126}
6127
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006128status_t CameraService::handleGetAutoframing(int out) {
6129 Mutex::Autolock lock(mServiceLock);
6130
6131 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6132}
6133
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006134status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6135 char *endPtr;
6136 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006137 std::string maskString = toStdString(args[1]);
6138 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006139
6140 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006141 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006142 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6143
6144 Mutex::Autolock lock(mServiceLock);
6145
6146 mImageDumpMask = maskValue;
6147
6148 return OK;
6149}
6150
6151status_t CameraService::handleGetImageDumpMask(int out) {
6152 Mutex::Autolock lock(mServiceLock);
6153
6154 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6155}
6156
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006157status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006158 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006159 if (errno != 0) return BAD_VALUE;
6160
6161 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6162 Mutex::Autolock lock(mServiceLock);
6163
6164 mOverrideCameraMuteMode = (muteValue == 1);
6165
6166 const auto clients = mActiveClientManager.getAll();
6167 for (auto& current : clients) {
6168 if (current != nullptr) {
6169 const auto basicClient = current->getValue();
6170 if (basicClient.get() != nullptr) {
6171 if (basicClient->supportsCameraMute()) {
6172 basicClient->setCameraMute(mOverrideCameraMuteMode);
6173 }
6174 }
6175 }
6176 }
6177
6178 return OK;
6179}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006180
Shuzhen Wang16610a62022-12-15 22:38:07 -08006181status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6182 std::vector<int64_t> useCasesOverride;
6183 for (size_t i = 1; i < args.size(); i++) {
6184 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006185 std::string arg = toStdString(args[i]);
6186 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006187 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006188 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006189 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006190 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006191 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006192 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006193 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006194 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006195 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006196 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006197 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006198 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006199 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6200 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006201 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006202 return BAD_VALUE;
6203 }
6204 useCasesOverride.push_back(useCase);
6205 }
6206
6207 Mutex::Autolock lock(mServiceLock);
6208 mStreamUseCaseOverrides = std::move(useCasesOverride);
6209
6210 return OK;
6211}
6212
6213void CameraService::handleClearStreamUseCaseOverrides() {
6214 Mutex::Autolock lock(mServiceLock);
6215 mStreamUseCaseOverrides.clear();
6216}
6217
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006218status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6219 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006220 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006221 if ((*end != '\0') ||
6222 (zoomOverrideValue != -1 &&
6223 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6224 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6225 return BAD_VALUE;
6226 }
6227
6228 Mutex::Autolock lock(mServiceLock);
6229 mZoomOverrideValue = zoomOverrideValue;
6230
6231 const auto clients = mActiveClientManager.getAll();
6232 for (auto& current : clients) {
6233 if (current != nullptr) {
6234 const auto basicClient = current->getValue();
6235 if (basicClient.get() != nullptr) {
6236 if (basicClient->supportsZoomOverride()) {
6237 basicClient->setZoomOverride(mZoomOverrideValue);
6238 }
6239 }
6240 }
6241 }
6242
6243 return OK;
6244}
6245
Avichal Rakesh84147132021-11-11 17:47:11 -08006246status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006247 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006248 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006249 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006250 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006251 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006252 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006253 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006254 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006255 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006256 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006257 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006258 dprintf(outFd, "Camera service watch commands:\n"
6259 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6260 " starts watching the provided tags for clients with provided package\n"
6261 " recognizes tag shorthands like '3a'\n"
6262 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006263 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006264 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006265 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006266 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006267 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006268 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006269 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006270}
6271
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006272status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6273 Mutex::Autolock lock(mLogLock);
6274 size_t tagsIdx; // index of '-m'
6275 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006276 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006277 if (tagsIdx < args.size() - 1) {
6278 tags = args[tagsIdx + 1];
6279 } else {
6280 dprintf(outFd, "No tags provided.\n");
6281 return BAD_VALUE;
6282 }
6283
6284 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006285 // watch all clients if no clients are provided
6286 String16 clients = toString16(kWatchAllClientsFlag);
6287 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006288 clientsIdx++);
6289 if (clientsIdx < args.size() - 1) {
6290 clients = args[clientsIdx + 1];
6291 }
Austin Borgered99f642023-06-01 16:51:35 -07006292 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006293
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006294 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006295 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006296
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006297 bool serviceLock = tryLock(mServiceLock);
6298 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006299 auto cameraClients = mActiveClientManager.getAll();
6300 for (const auto &clientDescriptor: cameraClients) {
6301 if (clientDescriptor == nullptr) { continue; }
6302 sp<BasicClient> client = clientDescriptor->getValue();
6303 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006304
6305 if (isClientWatchedLocked(client.get())) {
6306 client->startWatchingTags(mMonitorTags, outFd);
6307 numWatchedClients++;
6308 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006309 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006310 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6311
6312 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006313 return OK;
6314}
6315
6316status_t CameraService::stopWatchingTags(int outFd) {
6317 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006318 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006319 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006320
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006321 mWatchedClientPackages.clear();
6322 mWatchedClientsDumpCache.clear();
6323
6324 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006325 auto cameraClients = mActiveClientManager.getAll();
6326 for (const auto &clientDescriptor : cameraClients) {
6327 if (clientDescriptor == nullptr) { continue; }
6328 sp<BasicClient> client = clientDescriptor->getValue();
6329 if (client.get() == nullptr) { continue; }
6330 client->stopWatchingTags(outFd);
6331 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006332 dprintf(outFd, "Stopped watching all clients.\n");
6333 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006334 return OK;
6335}
6336
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006337status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6338 Mutex::Autolock lock(mLogLock);
6339 size_t clearedSize = mWatchedClientsDumpCache.size();
6340 mWatchedClientsDumpCache.clear();
6341 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6342 return OK;
6343}
6344
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006345status_t CameraService::printWatchedTags(int outFd) {
6346 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006347 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006348
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006349 bool printedSomething = false; // tracks if any monitoring information was printed
6350 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006351
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006352 bool serviceLock = tryLock(mServiceLock);
6353 // get all watched clients that are currently connected
6354 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6355 if (clientDescriptor == nullptr) { continue; }
6356
6357 sp<BasicClient> client = clientDescriptor->getValue();
6358 if (client.get() == nullptr) { continue; }
6359 if (!isClientWatchedLocked(client.get())) { continue; }
6360
6361 std::vector<std::string> dumpVector;
6362 client->dumpWatchedEventsToVector(dumpVector);
6363
6364 size_t printIdx = dumpVector.size();
6365 if (printIdx == 0) {
6366 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006367 }
6368
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006369 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006370 const std::string &cameraId = clientDescriptor->getKey();
6371 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006372 while(printIdx > 0) {
6373 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006374 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006375 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006376 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006377 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006378 printedSomething = true;
6379
6380 connectedMonitoredClients.emplace(client->getPackageName());
6381 }
6382 if (serviceLock) { mServiceLock.unlock(); }
6383
6384 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6385 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006386 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006387 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6388 continue;
6389 }
6390
Austin Borgered99f642023-06-01 16:51:35 -07006391 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006392 dprintf(outFd, "%s\n", kv.second.c_str());
6393 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006394 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006395
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006396 if (!printedSomething) {
6397 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006398 }
6399
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006400 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006401}
6402
Avichal Rakesh84147132021-11-11 17:47:11 -08006403// Print all events in vector `events' that came after lastPrintedEvent
6404void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006405 const std::string &cameraId,
6406 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006407 const std::vector<std::string> &events,
6408 const std::string &lastPrintedEvent) {
6409 if (events.empty()) { return; }
6410
6411 // index of lastPrintedEvent in events.
6412 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6413 size_t lastPrintedIdx;
6414 for (lastPrintedIdx = 0;
6415 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6416 lastPrintedIdx++);
6417
6418 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6419
Avichal Rakesh84147132021-11-11 17:47:11 -08006420 // print events in chronological order (latest event last)
6421 size_t idxToPrint = lastPrintedIdx;
6422 do {
6423 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006424 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6425 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006426 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006427}
6428
6429// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6430// command should be interrupted if the user presses the return key, or if user loses any way to
6431// signal interrupt.
6432// If timeoutMs == 0, this function will always return false
6433bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6434 struct timeval startTime;
6435 int startTimeError = gettimeofday(&startTime, nullptr);
6436 if (startTimeError) {
6437 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6438 return true;
6439 }
6440
6441 const nfds_t numFds = 1;
6442 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6443
6444 struct timeval currTime;
6445 char buffer[2];
6446 while(true) {
6447 int currTimeError = gettimeofday(&currTime, nullptr);
6448 if (currTimeError) {
6449 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6450 return true;
6451 }
6452
6453 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6454 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6455 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6456
6457 if (remainingTimeMs <= 0) {
6458 // No user interrupt within timeoutMs, don't interrupt watch command
6459 return false;
6460 }
6461
6462 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6463 if (numFdsUpdated < 0) {
6464 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6465 return true;
6466 }
6467
6468 if (numFdsUpdated == 0) {
6469 // No user input within timeoutMs, don't interrupt watch command
6470 return false;
6471 }
6472
6473 if (!(pollFd.revents & POLLIN)) {
6474 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6475 return true;
6476 }
6477
6478 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6479 if (sizeRead < 0) {
6480 dprintf(outFd, "Error reading user input. Exiting.\n");
6481 return true;
6482 }
6483
6484 if (sizeRead == 0) {
6485 // Reached end of input fd (can happen if input is piped)
6486 // User has no way to signal an interrupt, so interrupt here
6487 return true;
6488 }
6489
6490 if (buffer[0] == '\n') {
6491 // User pressed return, interrupt watch command.
6492 return true;
6493 }
6494 }
6495}
6496
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006497status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6498 int inFd, int outFd) {
6499 // Figure out refresh interval, if present in args
6500 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006501 if (args.size() > 2) {
6502 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006503 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006504 intervalIdx++);
6505
6506 size_t intervalValIdx = intervalIdx + 1;
6507 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006508 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006509 if (errno) { return BAD_VALUE; }
6510 }
6511 }
6512
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006513 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6514 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006515
Avichal Rakesh84147132021-11-11 17:47:11 -08006516 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006517 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006518
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006519 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006520 bool serviceLock = tryLock(mServiceLock);
6521 auto cameraClients = mActiveClientManager.getAll();
6522 if (serviceLock) { mServiceLock.unlock(); }
6523
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006524 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006525 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006526 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006527
6528 sp<BasicClient> client = clientDescriptor->getValue();
6529 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006530 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006531
Austin Borgered99f642023-06-01 16:51:35 -07006532 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006533 // This also initializes the map entries with an empty string
6534 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6535
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006536 std::vector<std::string> latestEvents;
6537 client->dumpWatchedEventsToVector(latestEvents);
6538
6539 if (!latestEvents.empty()) {
6540 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006541 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006542 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006543 latestEvents,
6544 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006545 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006546 }
6547 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006548 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006549 break;
6550 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006551 }
6552 return OK;
6553}
6554
Austin Borgered99f642023-06-01 16:51:35 -07006555void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006556 mWatchedClientPackages.clear();
6557
Austin Borgered99f642023-06-01 16:51:35 -07006558 std::istringstream iss(clients);
6559 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006560
Austin Borgered99f642023-06-01 16:51:35 -07006561 while (std::getline(iss, nextClient, ',')) {
6562 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006563 // Don't need to track any other package if 'all' is present
6564 mWatchedClientPackages.clear();
6565 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6566 break;
6567 }
6568
6569 // track package names
6570 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006571 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006572}
6573
Svet Ganova453d0d2018-01-11 15:37:58 -08006574status_t CameraService::printHelp(int out) {
6575 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006576 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6577 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6578 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006579 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6580 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6581 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006582 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6583 " Valid values 0=false, 1=true, 2=auto\n"
6584 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006585 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6586 " Valid values 0=OFF, 1=ON for JPEG\n"
6587 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006588 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006589 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6590 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6591 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6592 " on. In case the number of usecases is smaller than the number of streams, the\n"
6593 " last use case is assigned to all the remaining streams. In case of multiple\n"
6594 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6595 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6596 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6597 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006598 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6599 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006600 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6601 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006602 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006603 " help print this message\n");
6604}
6605
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006606bool CameraService::isClientWatched(const BasicClient *client) {
6607 Mutex::Autolock lock(mLogLock);
6608 return isClientWatchedLocked(client);
6609}
6610
6611bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6612 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6613 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6614}
6615
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006616int32_t CameraService::updateAudioRestriction() {
6617 Mutex::Autolock lock(mServiceLock);
6618 return updateAudioRestrictionLocked();
6619}
6620
6621int32_t CameraService::updateAudioRestrictionLocked() {
6622 int32_t mode = 0;
6623 // iterate through all active client
6624 for (const auto& i : mActiveClientManager.getAll()) {
6625 const auto clientSp = i->getValue();
6626 mode |= clientSp->getAudioRestriction();
6627 }
6628
6629 bool modeChanged = (mAudioRestriction != mode);
6630 mAudioRestriction = mode;
6631 if (modeChanged) {
6632 mAppOps.setCameraAudioRestriction(mode);
6633 }
6634 return mode;
6635}
6636
Austin Borgered99f642023-06-01 16:51:35 -07006637status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006638 sp<BasicClient> clientSp) {
6639 std::unique_ptr<AutoConditionLock> lock =
6640 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6641 status_t res = NO_ERROR;
6642 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006643 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006644 mInjectionStatusListener->notifyInjectionError(
6645 externalCamId, UNKNOWN_TRANSACTION);
6646 clientSp->notifyError(
6647 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6648 CaptureResultExtras());
6649
6650 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6651 // other clients from connecting in mServiceLockWrapper if held
6652 mServiceLock.unlock();
6653
6654 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006655 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006656 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006657 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006658
6659 // Reacquire mServiceLock
6660 mServiceLock.lock();
6661 }
6662
6663 return res;
6664}
6665
Cliff Wud3a05312021-04-26 23:07:31 +08006666void CameraService::clearInjectionParameters() {
6667 {
6668 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006669 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006670 mInjectionInternalCamId = "";
6671 }
6672 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006673 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006674}
6675
Biswarup Pal37a75182024-01-16 15:53:35 +00006676} // namespace android