blob: 3025fb4147846e24b7322d1d366aea0a28cf73e2 [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
Rucha Katakward9ea6452021-05-06 11:57:16 -0700169// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700170static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700171
Austin Borger74fca042022-05-23 12:41:21 -0700172CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700173 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
174 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
175 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
176 std::make_shared<AttributionAndPermissionUtils>()\
177 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700178 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
179 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800180 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800181 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700182 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700183 mSoundRef(0), mInitialized(false),
184 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000185 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700186 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800187 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700188 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
189 if (mMemFd == -1) {
190 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
191 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700192}
193
Charles Chena7b613c2023-01-24 21:57:33 +0000194// Enable processes with isolated AID to request the binder
195void CameraService::instantiate() {
196 CameraService::publish(true);
197}
198
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800199void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700200 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800201 return;
202 }
203
204 ALOGV("appops service registered. setting camera audio restriction");
205 mAppOps.setCameraAudioRestriction(mAudioRestriction);
206}
207
Iliyan Malchev8951a972011-04-14 16:55:59 -0700208void CameraService::onFirstRef()
209{
Ruben Brunkcc776712015-02-17 20:18:47 -0800210 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800211
Iliyan Malchev8951a972011-04-14 16:55:59 -0700212 BnCameraService::onFirstRef();
213
Ruben Brunk99e69712015-05-26 17:25:07 -0700214 // Update battery life tracking if service is restarting
215 BatteryNotifier& notifier(BatteryNotifier::getInstance());
216 notifier.noteResetCamera();
217 notifier.noteResetFlashlight();
218
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800219 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800220
Emilian Peevf53f66e2017-04-11 14:29:43 +0100221 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800222 if (res == OK) {
223 mInitialized = true;
224 }
225
Svet Ganova453d0d2018-01-11 15:37:58 -0800226 mUidPolicy = new UidPolicy(this);
227 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700228 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800229 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800230 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800231
232 // appops function setCamerAudioRestriction uses getService which
233 // is blocking till the appops service is ready. To enable early
234 // boot availability for cameraservice, use checkService which is
235 // non blocking and register for notifications
236 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700237 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800238 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700239 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800240 } else {
241 mAppOps.setCameraAudioRestriction(mAudioRestriction);
242 }
243
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700244 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
245 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000246 // Deprecated, so it will fail to register on newer devices
247 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700248 __FUNCTION__);
249 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700250
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700251 if (!AidlCameraService::registerService(this)) {
252 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
253 }
254
Shuzhen Wang24b44152019-09-20 10:38:11 -0700255 // This needs to be last call in this function, so that it's as close to
256 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700257 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700258 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800259}
260
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800261status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800262 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100263
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800264 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000265 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800266 {
267 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800268
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800269 if (nullptr == mCameraProviderManager.get()) {
270 mCameraProviderManager = new CameraProviderManager();
271 res = mCameraProviderManager->initialize(this);
272 if (res != OK) {
273 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
274 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700275 logServiceError("Unable to initialize camera provider manager",
276 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800277 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100278 }
279 }
280
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800281 // Setup vendor tags before we call get_camera_info the first time
282 // because HAL might need to setup static vendor keys in get_camera_info
283 // TODO: maybe put this into CameraProviderManager::initialize()?
284 mCameraProviderManager->setUpVendorTags();
285
286 if (nullptr == mFlashlight.get()) {
287 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700288 }
289
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800290 res = mFlashlight->findFlashUnits();
291 if (res != OK) {
292 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
293 }
294
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000295 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800296 }
297
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800298 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700299 if (getCameraState(cameraId) == nullptr) {
300 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800301 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000302 if (unavailPhysicalIds.count(cameraId) > 0) {
303 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700304 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000305 }
306 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800307 }
308
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700309 // Derive primary rear/front cameras, and filter their charactierstics.
310 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700311 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700312 // Assume internal cameras are advertised from the same
313 // provider. If multiple providers are registered at different time,
314 // and each provider contains multiple internal color cameras, the current
315 // logic may filter the characteristics of more than one front/rear color
316 // cameras.
317 Mutex::Autolock l(mServiceLock);
318 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700319 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700320
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800321 return OK;
322}
323
Austin Borgered99f642023-06-01 16:51:35 -0700324void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700325 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000326 // Get the device id and app-visible camera id for the given HAL-visible camera id.
327 auto [deviceId, mappedCameraId] =
328 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
329
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800330 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800331 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700332 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
333 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000334 ALOGV("%s: Skipping torch callback for system-only camera device %s",
335 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700336 continue;
337 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000338
Austin Borgere8e2c422022-05-12 13:45:24 -0700339 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000340 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700341 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
342 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +0000343
344 // Only cameras of the default device can be remapped to a different camera (using
345 // remapCameraIds method), so do the following only if the camera is associated with the
346 // default device.
347 if (deviceId == kDefaultDeviceId) {
348 // For the default device, also trigger the torch callbacks for cameras that were
349 // remapped to the current cameraId for the specific package that this listener belongs
350 // to.
351 std::vector<std::string> remappedCameraIds =
352 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
353 for (auto &remappedCameraId: remappedCameraIds) {
354 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
355 remappedCameraId, kDefaultDeviceId);
356 i->handleBinderStatus(ret,
357 "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
358 __FUNCTION__, i->getListenerUid(), i->getListenerPid(),
359 ret.exceptionCode());
360 }
malikakash82ed4352023-07-21 22:44:34 +0000361 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800362 }
363}
364
Mathias Agopian65ab4712010-07-14 17:59:35 -0700365CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800366 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800367 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800368 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800369 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700370}
371
Emilian Peevaee727d2017-05-04 16:35:48 +0100372void CameraService::onNewProviderRegistered() {
373 enumerateProviders();
374}
375
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700376void CameraService::filterAPI1SystemCameraLocked(
377 const std::vector<std::string> &normalDeviceIds) {
378 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000379 for (auto &cameraId : normalDeviceIds) {
380 if (vd_flags::camera_device_awareness()) {
381 CameraMetadata cameraInfo;
382 status_t res = mCameraProviderManager->getCameraCharacteristics(
383 cameraId, false, &cameraInfo, false);
384 int32_t deviceId = kDefaultDeviceId;
385 if (res != OK) {
386 ALOGW("%s: Not able to get camera characteristics for camera id %s",
387 __FUNCTION__, cameraId.c_str());
388 } else {
389 deviceId = getDeviceId(cameraInfo);
390 }
391 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
392 // system cameras, so skip for non-default device id's.
393 if (deviceId != kDefaultDeviceId) {
394 continue;
395 }
396 }
397
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700398 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000399 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
400 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700401 continue;
402 }
403 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700404 // All system camera ids will necessarily come after public camera
405 // device ids as per the HAL interface contract.
406 break;
407 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000408 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700409 }
410 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
411 mNormalDeviceIdsWithoutSystemCamera.size());
412}
413
Austin Borgered99f642023-06-01 16:51:35 -0700414status_t CameraService::getSystemCameraKind(const std::string& cameraId,
415 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700416 auto state = getCameraState(cameraId);
417 if (state != nullptr) {
418 *kind = state->getSystemCameraKind();
419 return OK;
420 }
421 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700422 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700423}
424
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800425void CameraService::updateCameraNumAndIds() {
426 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700427 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
428 // Excludes hidden secure cameras
429 mNumberOfCameras =
430 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
431 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800432 mNormalDeviceIds =
433 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700434 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800435}
436
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700437void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700438 // To claim to be S Performance primary cameras, the cameras must be
439 // backward compatible. So performance class primary camera Ids must be API1
440 // compatible.
441 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
442 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
443 int facing = -1;
444 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800445 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700446 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800447 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700448 if (facing == -1) {
449 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
450 return;
451 }
452
453 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
454 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700455 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
456 if (res == OK) {
457 mPerfClassPrimaryCameraIds.insert(cameraId);
458 } else {
459 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
460 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
461 break;
462 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700463
464 if (facing == hardware::CAMERA_FACING_BACK) {
465 firstRearCameraSeen = true;
466 }
467 if (facing == hardware::CAMERA_FACING_FRONT) {
468 firstFrontCameraSeen = true;
469 }
470 }
471
472 if (firstRearCameraSeen && firstFrontCameraSeen) {
473 break;
474 }
475 }
476}
477
Austin Borgered99f642023-06-01 16:51:35 -0700478void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700479 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100480 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
481 if (res != OK) {
482 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
483 return;
484 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000485 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700486 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
487 if (res != OK) {
488 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
489 return;
490 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000491 std::vector<std::string> physicalCameraIds;
492 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700493 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100494 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700495 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100496 }
497
498 {
499 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700500 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000501 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100502 }
503
Austin Borgered99f642023-06-01 16:51:35 -0700504 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100505 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700506 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800507
Austin Borgered99f642023-06-01 16:51:35 -0700508 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100509 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800510
511 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700512 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100513}
514
Austin Borgered99f642023-06-01 16:51:35 -0700515void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800516 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700517 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100518 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700519 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100520 }
521
522 {
523 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700524 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100525 }
526}
527
Austin Borgered99f642023-06-01 16:51:35 -0700528void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800529 CameraDeviceStatus newHalStatus) {
530 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700531 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700532
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800533 StatusInternal newStatus = mapToInternal(newHalStatus);
534
Austin Borgered99f642023-06-01 16:51:35 -0700535 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800536
537 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700538 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100539 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700540 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100541
542 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700543 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100544
Austin Borgered99f642023-06-01 16:51:35 -0700545 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700546 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700547 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700548 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700549 return;
550 }
551
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800552 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800553
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800554 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800555 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700556 return;
557 }
558
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800559 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000560 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
561 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800562 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
563 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700564 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000565 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800566
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800567 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700568 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800569 // Don't do this in updateStatus to avoid deadlock over mServiceLock
570 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700571
Ruben Brunkcc776712015-02-17 20:18:47 -0800572 // Remove cached shim parameters
573 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700574
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800575 // Remove online as well as offline client from the list of active clients,
576 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700577 clientToDisconnectOnline = removeClientLocked(cameraId);
578 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700579 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800580
Austin Borgered99f642023-06-01 16:51:35 -0700581 disconnectClient(cameraId, clientToDisconnectOnline);
582 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700583
Austin Borgered99f642023-06-01 16:51:35 -0700584 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800585 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800586 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000587 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
588 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700589 }
Austin Borgered99f642023-06-01 16:51:35 -0700590 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700591 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800592}
Igor Murashkincba2c162013-03-20 15:56:31 -0700593
Austin Borgered99f642023-06-01 16:51:35 -0700594void CameraService::onDeviceStatusChanged(const std::string& id,
595 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800596 CameraDeviceStatus newHalStatus) {
597 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700598 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800599
600 StatusInternal newStatus = mapToInternal(newHalStatus);
601
602 std::shared_ptr<CameraState> state = getCameraState(id);
603
604 if (state == nullptr) {
605 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700606 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800607 return;
608 }
609
610 StatusInternal logicalCameraStatus = state->getStatus();
611 if (logicalCameraStatus != StatusInternal::PRESENT &&
612 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
613 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700614 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800615 return;
616 }
617
618 bool updated = false;
619 if (newStatus == StatusInternal::PRESENT) {
620 updated = state->removeUnavailablePhysicalId(physicalId);
621 } else {
622 updated = state->addUnavailablePhysicalId(physicalId);
623 }
624
625 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700626 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800627 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000628 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800629 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000630 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800631 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700632 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
633 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
634 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700635 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700636 return;
637 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800638 Mutex::Autolock lock(mStatusListenerLock);
639 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700640 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
641 listener->getListenerPid(), listener->getListenerUid())) {
642 ALOGV("Skipping discovery callback for system-only camera device %s",
643 id.c_str());
644 continue;
645 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700646 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000647 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700648 listener->handleBinderStatus(ret,
649 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
650 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
651 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800652 }
653 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700654}
655
Austin Borgered99f642023-06-01 16:51:35 -0700656void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800657 if (clientToDisconnect.get() != nullptr) {
658 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700659 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800660 // Notify the client of disconnection
661 clientToDisconnect->notifyError(
662 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
663 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800664 clientToDisconnect->disconnect();
665 }
666}
667
Austin Borgered99f642023-06-01 16:51:35 -0700668void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800669 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700670 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
671 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
672 if (res != OK) {
673 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700674 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700675 return;
676 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800677 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700678 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800679}
680
Austin Borgered99f642023-06-01 16:51:35 -0700681void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700682 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
683 Mutex::Autolock al(mTorchStatusMutex);
684 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
685}
686
Austin Borgered99f642023-06-01 16:51:35 -0700687void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800688 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000689 // Get the device id and app-visible camera id for the given HAL-visible camera id.
690 auto [deviceId, mappedCameraId] =
691 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
692
Rucha Katakwar38284522021-11-10 11:25:21 -0800693 Mutex::Autolock lock(mStatusListenerLock);
694 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000695 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
696 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700697 i->handleBinderStatus(ret,
698 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
699 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800700 }
701}
702
Austin Borgered99f642023-06-01 16:51:35 -0700703void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700704 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800705 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700706 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800707
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800708 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800709 status_t res = getTorchStatusLocked(cameraId, &status);
710 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700711 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700712 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800713 return;
714 }
715 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800716 return;
717 }
718
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800719 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800720 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800721 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
722 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800723 return;
724 }
725
Ruben Brunkcc776712015-02-17 20:18:47 -0800726 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700727 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700728 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700729 auto iter = mTorchUidMap.find(cameraId);
730 if (iter != mTorchUidMap.end()) {
731 int oldUid = iter->second.second;
732 int newUid = iter->second.first;
733 BatteryNotifier& notifier(BatteryNotifier::getInstance());
734 if (oldUid != newUid) {
735 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800736 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700737 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700738 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800739 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700740 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700741 }
742 iter->second.second = newUid;
743 } else {
744 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800745 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700746 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700747 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700748 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700749 }
750 }
751 }
752 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700753 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800754}
755
Austin Borger249e6592024-03-10 22:28:11 -0700756bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700757 // Returns false if this is not an automotive device type.
758 if (!isAutomotiveDevice())
759 return false;
760
761 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700762 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700763 return false;
764
765 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
766 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
767 // This isn't a known camera ID, so it's not a system camera.
768 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
769 return false;
770 }
771
772 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
773 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
774 return false;
775 }
776
777 CameraMetadata cameraInfo;
778 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700779 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700780 if (res != OK){
781 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
782 cam_id.c_str());
783 return false;
784 }
785
786 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
787 if (auto_location.count != 1)
788 return false;
789
790 uint8_t location = auto_location.data.u8[0];
791 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
792 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
793 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
794 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
795 return false;
796 }
797
798 return true;
799}
800
Biswarup Pal37a75182024-01-16 15:53:35 +0000801Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
802 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700803 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000804 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
805 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
806 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
807 return Status::ok();
808 }
809
Emilian Peevaee727d2017-05-04 16:35:48 +0100810 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700811 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800812 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
813 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700814 switch (type) {
815 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700816 if (hasSystemCameraPermissions) {
817 *numCameras = static_cast<int>(mNormalDeviceIds.size());
818 } else {
819 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
820 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800821 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700822 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700823 if (hasSystemCameraPermissions) {
824 *numCameras = mNumberOfCameras;
825 } else {
826 *numCameras = mNumberOfCamerasWithoutSystemCamera;
827 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800828 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700829 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800830 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700831 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800832 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
833 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700834 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800835 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700836}
837
malikakash73125c62023-07-21 22:44:34 +0000838Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700839 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800840 const int pid = getCallingPid();
841 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000842 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
843 __FUNCTION__, pid, uid);
844 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
845 "Permission Denial: no permission to configure camera id mapping");
846 }
847 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000848 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000849 if (!parseStatus.isOk()) {
850 return parseStatus;
851 }
852 remapCameraIds(cameraIdRemappingMap);
853 return Status::ok();
854}
855
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700856Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000857 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700858 /* out */
859 hardware::camera2::impl::CameraMetadataNative* request) {
860 ATRACE_CALL();
861
862 if (!flags::feature_combination_query()) {
863 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
864 "Camera subsystem doesn't support this method!");
865 }
866 if (!mInitialized) {
867 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
868 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
869 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
870 }
871
Biswarup Pal37a75182024-01-16 15:53:35 +0000872 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
873 devicePolicy, getCallingUid());
874 if (!cameraIdOptional.has_value()) {
875 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
876 unresolvedCameraId.c_str(), deviceId);
877 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
878 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
879 }
880 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700881
882 binder::Status res;
883 if (request == nullptr) {
884 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
885 "Camera %s: Error creating default request", cameraId.c_str());
886 return res;
887 }
888 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
889 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
890 cameraId, templateId, &tempId);
891 if (!res.isOk()) {
892 ALOGE("%s: Camera %s: failed to map request Template %d",
893 __FUNCTION__, cameraId.c_str(), templateId);
894 return res;
895 }
896
897 if (shouldRejectSystemCameraConnection(cameraId)) {
898 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
899 "request for system only device %s: ", cameraId.c_str());
900 }
901
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700902 CameraMetadata metadata;
903 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
904 if (err == OK) {
905 request->swap(metadata);
906 } else if (err == BAD_VALUE) {
907 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
908 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
909 cameraId.c_str(), templateId, strerror(-err), err);
910 } else {
911 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
912 "Camera %s: Error creating default request for template %d: %s (%d)",
913 cameraId.c_str(), templateId, strerror(-err), err);
914 }
915 return res;
916}
917
918Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700919 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700920 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000921 int32_t deviceId, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700922 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700923 ATRACE_CALL();
924
925 if (!flags::feature_combination_query()) {
926 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
927 "Camera subsystem doesn't support this method!");
928 }
929 if (!mInitialized) {
930 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
931 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
932 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
933 }
934
Biswarup Pal37a75182024-01-16 15:53:35 +0000935 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
936 devicePolicy, getCallingUid());
937 if (!cameraIdOptional.has_value()) {
938 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
939 unresolvedCameraId.c_str(), deviceId);
940 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
941 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
942 }
943 std::string cameraId = cameraIdOptional.value();
944
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700945 if (supported == nullptr) {
946 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
947 unresolvedCameraId.c_str());
948 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
949 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
950 }
951
952 if (shouldRejectSystemCameraConnection(cameraId)) {
953 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
954 "session configuration with parameters support for system only device %s: ",
955 cameraId.c_str());
956 }
957
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700958 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
959 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
960 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
961
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700962 return isSessionConfigurationWithParametersSupportedUnsafe(cameraId, sessionConfiguration,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700963 overrideForPerfClass, supported);
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700964}
965
966Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
967 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
968 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700969 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700970 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
971 cameraId, sessionConfiguration, overrideForPerfClass,
972 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700973 binder::Status res;
974 switch (ret) {
975 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700976 // Expected. Do Nothing.
977 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700978 case INVALID_OPERATION: {
979 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700980 "Camera %s: Session configuration with parameters supported query not "
981 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700982 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700983 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
984 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
985 *supported = false;
986 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700987 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700988 break;
989 case NAME_NOT_FOUND: {
990 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
991 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
992 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
993 *supported = false;
994 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
995 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700996 break;
997 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700998 std::string msg = fmt::sprintf(
999 "Unable to retrieve session configuration support for camera "
1000 "device %s: Error: %s (%d)",
1001 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001002 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001003 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1004 *supported = false;
1005 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001006 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001007 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001008 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001009}
1010
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001011Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001012 int targetSdkVersion, bool overrideToPortrait,
1013 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
1014 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001015 ATRACE_CALL();
1016
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001017 if (outMetadata == nullptr) {
1018 std::string msg =
1019 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1020 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1021 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1022 }
1023
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001024 if (!mInitialized) {
1025 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1026 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1027 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1028 }
1029
Biswarup Pal37a75182024-01-16 15:53:35 +00001030 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001031 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001032 if (!cameraIdOptional.has_value()) {
1033 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001034 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001035 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1036 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1037 }
1038 std::string cameraId = cameraIdOptional.value();
1039
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001040 if (shouldRejectSystemCameraConnection(cameraId)) {
1041 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1042 "Unable to retrieve camera"
1043 "characteristics for system only device %s: ",
1044 cameraId.c_str());
1045 }
1046
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001047 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1048 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001049 if (flags::check_session_support_before_session_char()) {
1050 bool sessionConfigSupported;
1051 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1052 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1053 if (!res.isOk()) {
1054 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1055 // report the correct Status to send to the client. Simply forward the error to
1056 // the client.
1057 outMetadata->clear();
1058 return res;
1059 }
1060 if (!sessionConfigSupported) {
1061 std::string msg = fmt::sprintf(
1062 "Session configuration not supported for camera device %s.", cameraId.c_str());
1063 outMetadata->clear();
1064 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1065 }
1066 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001067
1068 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1069 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1070
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001071 switch (ret) {
1072 case OK:
1073 // Expected, no handling needed.
1074 break;
1075 case INVALID_OPERATION: {
1076 std::string msg = fmt::sprintf(
1077 "Camera %s: Session characteristics query not supported!",
1078 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001079 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001080 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1081 outMetadata->clear();
1082 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1083 }
1084 break;
1085 case NAME_NOT_FOUND: {
1086 std::string msg = fmt::sprintf(
1087 "Camera %s: Unknown camera ID.",
1088 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001089 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001090 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1091 outMetadata->clear();
1092 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001093 }
1094 break;
1095 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001096 std::string msg = fmt::sprintf(
1097 "Unable to retrieve session characteristics for camera device %s: "
1098 "Error: %s (%d)",
1099 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001100 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001101 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1102 outMetadata->clear();
1103 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001104 }
1105 }
1106
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001107 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1108}
1109
1110Status CameraService::filterSensitiveMetadataIfNeeded(
1111 const std::string& cameraId, CameraMetadata* metadata) {
1112 int callingPid = getCallingPid();
1113 int callingUid = getCallingUid();
1114
1115 if (callingPid == getpid()) {
1116 // Caller is cameraserver; no need to remove keys
1117 return Status::ok();
1118 }
1119
1120 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1121 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1122 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1123 metadata->clear();
1124 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1125 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1126 }
1127 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1128 // Attempting to query system only camera without system camera permission would have
1129 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1130 // for a system only camera, then the caller has the required permission.
1131 // No need to remove keys
1132 return Status::ok();
1133 }
1134
1135 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001136 // Get the device id that owns this camera.
1137 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1138 cameraId);
1139 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1140 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001141 if (hasCameraPermission) {
1142 // Caller has camera permission; no need to remove keys
1143 return Status::ok();
1144 }
1145
1146 status_t ret = metadata->removePermissionEntries(
1147 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1148 if (ret != OK) {
1149 metadata->clear();
1150 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1151 "Failed to remove camera characteristics needing camera permission "
1152 "for device %s:%s (%d)",
1153 cameraId.c_str(), strerror(-ret), ret);
1154 }
1155
1156 if (!tagsRemoved.empty()) {
1157 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1158 tagsRemoved.data(), tagsRemoved.size());
1159 if (ret != OK) {
1160 metadata->clear();
1161 return STATUS_ERROR_FMT(
1162 ERROR_INVALID_OPERATION,
1163 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1164 cameraId.c_str(), strerror(-ret), ret);
1165 }
1166 }
1167 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001168}
1169
malikakash82ed4352023-07-21 22:44:34 +00001170Status CameraService::parseCameraIdRemapping(
1171 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001172 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001173 std::string packageName;
1174 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001175 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001176 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001177 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001178 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1179 "CameraIdRemapping: Package name cannot be empty");
1180 }
malikakash214f6e62023-08-10 23:50:56 +00001181 if (packageIdRemapping.cameraIdsToReplace.size()
1182 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001183 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1184 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001185 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001186 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001187 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001188 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1189 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001190 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001191 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1192 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001193 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001194 }
1195 if (cameraIdToReplace == updatedCameraId) {
1196 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1197 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1198 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001199 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001200 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001201
1202 // Do not allow any camera remapping that involves a virtual camera.
1203 auto [deviceIdForCameraToReplace, _] =
1204 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1205 cameraIdToReplace);
1206 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1207 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1208 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1209 }
1210 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1211 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1212 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1213 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1214 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1215 }
1216
malikakash214f6e62023-08-10 23:50:56 +00001217 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001218 }
1219 }
1220 return Status::ok();
1221}
1222
1223void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1224 // Acquire mServiceLock and prevent other clients from connecting
1225 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1226 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1227
malikakashedb38962023-09-06 00:03:35 +00001228 // Collect all existing clients for camera Ids that are being
1229 // remapped in the new cameraIdRemapping, but only if they were being used by a
1230 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001231 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001232 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001233 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1234 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001235 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001236 id0.c_str(), id1.c_str());
1237 auto clientDescriptor = mActiveClientManager.get(id0);
1238 if (clientDescriptor != nullptr) {
1239 sp<BasicClient> clientSp = clientDescriptor->getValue();
1240 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001241 // This camera is being used by a targeted packageName and
1242 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001243 clientsToDisconnect.push_back(clientSp);
1244 cameraIdsToUpdate.push_back(id0);
1245 }
1246 }
1247 }
1248 }
1249
malikakashedb38962023-09-06 00:03:35 +00001250 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001251 // Notify the clients about the disconnection.
1252 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001253 CaptureResultExtras{});
1254 }
malikakash82ed4352023-07-21 22:44:34 +00001255
1256 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1257 // blocking other clients from connecting in mServiceLockWrapper if held.
1258 mServiceLock.unlock();
1259
malikakashedb38962023-09-06 00:03:35 +00001260 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001261 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001262
malikakash82ed4352023-07-21 22:44:34 +00001263 // Disconnect clients.
1264 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001265 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1266 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001267 clientSp->disconnect();
1268 }
1269
malikakashedb38962023-09-06 00:03:35 +00001270 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1271 clientsToDisconnect.clear();
1272
Austin Borger22c5c852024-03-08 13:31:36 -08001273 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001274 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001275
1276 {
1277 Mutex::Autolock lock(mCameraIdRemappingLock);
1278 // Update mCameraIdRemapping.
1279 mCameraIdRemapping.clear();
1280 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1281 }
malikakash82ed4352023-07-21 22:44:34 +00001282}
1283
malikakash22af94c2023-12-04 18:13:14 +00001284Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001285 const std::string& cameraId,
1286 const CameraMetadata& sessionParams) {
1287 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001288 const int pid = getCallingPid();
1289 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001290 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1291 __FUNCTION__, pid, uid);
1292 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1293 "Permission Denial: no permission to inject session params");
1294 }
1295
Biswarup Pal37a75182024-01-16 15:53:35 +00001296 // Do not allow session params injection for a virtual camera.
1297 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1298 if (deviceId != kDefaultDeviceId) {
1299 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1300 "Cannot inject session params for a virtual camera");
1301 }
1302
malikakash22af94c2023-12-04 18:13:14 +00001303 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1304 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1305
1306 auto clientDescriptor = mActiveClientManager.get(cameraId);
1307 if (clientDescriptor == nullptr) {
1308 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1309 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1310 "No active client for camera id %s", cameraId.c_str());
1311 }
1312
1313 sp<BasicClient> clientSp = clientDescriptor->getValue();
1314 status_t res = clientSp->injectSessionParams(sessionParams);
1315
1316 if (res != OK) {
1317 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1318 "Error injecting session params into camera \"%s\": %s (%d)",
1319 cameraId.c_str(), strerror(-res), res);
1320 }
1321 return Status::ok();
1322}
1323
Austin Borgered99f642023-06-01 16:51:35 -07001324std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1325 const std::string& inputCameraId, int clientUid) {
1326 std::string packageName = getPackageNameFromUid(clientUid);
1327 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001328 Mutex::Autolock lock(mCameraIdRemappingLock);
1329 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1330 packageMapIter != mCameraIdRemapping.end()) {
1331 for (auto& [id0, id1]: packageMapIter->second) {
1332 if (id1 == inputCameraId) {
1333 cameraIds.push_back(id0);
1334 }
1335 }
1336 }
1337 return cameraIds;
1338}
1339
Austin Borgered99f642023-06-01 16:51:35 -07001340std::string CameraService::resolveCameraId(
1341 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001342 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001343 const std::string& packageName) {
1344 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001345 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001346 packageNameVal = getPackageNameFromUid(clientUid);
1347 }
malikakash65d20692023-09-07 01:06:33 +00001348 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001349 // We shouldn't remap cameras for processes with system/vendor UIDs.
1350 return inputCameraId;
1351 }
malikakash82ed4352023-07-21 22:44:34 +00001352 Mutex::Autolock lock(mCameraIdRemappingLock);
1353 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1354 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001355 auto packageMap = packageMapIter->second;
1356 if (auto replacementIdIter = packageMap.find(inputCameraId);
1357 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001358 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001359 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001360 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001361 replacementIdIter->second.c_str());
1362 return replacementIdIter->second;
1363 }
1364 }
1365 return inputCameraId;
1366}
1367
Biswarup Pal37a75182024-01-16 15:53:35 +00001368std::optional<std::string> CameraService::resolveCameraId(
1369 const std::string& inputCameraId,
1370 int32_t deviceId,
1371 int32_t devicePolicy,
1372 int clientUid,
1373 const std::string& packageName) {
1374 if ((deviceId == kDefaultDeviceId)
1375 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1376 auto [storedDeviceId, _] =
1377 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1378 if (storedDeviceId != kDefaultDeviceId) {
1379 // Trying to access a virtual camera from default-policy device context, we should fail.
1380 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1381 inputCameraId.c_str(), deviceId);
1382 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1383 return std::nullopt;
1384 }
1385 return resolveCameraId(inputCameraId, clientUid, packageName);
1386 }
1387
1388 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1389}
1390
1391Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1392 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001393 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001394 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001395 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1396 if (cameraIdStr.empty()) {
1397 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1398 cameraId, deviceId);
1399 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1400 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1401 }
malikakashedb38962023-09-06 00:03:35 +00001402
Austin Borgered99f642023-06-01 16:51:35 -07001403 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001404 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1405 "characteristics for system only device %s: ", cameraIdStr.c_str());
1406 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001407
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001408 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001409 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001410 return STATUS_ERROR(ERROR_DISCONNECTED,
1411 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001412 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001413 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001414 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001415 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1416 if (hasSystemCameraPermissions) {
1417 cameraIdBound = mNumberOfCameras;
1418 }
1419 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001420 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1421 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422 }
1423
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001424 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001425 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001426 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001427 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001428 if (err != OK) {
1429 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1430 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1431 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001432 logServiceError(std::string("Error retrieving camera info from device ")
1433 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001434 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001435
Ruben Brunkcc776712015-02-17 20:18:47 -08001436 return ret;
1437}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001438
Biswarup Pal37a75182024-01-16 15:53:35 +00001439std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1440 int32_t deviceId, int32_t devicePolicy) {
1441 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1442 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1443 std::optional<std::string> cameraIdOptional =
1444 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1445 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1446 }
1447
1448 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001449 auto callingPid = getCallingPid();
1450 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001451 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1452 callingPid, callingUid, /* checkCameraPermissions= */ false);
1453 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001454 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001455 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001456 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1457 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1458 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001459 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001460 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001461
Biswarup Pal37a75182024-01-16 15:53:35 +00001462 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1463 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001464}
1465
Biswarup Pal37a75182024-01-16 15:53:35 +00001466std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1467 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001468 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001469 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001470}
1471
Austin Borgered99f642023-06-01 16:51:35 -07001472Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001473 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1474 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001475 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001476
Zhijun He2b59be82013-09-25 10:14:30 -07001477 if (!cameraInfo) {
1478 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001479 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001480 }
1481
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001482 if (!mInitialized) {
1483 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001484 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001485 return STATUS_ERROR(ERROR_DISCONNECTED,
1486 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001487 }
1488
Biswarup Pal37a75182024-01-16 15:53:35 +00001489 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1490 devicePolicy, getCallingUid());
1491 if (!cameraIdOptional.has_value()) {
1492 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1493 unresolvedCameraId.c_str(), deviceId);
1494 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1495 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1496 }
1497 std::string cameraId = cameraIdOptional.value();
1498
Austin Borgered99f642023-06-01 16:51:35 -07001499 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001500 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001501 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001502 }
1503
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001504 bool overrideForPerfClass =
1505 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001506 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001507 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001508 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001509 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001510 if (res == NAME_NOT_FOUND) {
1511 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001512 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001513 strerror(-res), res);
1514 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001515 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1516 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001517 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001518 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001519 strerror(-res), res);
1520 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001521 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001522
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001523 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001524}
1525
Biswarup Pal37a75182024-01-16 15:53:35 +00001526Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1527 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001528 ATRACE_CALL();
1529 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001530
Biswarup Pal37a75182024-01-16 15:53:35 +00001531 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1532 devicePolicy, getCallingUid());
1533 if (!cameraIdOptional.has_value()) {
1534 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1535 unresolvedCameraId.c_str(), deviceId);
1536 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1537 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1538 }
1539 std::string cameraId = cameraIdOptional.value();
1540
Rucha Katakwar38284522021-11-10 11:25:21 -08001541 if (!mInitialized) {
1542 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1543 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1544 }
1545
Biswarup Pal37a75182024-01-16 15:53:35 +00001546 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001547 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1548 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1549 }
1550
Austin Borgered99f642023-06-01 16:51:35 -07001551 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001552 if (res != OK) {
1553 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001554 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001555 strerror(-res), res);
1556 }
1557 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1558 return Status::ok();
1559}
1560
Austin Borgered99f642023-06-01 16:51:35 -07001561std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001562 time_t now = time(nullptr);
1563 char formattedTime[64];
1564 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001565 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001566}
1567
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001568Status CameraService::getCameraVendorTagDescriptor(
1569 /*out*/
1570 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001571 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001572 if (!mInitialized) {
1573 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001574 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001575 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001576 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1577 if (globalDescriptor != nullptr) {
1578 *desc = *(globalDescriptor.get());
1579 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001580 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001581}
1582
Emilian Peev71c73a22017-03-21 16:35:51 +00001583Status CameraService::getCameraVendorTagCache(
1584 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1585 ATRACE_CALL();
1586 if (!mInitialized) {
1587 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1588 return STATUS_ERROR(ERROR_DISCONNECTED,
1589 "Camera subsystem not available");
1590 }
1591 sp<VendorTagDescriptorCache> globalCache =
1592 VendorTagDescriptorCache::getGlobalVendorTagCache();
1593 if (globalCache != nullptr) {
1594 *cache = *(globalCache.get());
1595 }
1596 return Status::ok();
1597}
1598
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001599void CameraService::clearCachedVariables() {
1600 BasicClient::BasicClient::sCameraService = nullptr;
1601}
1602
Austin Borgered99f642023-06-01 16:51:35 -07001603std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001604 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001605 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001606
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001607 int deviceVersion = 0;
1608
Emilian Peevf53f66e2017-04-11 14:29:43 +01001609 status_t res;
1610 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001611 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001612 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001613 if (res != OK || transport == IPCTransport::INVALID) {
1614 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001615 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001616 return std::make_pair(-1, IPCTransport::INVALID) ;
1617 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001618 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001619
Emilian Peevf53f66e2017-04-11 14:29:43 +01001620 hardware::CameraInfo info;
1621 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001622 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001623 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001624 if (res != OK) {
1625 return std::make_pair(-1, IPCTransport::INVALID);
1626 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001627 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001628 if (orientation) {
1629 *orientation = info.orientation;
1630 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001631 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001632
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001633 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001634}
1635
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001636Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001637 switch(err) {
1638 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001639 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001640 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001641 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1642 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001643 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001644 return STATUS_ERROR(ERROR_DISCONNECTED,
1645 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001646 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001647 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1648 "Camera HAL encountered error %d: %s",
1649 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001650 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001651}
1652
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001653Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001654 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1655 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001656 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001657 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001658 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001659 bool forceSlowJpegMode, const std::string& originalCameraId,
1660 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001661 // For HIDL devices
1662 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1663 // Create CameraClient based on device version reported by the HAL.
1664 int deviceVersion = deviceVersionAndTransport.first;
1665 switch(deviceVersion) {
1666 case CAMERA_DEVICE_API_VERSION_1_0:
1667 ALOGE("Camera using old HAL version: %d", deviceVersion);
1668 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1669 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001670 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001671 break;
1672 case CAMERA_DEVICE_API_VERSION_3_0:
1673 case CAMERA_DEVICE_API_VERSION_3_1:
1674 case CAMERA_DEVICE_API_VERSION_3_2:
1675 case CAMERA_DEVICE_API_VERSION_3_3:
1676 case CAMERA_DEVICE_API_VERSION_3_4:
1677 case CAMERA_DEVICE_API_VERSION_3_5:
1678 case CAMERA_DEVICE_API_VERSION_3_6:
1679 case CAMERA_DEVICE_API_VERSION_3_7:
1680 break;
1681 default:
1682 // Should not be reachable
1683 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1684 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1685 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001686 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001687 }
1688 }
1689 if (effectiveApiLevel == API_1) { // Camera1 API route
1690 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001691 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001692 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001693 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001694 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1695 forceSlowJpegMode);
1696 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1697 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001698 } else { // Camera2 API route
1699 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1700 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001701 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001702 cameraService->mCameraServiceProxyWrapper,
1703 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001704 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001705 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001706 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001707 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001708 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001709}
1710
Austin Borgered99f642023-06-01 16:51:35 -07001711std::string CameraService::toString(std::set<userid_t> intSet) {
1712 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001713 bool first = true;
1714 for (userid_t i : intSet) {
1715 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001716 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001717 first = false;
1718 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001719 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001720 }
1721 }
Austin Borgered99f642023-06-01 16:51:35 -07001722 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001723}
1724
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001725int32_t CameraService::mapToInterface(TorchModeStatus status) {
1726 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1727 switch (status) {
1728 case TorchModeStatus::NOT_AVAILABLE:
1729 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1730 break;
1731 case TorchModeStatus::AVAILABLE_OFF:
1732 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1733 break;
1734 case TorchModeStatus::AVAILABLE_ON:
1735 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1736 break;
1737 default:
1738 ALOGW("Unknown new flash status: %d", status);
1739 }
1740 return serviceStatus;
1741}
1742
1743CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1744 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1745 switch (status) {
1746 case CameraDeviceStatus::NOT_PRESENT:
1747 serviceStatus = StatusInternal::NOT_PRESENT;
1748 break;
1749 case CameraDeviceStatus::PRESENT:
1750 serviceStatus = StatusInternal::PRESENT;
1751 break;
1752 case CameraDeviceStatus::ENUMERATING:
1753 serviceStatus = StatusInternal::ENUMERATING;
1754 break;
1755 default:
1756 ALOGW("Unknown new HAL device status: %d", status);
1757 }
1758 return serviceStatus;
1759}
1760
1761int32_t CameraService::mapToInterface(StatusInternal status) {
1762 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1763 switch (status) {
1764 case StatusInternal::NOT_PRESENT:
1765 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1766 break;
1767 case StatusInternal::PRESENT:
1768 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1769 break;
1770 case StatusInternal::ENUMERATING:
1771 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1772 break;
1773 case StatusInternal::NOT_AVAILABLE:
1774 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1775 break;
1776 case StatusInternal::UNKNOWN:
1777 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1778 break;
1779 default:
1780 ALOGW("Unknown new internal device status: %d", status);
1781 }
1782 return serviceStatus;
1783}
1784
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001785Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001786 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001787
Austin Borgered99f642023-06-01 16:51:35 -07001788 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001789 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001790 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001791 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001792 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1793 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001794 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001795 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001796 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001797 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001798 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001799 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001800 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001801}
1802
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001803Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001804 /*out*/
1805 CameraParameters* parameters) {
1806
1807 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1808
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001809 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001810
1811 if (parameters == NULL) {
1812 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001813 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001814 }
1815
malikakashedb38962023-09-06 00:03:35 +00001816 std::string unresolvedCameraId = std::to_string(cameraId);
1817 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001818 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001819
1820 // Check if we already have parameters
1821 {
1822 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001823 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001824 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001825 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001826 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001827 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001828 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001829 }
1830 CameraParameters p = cameraState->getShimParams();
1831 if (!p.isEmpty()) {
1832 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001833 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001834 }
1835 }
1836
Austin Borger22c5c852024-03-08 13:31:36 -08001837 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001838 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001839 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001840 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001841 // Error already logged by callee
1842 return ret;
1843 }
1844
1845 // Check for parameters again
1846 {
1847 // Scope for service lock
1848 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001849 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001850 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001851 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001852 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001853 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001854 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001855 CameraParameters p = cameraState->getShimParams();
1856 if (!p.isEmpty()) {
1857 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001858 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001859 }
1860 }
1861
Ruben Brunkcc776712015-02-17 20:18:47 -08001862 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1863 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001864 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001865}
1866
Austin Borgered99f642023-06-01 16:51:35 -07001867Status CameraService::validateConnectLocked(const std::string& cameraId,
1868 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001869 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001870
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001871#ifdef __BRILLO__
1872 UNUSED(clientName8);
1873 UNUSED(clientUid);
1874 UNUSED(clientPid);
1875 UNUSED(originalClientPid);
1876#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001877 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1878 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001879 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001880 return allowed;
1881 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001882#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001883
Austin Borger22c5c852024-03-08 13:31:36 -08001884 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001885
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001886 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001887 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1888 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001889 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001890 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001891 }
1892
Ruben Brunkcc776712015-02-17 20:18:47 -08001893 if (getCameraState(cameraId) == nullptr) {
1894 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001895 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001896 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001897 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001898 }
1899
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001900 status_t err = checkIfDeviceIsUsable(cameraId);
1901 if (err != NO_ERROR) {
1902 switch(err) {
1903 case -ENODEV:
1904 case -EBUSY:
1905 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001906 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001907 default:
1908 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001909 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001910 }
1911 }
1912 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001913}
1914
Austin Borgered99f642023-06-01 16:51:35 -07001915Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1916 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001917 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001918 int callingPid = getCallingPid();
1919 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001920
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001921 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001922 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001923 clientUid = callingUid;
1924 } else if (!isTrustedCallingUid(callingUid)) {
1925 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1926 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001927 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1928 "Untrusted caller (calling PID %d, UID %d) trying to "
1929 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001930 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001931 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001932 }
1933
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001934 // Check if we can trust clientPid
1935 if (clientPid == USE_CALLING_PID) {
1936 clientPid = callingPid;
1937 } else if (!isTrustedCallingUid(callingUid)) {
1938 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1939 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001940 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1941 "Untrusted caller (calling PID %d, UID %d) trying to "
1942 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001943 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001944 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001945 }
1946
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001947 if (shouldRejectSystemCameraConnection(cameraId)) {
1948 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1949 cameraId.c_str());
1950 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001951 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001952 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001953 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1954 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001955 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001956 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001957 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001958 }
1959
Biswarup Pale506e732024-03-27 13:46:20 +00001960 // Get the device id that owns this camera.
1961 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1962
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001963 // If it's not calling from cameraserver, check the permission if the
1964 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1965 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001966 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001967 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001968 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001969 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001970 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001971 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1972 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001973 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001974 }
1975
Svet Ganova453d0d2018-01-11 15:37:58 -08001976 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001977 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001978 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001979 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1980 clientPid, clientUid);
1981 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001982 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1983 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001984 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001985 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001986 }
1987
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001988 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1989 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1990 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1991 if ((!isAutomotivePrivilegedClient(callingUid) ||
1992 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1993 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001994 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1995 return STATUS_ERROR_FMT(ERROR_DISABLED,
1996 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001997 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001998 }
1999
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002000 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
2001 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07002002 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002003 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002004
Ruben Brunk6267b532015-04-30 17:44:07 -07002005 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08002006
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002007 // For non-system clients : Only allow clients who are being used by the current foreground
2008 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08002009 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08002010 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002011 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
2012 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07002013 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002014 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2015 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002016 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07002017 }
2018
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002019 if (flags::camera_hsum_permission()) {
2020 // If the System User tries to access the camera when the device is running in
2021 // headless system user mode, ensure that client has the required permission
2022 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07002023 if (isHeadlessSystemUserMode()
2024 && (clientUserId == USER_SYSTEM)
2025 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002026 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
2027 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2028 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
2029 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07002030 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002031 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07002032 }
2033
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002034 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002035}
2036
Austin Borgered99f642023-06-01 16:51:35 -07002037status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002038 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08002039 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08002040 if (cameraState == nullptr) {
2041 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002042 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002043 return -ENODEV;
2044 }
2045
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002046 StatusInternal currentStatus = cameraState->getStatus();
2047 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002048 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002049 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002050 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002051 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002052 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002053 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002054 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002055 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002056
Ruben Brunkcc776712015-02-17 20:18:47 -08002057 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002058}
2059
Ruben Brunkcc776712015-02-17 20:18:47 -08002060void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002061 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002062
Ruben Brunkcc776712015-02-17 20:18:47 -08002063 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002064 auto clientDescriptor =
2065 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002066 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002067 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2068
2069 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002070 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002071
2072 if (evicted.size() > 0) {
2073 // This should never happen - clients should already have been removed in disconnect
2074 for (auto& i : evicted) {
2075 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002076 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002077 }
2078
2079 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2080 __FUNCTION__);
2081 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002082
2083 // And register a death notification for the client callback. Do
2084 // this last to avoid Binder policy where a nested Binder
2085 // transaction might be pre-empted to service the client death
2086 // notification if the client process dies before linkToDeath is
2087 // invoked.
2088 sp<IBinder> remoteCallback = client->getRemote();
2089 if (remoteCallback != nullptr) {
2090 remoteCallback->linkToDeath(this);
2091 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002092}
2093
Austin Borgered99f642023-06-01 16:51:35 -07002094status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2095 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2096 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002097 /*out*/
2098 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002099 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002100 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002101 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002102 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002103 DescriptorPtr clientDescriptor;
2104 {
2105 if (effectiveApiLevel == API_1) {
2106 // If we are using API1, any existing client for this camera ID with the same remote
2107 // should be returned rather than evicted to allow MediaRecorder to work properly.
2108
2109 auto current = mActiveClientManager.get(cameraId);
2110 if (current != nullptr) {
2111 auto clientSp = current->getValue();
2112 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002113 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002114 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002115 " API level, evicting prior client...");
2116 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002117 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002118 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002119 *client = clientSp;
2120 return NO_ERROR;
2121 }
2122 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002123 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002124 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002125
Ruben Brunkcc776712015-02-17 20:18:47 -08002126 // Get state for the given cameraId
2127 auto state = getCameraState(cameraId);
2128 if (state == nullptr) {
2129 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002130 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002131 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002132 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002133 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002134
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002135 sp<IServiceManager> sm = defaultServiceManager();
2136 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002137 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002138 // If processinfo service is not available and the client is automotive privileged
2139 // client used for safety critical uses cases such as rear-view and surround-view which
2140 // needs to be available before android boot completes, then use the hardcoded values
2141 // for the process state and priority score. As this scenario is before android system
2142 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2143 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2144 // visible on the top.
2145 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2146 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2147 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2148 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2149 } else {
2150 // Get current active client PIDs
2151 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2152 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002153
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002154 std::vector<int> priorityScores(ownerPids.size());
2155 std::vector<int> states(ownerPids.size());
2156
2157 // Get priority scores of all active PIDs
2158 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2159 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2160 if (err != OK) {
2161 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2162 return err;
2163 }
2164
2165 // Update all active clients' priorities
2166 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2167 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2168 pidToPriorityMap.emplace(ownerPids[i],
2169 resource_policy::ClientPriority(priorityScores[i], states[i],
2170 /* isVendorClient won't get copied over*/ false,
2171 /* oomScoreOffset won't get copied over*/ 0));
2172 }
2173 mActiveClientManager.updatePriorities(pidToPriorityMap);
2174
2175 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2176 int32_t actualState = states[states.size() - 1];
2177
2178 // Make descriptor for incoming client. We store the oomScoreOffset
2179 // since we might need it later on new handleEvictionsLocked and
2180 // ProcessInfoService would not take that into account.
2181 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2182 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2183 state->getConflicting(), actualScore, clientPid, actualState,
2184 oomScoreOffset, systemNativeClient);
2185 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002186
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002187 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2188
Ruben Brunkcc776712015-02-17 20:18:47 -08002189 // Find clients that would be evicted
2190 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2191
2192 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2193 // background, so we cannot do evictions
2194 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2195 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2196 " priority).", clientPid);
2197
2198 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002199 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002200 auto incompatibleClients =
2201 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2202
Austin Borgered99f642023-06-01 16:51:35 -07002203 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2204 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2205 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002206 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002207
2208 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002209 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002210 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002211 i->getKey().c_str(),
2212 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002213 i->getOwnerId(), i->getPriority().getScore(),
2214 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002215 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002216 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2217 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002218 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002219 }
2220
2221 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002222 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002223 mEventLog.add(msg);
2224
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002225 auto current = mActiveClientManager.get(cameraId);
2226 if (current != nullptr) {
2227 return -EBUSY; // CAMERA_IN_USE
2228 } else {
2229 return -EUSERS; // MAX_CAMERAS_IN_USE
2230 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002231 }
2232
2233 for (auto& i : evicted) {
2234 sp<BasicClient> clientSp = i->getValue();
2235 if (clientSp.get() == nullptr) {
2236 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2237
2238 // TODO: Remove this
2239 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2240 __FUNCTION__);
2241 mActiveClientManager.remove(i);
2242 continue;
2243 }
2244
2245 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002246 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002247 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002248
Ruben Brunkcc776712015-02-17 20:18:47 -08002249 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002250 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002251 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2252 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002253 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002254 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002255 i->getPriority().getState(), cameraId.c_str(),
2256 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002257 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002258
2259 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002260 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002261 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002262 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002263 }
2264
Ruben Brunkcc776712015-02-17 20:18:47 -08002265 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2266 // other clients from connecting in mServiceLockWrapper if held
2267 mServiceLock.unlock();
2268
2269 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002270 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002271
2272 // Destroy evicted clients
2273 for (auto& i : evictedClients) {
2274 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002275 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002276 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002277
Austin Borger22c5c852024-03-08 13:31:36 -08002278 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002279
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002280 for (const auto& i : evictedClients) {
2281 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002282 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002283 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2284 if (ret == TIMED_OUT) {
2285 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002286 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2287 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002288 return -EBUSY;
2289 }
2290 if (ret != NO_ERROR) {
2291 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002292 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2293 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002294 return ret;
2295 }
2296 }
2297
2298 evictedClients.clear();
2299
Ruben Brunkcc776712015-02-17 20:18:47 -08002300 // Once clients have been disconnected, relock
2301 mServiceLock.lock();
2302
2303 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2304 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2305 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002306 }
2307
Ruben Brunkcc776712015-02-17 20:18:47 -08002308 *partial = clientDescriptor;
2309 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002310}
2311
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002312Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002313 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002314 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002315 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002316 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002317 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002318 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002319 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002320 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002321 int32_t deviceId,
2322 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002323 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002324 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002325 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002326 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002327
Biswarup Pal37a75182024-01-16 15:53:35 +00002328 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2329 if (cameraIdStr.empty()) {
2330 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2331 api1CameraId, deviceId);
2332 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2333 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2334 }
malikakashedb38962023-09-06 00:03:35 +00002335
Ruben Brunkcc776712015-02-17 20:18:47 -08002336 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002337 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2338 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002339 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002340 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002341
Biswarup Pal37a75182024-01-16 15:53:35 +00002342 if (!ret.isOk()) {
2343 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002344 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002345 }
2346
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002347 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002348
2349 const sp<IServiceManager> sm(defaultServiceManager());
2350 const auto& mActivityManager = getActivityManager();
2351 if (mActivityManager) {
2352 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002353 getCallingUid(),
2354 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002355 }
2356
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002357 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002358}
2359
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002360bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2361 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002362 // If the client is not a vendor client, don't add listener if
2363 // a) the camera is a publicly hidden secure camera OR
2364 // b) the camera is a system only camera and the client doesn't
2365 // have android.permission.SYSTEM_CAMERA permissions.
2366 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2367 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002368 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002369 return true;
2370 }
2371 return false;
2372}
2373
Austin Borgered99f642023-06-01 16:51:35 -07002374bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002375 // Rules for rejection:
2376 // 1) If cameraserver tries to access this camera device, accept the
2377 // connection.
2378 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002379 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002380 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2381 // and the serving thread is a non hwbinder thread, the client must have
2382 // android.permission.SYSTEM_CAMERA permissions to connect.
2383
Austin Borger22c5c852024-03-08 13:31:36 -08002384 int cPid = getCallingPid();
2385 int cUid = getCallingUid();
2386 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002387 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2388 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002389 // This isn't a known camera ID, so it's not a system camera
2390 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2391 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002392 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002393
2394 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002395 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002396 return false;
2397 }
2398 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002399 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002400 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2401 return true;
2402 }
2403 // (3) Here we only check for permissions if it is a system only camera device. This is since
2404 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2405 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2406 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002407 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002408 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002409 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2410 cameraId.c_str());
2411 return true;
2412 }
2413
2414 return false;
2415}
2416
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002417Status CameraService::connectDevice(
2418 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002419 const std::string& unresolvedCameraId,
2420 const std::string& clientPackageName,
2421 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002422 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002423 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002424 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002425 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002426 ATRACE_CALL();
Emilian Peev31bd2422024-04-23 22:24:09 +00002427 RunThreadWithRealtimePriority priorityBump;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002428 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002429 sp<CameraDeviceClient> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002430 std::string clientPackageNameAdj = clientPackageName;
Austin Borger22c5c852024-03-08 13:31:36 -08002431 int callingPid = getCallingPid();
2432 int callingUid = getCallingUid();
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002433 bool systemNativeClient = false;
Austin Borger22c5c852024-03-08 13:31:36 -08002434 if (callerHasSystemUid() && (clientPackageNameAdj.size() == 0)) {
Austin Borger249e6592024-03-10 22:28:11 -07002435 std::string systemClient = fmt::sprintf("client.pid<%d>", callingPid);
Austin Borgered99f642023-06-01 16:51:35 -07002436 clientPackageNameAdj = systemClient;
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002437 systemNativeClient = true;
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002438 }
Austin Borger249e6592024-03-10 22:28:11 -07002439
Biswarup Pal37a75182024-01-16 15:53:35 +00002440 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
2441 devicePolicy, callingUid, clientPackageNameAdj);
2442 if (!cameraIdOptional.has_value()) {
2443 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
2444 unresolvedCameraId.c_str(), deviceId);
2445 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2446 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2447 }
2448 std::string cameraId = cameraIdOptional.value();
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002449
2450 if (oomScoreOffset < 0) {
Austin Borgered99f642023-06-01 16:51:35 -07002451 std::string msg =
2452 fmt::sprintf("Cannot increase the priority of a client %s pid %d for "
2453 "camera id %s", clientPackageNameAdj.c_str(), callingPid,
2454 cameraId.c_str());
2455 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2456 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002457 }
2458
Austin Borger9bfa0a72022-08-03 17:50:40 -07002459 userid_t clientUserId = multiuser_get_user_id(clientUid);
Austin Borger9bfa0a72022-08-03 17:50:40 -07002460 if (clientUid == USE_CALLING_UID) {
2461 clientUserId = multiuser_get_user_id(callingUid);
2462 }
2463
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002464 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
2465 // such as rear view and surround view cannot be disabled.
Austin Borger1c1bee02023-06-01 16:51:35 -07002466 if ((!isAutomotivePrivilegedClient(callingUid) || !isAutomotiveExteriorSystemCamera(cameraId))
2467 && mCameraServiceProxyWrapper->isCameraDisabled(clientUserId)) {
Austin Borgered99f642023-06-01 16:51:35 -07002468 std::string msg = "Camera disabled by device policy";
2469 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2470 return STATUS_ERROR(ERROR_DISABLED, msg.c_str());
Austin Borger5f7abe22022-04-26 15:55:10 -07002471 }
2472
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002473 // enforce system camera permissions
Austin Borger1c1bee02023-06-01 16:51:35 -07002474 if (oomScoreOffset > 0
2475 && !hasPermissionsForSystemCamera(cameraId, callingPid,
Austin Borger249e6592024-03-10 22:28:11 -07002476 callingUid)
2477 && !isTrustedCallingUid(callingUid)) {
Austin Borgered99f642023-06-01 16:51:35 -07002478 std::string msg = fmt::sprintf("Cannot change the priority of a client %s pid %d for "
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002479 "camera id %s without SYSTEM_CAMERA permissions",
Austin Borgered99f642023-06-01 16:51:35 -07002480 clientPackageNameAdj.c_str(), callingPid, cameraId.c_str());
2481 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2482 return STATUS_ERROR(ERROR_PERMISSION_DENIED, msg.c_str());
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002483 }
2484
Austin Borgered99f642023-06-01 16:51:35 -07002485 ret = connectHelper<hardware::camera2::ICameraDeviceCallbacks,CameraDeviceClient>(cameraCb,
2486 cameraId, /*api1CameraId*/-1, clientPackageNameAdj, systemNativeClient, clientFeatureId,
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002487 clientUid, USE_CALLING_PID, API_2, /*shimUpdateOnly*/ false, oomScoreOffset,
malikakash73125c62023-07-21 22:44:34 +00002488 targetSdkVersion, overrideToPortrait, /*forceSlowJpegMode*/false, unresolvedCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002489 /*out*/client);
Ruben Brunkcc776712015-02-17 20:18:47 -08002490
Biswarup Pal37a75182024-01-16 15:53:35 +00002491 if (!ret.isOk()) {
Austin Borgered99f642023-06-01 16:51:35 -07002492 logRejected(cameraId, callingPid, clientPackageNameAdj, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002493 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002494 }
2495
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002496 *device = client;
Rucha Katakwardf223072021-06-15 10:21:00 -07002497 Mutex::Autolock lock(mServiceLock);
2498
2499 // Clear the previous cached logs and reposition the
2500 // file offset to beginning of the file to log new data.
2501 // If either truncate or lseek fails, close the previous file and create a new one.
2502 if ((ftruncate(mMemFd, 0) == -1) || (lseek(mMemFd, 0, SEEK_SET) == -1)) {
2503 ALOGE("%s: Error while truncating the file: %s", __FUNCTION__, sFileName);
2504 // Close the previous memfd.
2505 close(mMemFd);
2506 // If failure to wipe the data, then create a new file and
2507 // assign the new value to mMemFd.
2508 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
2509 if (mMemFd == -1) {
2510 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
2511 }
2512 }
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002513 const sp<IServiceManager> sm(defaultServiceManager());
2514 const auto& mActivityManager = getActivityManager();
2515 if (mActivityManager) {
2516 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger249e6592024-03-10 22:28:11 -07002517 callingUid,
2518 callingPid);
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002519 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002520 return ret;
Chien-Yu Chen88da5262015-02-17 13:56:46 -08002521}
2522
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002523bool CameraService::isCameraPrivacyEnabled(const String16& packageName, const std::string& cam_id,
2524 int callingPid, int callingUid) {
2525 if (!isAutomotiveDevice()) {
2526 return mSensorPrivacyPolicy->isCameraPrivacyEnabled();
2527 }
2528
2529 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for
2530 // safety-critical use cases cannot be disabled and are exempt from camera privacy policy.
2531 if ((isAutomotivePrivilegedClient(callingUid) && isAutomotiveExteriorSystemCamera(cam_id))) {
2532 ALOGI("Camera privacy cannot be enabled for automotive privileged client %d "
2533 "using camera %s", callingUid, cam_id.c_str());
2534 return false;
2535 }
2536
2537 if (mSensorPrivacyPolicy->isCameraPrivacyEnabled(packageName)) {
2538 return true;
2539 } else if (mSensorPrivacyPolicy->getCameraPrivacyState() == SensorPrivacyManager::DISABLED) {
2540 return false;
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08002541 } else if (mSensorPrivacyPolicy->getCameraPrivacyState()
2542 == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002543 if (hasPermissionsForCameraPrivacyAllowlist(callingPid, callingUid)) {
2544 return false;
2545 } else {
2546 return true;
2547 }
2548 }
2549 return false;
2550}
2551
Austin Borgered99f642023-06-01 16:51:35 -07002552std::string CameraService::getPackageNameFromUid(int clientUid) {
2553 std::string packageName("");
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002554
Avichal Rakesh5788fec2024-03-15 14:39:20 -07002555 sp<IPermissionController> permCtrl;
2556 if (flags::cache_permission_services()) {
2557 permCtrl = getPermissionController();
2558 } else {
2559 sp<IServiceManager> sm = defaultServiceManager();
2560#pragma clang diagnostic push
2561#pragma clang diagnostic ignored "-Wdeprecated-declarations"
2562 // Using deprecated function to preserve functionality until the
2563 // cache_permission_services flag is removed.
2564 sp<IBinder> binder = sm->getService(toString16(kPermissionServiceName));
2565#pragma clang diagnostic pop
2566 if (binder == 0) {
2567 ALOGE("Cannot get permission service");
2568 permCtrl = nullptr;
2569 } else {
2570 permCtrl = interface_cast<IPermissionController>(binder);
2571 }
2572 }
2573
2574 if (permCtrl == nullptr) {
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002575 // Return empty package name and the further interaction
2576 // with camera will likely fail
2577 return packageName;
2578 }
2579
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002580 Vector<String16> packages;
2581
2582 permCtrl->getPackagesForUid(clientUid, packages);
2583
2584 if (packages.isEmpty()) {
2585 ALOGE("No packages for calling UID %d", clientUid);
2586 // Return empty package name and the further interaction
2587 // with camera will likely fail
2588 return packageName;
2589 }
2590
2591 // Arbitrarily pick the first name in the list
Austin Borgered99f642023-06-01 16:51:35 -07002592 packageName = toStdString(packages[0]);
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002593
2594 return packageName;
2595}
2596
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002597template<class CALLBACK, class CLIENT>
Austin Borgered99f642023-06-01 16:51:35 -07002598Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const std::string& cameraId,
2599 int api1CameraId, const std::string& clientPackageNameMaybe, bool systemNativeClient,
2600 const std::optional<std::string>& clientFeatureId, int clientUid, int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002601 apiLevel effectiveApiLevel, bool shimUpdateOnly, int oomScoreOffset, int targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002602 bool overrideToPortrait, bool forceSlowJpegMode, const std::string& originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002603 /*out*/sp<CLIENT>& device) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002604 binder::Status ret = binder::Status::ok();
2605
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002606 bool isNonSystemNdk = false;
Austin Borgered99f642023-06-01 16:51:35 -07002607 std::string clientPackageName;
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002608 int packageUid = (clientUid == USE_CALLING_UID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002609 getCallingUid() : clientUid;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002610 if (clientPackageNameMaybe.size() <= 0) {
2611 // NDK calls don't come with package names, but we need one for various cases.
2612 // Generally, there's a 1:1 mapping between UID and package name, but shared UIDs
2613 // do exist. For all authentication cases, all packages under the same UID get the
2614 // same permissions, so picking any associated package name is sufficient. For some
2615 // other cases, this may give inaccurate names for clients in logs.
2616 isNonSystemNdk = true;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002617 clientPackageName = getPackageNameFromUid(packageUid);
2618 } else {
2619 clientPackageName = clientPackageNameMaybe;
2620 }
2621
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002622 int originalClientPid = 0;
2623
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002624 int packagePid = (clientPid == USE_CALLING_PID) ?
Austin Borger22c5c852024-03-08 13:31:36 -08002625 getCallingPid() : clientPid;
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002626 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) and "
Austin Borgered99f642023-06-01 16:51:35 -07002627 "Camera API version %d", packagePid, clientPackageName.c_str(), cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002628 static_cast<int>(effectiveApiLevel));
2629
Shuzhen Wang316781a2020-08-18 18:11:01 -07002630 nsecs_t openTimeNs = systemTime();
2631
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002632 sp<CLIENT> client = nullptr;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002633 int facing = -1;
Emilian Peevb91f1802021-03-23 14:50:28 -07002634 int orientation = 0;
Eino-Ville Talvala58106af2022-09-23 16:51:06 -07002635
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002636 {
2637 // Acquire mServiceLock and prevent other clients from connecting
2638 std::unique_ptr<AutoConditionLock> lock =
2639 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2640
2641 if (lock == nullptr) {
2642 ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
2643 , clientPid);
2644 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2645 "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
Austin Borgered99f642023-06-01 16:51:35 -07002646 cameraId.c_str(), clientPackageName.c_str(), clientPid);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002647 }
2648
Eino-Ville Talvala0bdfa282020-06-19 13:54:35 -07002649 // Enforce client permissions and do basic validity checks
Biswarup Pal37a75182024-01-16 15:53:35 +00002650 if (!(ret = validateConnectLocked(cameraId, clientPackageName,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002651 /*inout*/clientUid, /*inout*/clientPid, /*out*/originalClientPid)).isOk()) {
2652 return ret;
2653 }
2654
2655 // Check the shim parameters after acquiring lock, if they have already been updated and
2656 // we were doing a shim update, return immediately
2657 if (shimUpdateOnly) {
2658 auto cameraState = getCameraState(cameraId);
2659 if (cameraState != nullptr) {
2660 if (!cameraState->getShimParams().isEmpty()) return ret;
2661 }
2662 }
2663
2664 status_t err;
2665
2666 sp<BasicClient> clientTmp = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002667 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>> partial;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002668 if ((err = handleEvictionsLocked(cameraId, originalClientPid, effectiveApiLevel,
Austin Borgered99f642023-06-01 16:51:35 -07002669 IInterface::asBinder(cameraCb), clientPackageName, oomScoreOffset,
2670 systemNativeClient, /*out*/&clientTmp, /*out*/&partial)) != NO_ERROR) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002671 switch (err) {
2672 case -ENODEV:
2673 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2674 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002675 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002676 case -EBUSY:
2677 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
2678 "Higher-priority client using camera, ID \"%s\" currently unavailable",
Austin Borgered99f642023-06-01 16:51:35 -07002679 cameraId.c_str());
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002680 case -EUSERS:
2681 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2682 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002683 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002684 default:
2685 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
2686 "Unexpected error %s (%d) opening camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002687 strerror(-err), err, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002688 }
2689 }
2690
2691 if (clientTmp.get() != nullptr) {
2692 // Handle special case for API1 MediaRecorder where the existing client is returned
2693 device = static_cast<CLIENT*>(clientTmp.get());
2694 return ret;
2695 }
2696
2697 // give flashlight a chance to close devices if necessary.
2698 mFlashlight->prepareDeviceOpen(cameraId);
2699
Austin Borger18b30a72022-10-27 12:20:29 -07002700 int portraitRotation;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002701 auto deviceVersionAndTransport =
Austin Borger18b30a72022-10-27 12:20:29 -07002702 getDeviceVersion(cameraId, overrideToPortrait, /*out*/&portraitRotation,
2703 /*out*/&facing, /*out*/&orientation);
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002704 if (facing == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07002705 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002706 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002707 "Unable to get camera device \"%s\" facing", cameraId.c_str());
Eino-Ville Talvala6963d0a2017-01-31 13:00:34 -08002708 }
2709
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002710 sp<BasicClient> tmp = nullptr;
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002711 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
Austin Borgered99f642023-06-01 16:51:35 -07002712 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002713 if(!(ret = makeClient(this, cameraCb, clientPackageName, systemNativeClient,
Austin Borgered99f642023-06-01 16:51:35 -07002714 clientFeatureId, cameraId, api1CameraId, facing,
2715 orientation, clientPid, clientUid, getpid(),
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00002716 deviceVersionAndTransport, effectiveApiLevel, overrideForPerfClass,
malikakash82ed4352023-07-21 22:44:34 +00002717 overrideToPortrait, forceSlowJpegMode, originalCameraId,
Chengfei Taobe683db2023-01-31 18:52:49 +00002718 /*out*/&tmp)).isOk()) {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002719 return ret;
2720 }
2721 client = static_cast<CLIENT*>(tmp.get());
2722
2723 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
2724 __FUNCTION__);
2725
Austin Borgered99f642023-06-01 16:51:35 -07002726 std::string monitorTags = isClientWatched(client.get()) ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002727 err = client->initialize(mCameraProviderManager, monitorTags);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08002728 if (err != OK) {
2729 ALOGE("%s: Could not initialize client from HAL.", __FUNCTION__);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002730 // Errors could be from the HAL module open call or from AppOpsManager
Kwangkyu Parkb1aaf9a2023-07-08 00:42:03 +09002731 mServiceLock.unlock();
2732 client->disconnect();
2733 mServiceLock.lock();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002734 switch(err) {
2735 case BAD_VALUE:
2736 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07002737 "Illegal argument to HAL module for camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002738 case -EBUSY:
2739 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
Austin Borgered99f642023-06-01 16:51:35 -07002740 "Camera \"%s\" is already open", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002741 case -EUSERS:
2742 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
2743 "Too many cameras already open, cannot open camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002744 cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002745 case PERMISSION_DENIED:
2746 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Austin Borgered99f642023-06-01 16:51:35 -07002747 "No permission to open camera \"%s\"", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002748 case -EACCES:
2749 return STATUS_ERROR_FMT(ERROR_DISABLED,
Austin Borgered99f642023-06-01 16:51:35 -07002750 "Camera \"%s\" disabled by policy", cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002751 case -ENODEV:
2752 default:
2753 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07002754 "Failed to initialize camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002755 strerror(-err), err);
2756 }
2757 }
2758
2759 // Update shim paremeters for legacy clients
2760 if (effectiveApiLevel == API_1) {
2761 // Assume we have always received a Client subclass for API1
2762 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
2763 String8 rawParams = shimClient->getParameters();
2764 CameraParameters params(rawParams);
2765
2766 auto cameraState = getCameraState(cameraId);
2767 if (cameraState != nullptr) {
2768 cameraState->setShimParams(params);
2769 } else {
2770 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
Austin Borgered99f642023-06-01 16:51:35 -07002771 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002772 }
2773 }
2774
Ravneetaeb20dc2022-03-30 05:33:03 +00002775 // Enable/disable camera service watchdog
2776 client->setCameraServiceWatchdog(mCameraServiceWatchdogEnabled);
2777
Emilian Peev6d45db82024-01-18 20:11:54 +00002778 CameraMetadata chars;
2779 bool rotateAndCropSupported = true;
2780 err = mCameraProviderManager->getCameraCharacteristics(cameraId, overrideForPerfClass,
2781 &chars, overrideToPortrait);
2782 if (err == OK) {
2783 auto availableRotateCropEntry = chars.find(
2784 ANDROID_SCALER_AVAILABLE_ROTATE_AND_CROP_MODES);
2785 if (availableRotateCropEntry.count <= 1) {
2786 rotateAndCropSupported = false;
Austin Borger18b30a72022-10-27 12:20:29 -07002787 }
Emilian Peev13f35ad2022-04-27 11:28:48 -07002788 } else {
Emilian Peev6d45db82024-01-18 20:11:54 +00002789 ALOGE("%s: Unable to query static metadata for camera %s: %s (%d)", __FUNCTION__,
2790 cameraId.c_str(), strerror(-err), err);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00002791 }
2792
Emilian Peev6d45db82024-01-18 20:11:54 +00002793 if (rotateAndCropSupported) {
2794 // Set rotate-and-crop override behavior
2795 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2796 client->setRotateAndCropOverride(mOverrideRotateAndCropMode);
2797 } else if (overrideToPortrait && portraitRotation != 0) {
2798 uint8_t rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO;
2799 switch (portraitRotation) {
2800 case 90:
2801 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_90;
2802 break;
2803 case 180:
2804 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_180;
2805 break;
2806 case 270:
2807 rotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_270;
2808 break;
2809 default:
2810 ALOGE("Unexpected portrait rotation: %d", portraitRotation);
2811 break;
2812 }
2813 client->setRotateAndCropOverride(rotateAndCropMode);
2814 } else {
2815 client->setRotateAndCropOverride(
2816 mCameraServiceProxyWrapper->getRotateAndCropOverride(
2817 clientPackageName, facing, multiuser_get_user_id(clientUid)));
2818 }
2819 }
2820
2821 bool autoframingSupported = true;
2822 auto availableAutoframingEntry = chars.find(ANDROID_CONTROL_AUTOFRAMING_AVAILABLE);
2823 if ((availableAutoframingEntry.count == 1) && (availableAutoframingEntry.data.u8[0] ==
2824 ANDROID_CONTROL_AUTOFRAMING_AVAILABLE_FALSE)) {
2825 autoframingSupported = false;
2826 }
2827
2828 if (autoframingSupported) {
2829 // Set autoframing override behaviour
2830 if (mOverrideAutoframingMode != ANDROID_CONTROL_AUTOFRAMING_AUTO) {
2831 client->setAutoframingOverride(mOverrideAutoframingMode);
2832 } else {
2833 client->setAutoframingOverride(
2834 mCameraServiceProxyWrapper->getAutoframingOverride(
2835 clientPackageName));
2836 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002837 }
2838
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002839 bool isCameraPrivacyEnabled;
2840 if (flags::camera_privacy_allowlist()) {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002841 // Set camera muting behavior.
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002842 isCameraPrivacyEnabled = this->isCameraPrivacyEnabled(
2843 toString16(client->getPackageName()), cameraId, packagePid, packageUid);
2844 } else {
2845 isCameraPrivacyEnabled =
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002846 mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002847 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02002848
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002849 if (client->supportsCameraMute()) {
2850 client->setCameraMute(
2851 mOverrideCameraMuteMode || isCameraPrivacyEnabled);
2852 } else if (isCameraPrivacyEnabled) {
2853 // no camera mute supported, but privacy is on! => disconnect
2854 ALOGI("Camera mute not supported for package: %s, camera id: %s",
2855 client->getPackageName().c_str(), cameraId.c_str());
2856 // Do not hold mServiceLock while disconnecting clients, but
2857 // retain the condition blocking other clients from connecting
2858 // in mServiceLockWrapper if held.
2859 mServiceLock.unlock();
2860 // Clear caller identity temporarily so client disconnect PID
2861 // checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002862 int64_t token = clearCallingIdentity();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002863 // Note AppOp to trigger the "Unblock" dialog
2864 client->noteAppOp();
2865 client->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08002866 restoreCallingIdentity(token);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00002867 // Reacquire mServiceLock
2868 mServiceLock.lock();
2869
2870 return STATUS_ERROR_FMT(ERROR_DISABLED,
2871 "Camera \"%s\" disabled due to camera mute", cameraId.c_str());
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08002872 }
2873
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002874 if (shimUpdateOnly) {
2875 // If only updating legacy shim parameters, immediately disconnect client
2876 mServiceLock.unlock();
2877 client->disconnect();
2878 mServiceLock.lock();
2879 } else {
2880 // Otherwise, add client to active clients list
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002881 finishConnectLocked(client, partial, oomScoreOffset, systemNativeClient);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002882 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08002883
2884 client->setImageDumpMask(mImageDumpMask);
Shuzhen Wang16610a62022-12-15 22:38:07 -08002885 client->setStreamUseCaseOverrides(mStreamUseCaseOverrides);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07002886 client->setZoomOverride(mZoomOverrideValue);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002887 } // lock is destroyed, allow further connect calls
2888
2889 // Important: release the mutex here so the client can call back into the service from its
2890 // destructor (can be at the end of the call)
2891 device = client;
Shuzhen Wang316781a2020-08-18 18:11:01 -07002892
2893 int32_t openLatencyMs = ns2ms(systemTime() - openTimeNs);
Austin Borger74fca042022-05-23 12:41:21 -07002894 mCameraServiceProxyWrapper->logOpen(cameraId, facing, clientPackageName,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002895 effectiveApiLevel, isNonSystemNdk, openLatencyMs);
Shuzhen Wang316781a2020-08-18 18:11:01 -07002896
Cliff Wud3a05312021-04-26 23:07:31 +08002897 {
2898 Mutex::Autolock lock(mInjectionParametersLock);
2899 if (cameraId == mInjectionInternalCamId && mInjectionInitPending) {
2900 mInjectionInitPending = false;
2901 status_t res = NO_ERROR;
2902 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
2903 if (clientDescriptor != nullptr) {
Cliff Wu646bd612021-11-23 23:21:29 +08002904 sp<BasicClient> clientSp = clientDescriptor->getValue();
2905 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
2906 if(res != OK) {
2907 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
2908 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07002909 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08002910 }
2911 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Cliff Wud3a05312021-04-26 23:07:31 +08002912 if (res != OK) {
2913 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2914 }
2915 } else {
2916 ALOGE("%s: Internal camera ID = %s 's client does not exist!",
Austin Borgered99f642023-06-01 16:51:35 -07002917 __FUNCTION__, mInjectionInternalCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08002918 res = NO_INIT;
2919 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
2920 }
2921 }
2922 }
2923
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002924 return ret;
2925}
2926
Austin Borgered99f642023-06-01 16:51:35 -07002927status_t CameraService::addOfflineClient(const std::string &cameraId,
2928 sp<BasicClient> offlineClient) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002929 if (offlineClient.get() == nullptr) {
2930 return BAD_VALUE;
2931 }
2932
2933 {
2934 // Acquire mServiceLock and prevent other clients from connecting
2935 std::unique_ptr<AutoConditionLock> lock =
2936 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
2937
2938 if (lock == nullptr) {
2939 ALOGE("%s: (PID %d) rejected (too many other clients connecting)."
2940 , __FUNCTION__, offlineClient->getClientPid());
2941 return TIMED_OUT;
2942 }
2943
2944 auto onlineClientDesc = mActiveClientManager.get(cameraId);
2945 if (onlineClientDesc.get() == nullptr) {
2946 ALOGE("%s: No active online client using camera id: %s", __FUNCTION__,
2947 cameraId.c_str());
2948 return BAD_VALUE;
2949 }
2950
2951 // Offline clients do not evict or conflict with other online devices. Resource sharing
2952 // conflicts are handled by the camera provider which will either succeed or fail before
2953 // reaching this method.
2954 const auto& onlinePriority = onlineClientDesc->getPriority();
2955 auto offlineClientDesc = CameraClientManager::makeClientDescriptor(
2956 kOfflineDevice + onlineClientDesc->getKey(), offlineClient, /*cost*/ 0,
Austin Borgered99f642023-06-01 16:51:35 -07002957 /*conflictingKeys*/ std::set<std::string>(), onlinePriority.getScore(),
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002958 onlineClientDesc->getOwnerId(), onlinePriority.getState(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002959 // native clients don't have offline processing support.
2960 /*ommScoreOffset*/ 0, /*systemNativeClient*/false);
Guillaume Bailey417e43d2022-11-02 15:30:24 +01002961 if (offlineClientDesc == nullptr) {
2962 ALOGE("%s: Offline client descriptor was NULL", __FUNCTION__);
2963 return BAD_VALUE;
2964 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002965
2966 // Allow only one offline device per camera
2967 auto incompatibleClients = mActiveClientManager.getIncompatibleClients(offlineClientDesc);
2968 if (!incompatibleClients.empty()) {
2969 ALOGE("%s: Incompatible offline clients present!", __FUNCTION__);
2970 return BAD_VALUE;
2971 }
2972
Austin Borgered99f642023-06-01 16:51:35 -07002973 std::string monitorTags = isClientWatched(offlineClient.get())
2974 ? mMonitorTags : std::string();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07002975 auto err = offlineClient->initialize(mCameraProviderManager, monitorTags);
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002976 if (err != OK) {
2977 ALOGE("%s: Could not initialize offline client.", __FUNCTION__);
2978 return err;
2979 }
2980
2981 auto evicted = mActiveClientManager.addAndEvict(offlineClientDesc);
2982 if (evicted.size() > 0) {
2983 for (auto& i : evicted) {
2984 ALOGE("%s: Invalid state: Offline client for camera %s was not removed ",
Austin Borgered99f642023-06-01 16:51:35 -07002985 __FUNCTION__, i->getKey().c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002986 }
2987
2988 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, offline clients not evicted "
2989 "properly", __FUNCTION__);
2990
2991 return BAD_VALUE;
2992 }
2993
2994 logConnectedOffline(offlineClientDesc->getKey(),
2995 static_cast<int>(offlineClientDesc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002996 offlineClient->getPackageName());
Emilian Peevb2bc5a42019-11-20 16:02:14 -08002997
2998 sp<IBinder> remoteCallback = offlineClient->getRemote();
2999 if (remoteCallback != nullptr) {
3000 remoteCallback->linkToDeath(this);
3001 }
3002 } // lock is destroyed, allow further connect calls
3003
3004 return OK;
3005}
3006
Austin Borgered99f642023-06-01 16:51:35 -07003007Status CameraService::turnOnTorchWithStrengthLevel(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00003008 int32_t torchStrength, const sp<IBinder>& clientBinder, int32_t deviceId,
3009 int32_t devicePolicy) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003010 Mutex::Autolock lock(mServiceLock);
3011
3012 ATRACE_CALL();
3013 if (clientBinder == nullptr) {
3014 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
3015 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3016 "Torch client binder in null.");
3017 }
3018
Austin Borger22c5c852024-03-08 13:31:36 -08003019 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003020 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3021 devicePolicy, uid);
3022 if (!cameraIdOptional.has_value()) {
3023 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3024 unresolvedCameraId.c_str(), deviceId);
3025 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3026 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3027 }
3028 std::string cameraId = cameraIdOptional.value();
3029
Austin Borgered99f642023-06-01 16:51:35 -07003030 if (shouldRejectSystemCameraConnection(cameraId)) {
Rucha Katakwar38284522021-11-10 11:25:21 -08003031 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to change the strength level"
Austin Borgered99f642023-06-01 16:51:35 -07003032 "for system only device %s: ", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003033 }
3034
3035 // verify id is valid
Austin Borgered99f642023-06-01 16:51:35 -07003036 auto state = getCameraState(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003037 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003038 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003039 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003040 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003041 }
3042
3043 StatusInternal cameraStatus = state->getStatus();
3044 if (cameraStatus != StatusInternal::NOT_AVAILABLE &&
3045 cameraStatus != StatusInternal::PRESENT) {
Austin Borgered99f642023-06-01 16:51:35 -07003046 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08003047 (int)cameraStatus);
3048 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003049 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003050 }
3051
3052 {
3053 Mutex::Autolock al(mTorchStatusMutex);
3054 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003055 status_t err = getTorchStatusLocked(cameraId, &status);
Rucha Katakwar38284522021-11-10 11:25:21 -08003056 if (err != OK) {
3057 if (err == NAME_NOT_FOUND) {
3058 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003059 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003060 }
3061 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003062 __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003063 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
3064 "Error changing torch strength level for camera \"%s\": %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003065 cameraId.c_str(), strerror(-err), err);
Rucha Katakwar38284522021-11-10 11:25:21 -08003066 }
3067
3068 if (status == TorchModeStatus::NOT_AVAILABLE) {
3069 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
3070 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003071 "camera is in use.", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003072 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3073 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003074 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003075 } else {
3076 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003077 "insufficient resources", __FUNCTION__, cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003078 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3079 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003080 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003081 }
3082 }
3083 }
3084
3085 {
3086 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003087 updateTorchUidMapLocked(cameraId, uid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003088 }
3089 // Check if the current torch strength level is same as the new one.
3090 bool shouldSkipTorchStrengthUpdates = mCameraProviderManager->shouldSkipTorchStrengthUpdate(
Austin Borgered99f642023-06-01 16:51:35 -07003091 cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003092
Austin Borgered99f642023-06-01 16:51:35 -07003093 status_t err = mFlashlight->turnOnTorchWithStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003094
3095 if (err != OK) {
3096 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003097 std::string msg;
Rucha Katakwar38284522021-11-10 11:25:21 -08003098 switch (err) {
3099 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003100 msg = fmt::sprintf("Camera \"%s\" has no flashlight.",
3101 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003102 errorCode = ERROR_ILLEGAL_ARGUMENT;
3103 break;
3104 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003105 msg = fmt::sprintf("Camera \"%s\" is in use",
3106 cameraId.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003107 errorCode = ERROR_CAMERA_IN_USE;
3108 break;
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003109 case -EINVAL:
Austin Borgered99f642023-06-01 16:51:35 -07003110 msg = fmt::sprintf("Torch strength level %d is not within the "
Rucha Katakwar922fa9c2022-02-25 17:46:49 -08003111 "valid range.", torchStrength);
3112 errorCode = ERROR_ILLEGAL_ARGUMENT;
3113 break;
Rucha Katakwar38284522021-11-10 11:25:21 -08003114 default:
Austin Borgered99f642023-06-01 16:51:35 -07003115 msg = "Changing torch strength level failed.";
Rucha Katakwar38284522021-11-10 11:25:21 -08003116 errorCode = ERROR_INVALID_OPERATION;
Rucha Katakwar38284522021-11-10 11:25:21 -08003117 }
Austin Borgered99f642023-06-01 16:51:35 -07003118 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3119 return STATUS_ERROR(errorCode, msg.c_str());
Rucha Katakwar38284522021-11-10 11:25:21 -08003120 }
3121
3122 {
3123 // update the link to client's death
3124 // Store the last client that turns on each camera's torch mode.
3125 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003126 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Rucha Katakwar38284522021-11-10 11:25:21 -08003127 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003128 mTorchClientMap.add(cameraId, clientBinder);
Rucha Katakwar38284522021-11-10 11:25:21 -08003129 } else {
3130 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
3131 mTorchClientMap.replaceValueAt(index, clientBinder);
3132 }
3133 clientBinder->linkToDeath(this);
3134 }
3135
Austin Borger22c5c852024-03-08 13:31:36 -08003136 int clientPid = getCallingPid();
Rucha Katakwar38284522021-11-10 11:25:21 -08003137 ALOGI("%s: Torch strength for camera id %s changed to %d for client PID %d",
Austin Borgered99f642023-06-01 16:51:35 -07003138 __FUNCTION__, cameraId.c_str(), torchStrength, clientPid);
Rucha Katakwar38284522021-11-10 11:25:21 -08003139 if (!shouldSkipTorchStrengthUpdates) {
Austin Borgered99f642023-06-01 16:51:35 -07003140 broadcastTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08003141 }
3142 return Status::ok();
3143}
3144
malikakash73125c62023-07-21 22:44:34 +00003145Status CameraService::setTorchMode(const std::string& unresolvedCameraId, bool enabled,
Biswarup Pal37a75182024-01-16 15:53:35 +00003146 const sp<IBinder>& clientBinder, int32_t deviceId, int32_t devicePolicy) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08003147 Mutex::Autolock lock(mServiceLock);
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003148
3149 ATRACE_CALL();
Ruben Brunk99e69712015-05-26 17:25:07 -07003150 if (enabled && clientBinder == nullptr) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003151 ALOGE("%s: torch client binder is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003152 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
3153 "Torch client Binder is null");
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003154 }
3155
Austin Borger22c5c852024-03-08 13:31:36 -08003156 int uid = getCallingUid();
Biswarup Pal37a75182024-01-16 15:53:35 +00003157 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
3158 devicePolicy, uid);
3159 if (!cameraIdOptional.has_value()) {
3160 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3161 unresolvedCameraId.c_str(), deviceId);
3162 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3163 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3164 }
3165 std::string cameraId = cameraIdOptional.value();
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003166
Austin Borgered99f642023-06-01 16:51:35 -07003167 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003168 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to set torch mode"
Austin Borgered99f642023-06-01 16:51:35 -07003169 " for system only device %s: ", cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003170 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003171 // verify id is valid.
Austin Borgered99f642023-06-01 16:51:35 -07003172 auto state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08003173 if (state == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07003174 ALOGE("%s: camera id is invalid %s", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003175 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003176 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003177 }
3178
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003179 StatusInternal cameraStatus = state->getStatus();
3180 if (cameraStatus != StatusInternal::PRESENT &&
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003181 cameraStatus != StatusInternal::NOT_AVAILABLE) {
Austin Borgered99f642023-06-01 16:51:35 -07003182 ALOGE("%s: camera id is invalid %s, status %d", __FUNCTION__, cameraId.c_str(),
3183 (int)cameraStatus);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003184 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003185 "Camera ID \"%s\" is a not valid camera ID", cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003186 }
3187
3188 {
3189 Mutex::Autolock al(mTorchStatusMutex);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003190 TorchModeStatus status;
Austin Borgered99f642023-06-01 16:51:35 -07003191 status_t err = getTorchStatusLocked(cameraId, &status);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003192 if (err != OK) {
3193 if (err == NAME_NOT_FOUND) {
3194 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07003195 "Camera \"%s\" does not have a flash unit", cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003196 }
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003197 ALOGE("%s: getting current torch status failed for camera %s",
Austin Borgered99f642023-06-01 16:51:35 -07003198 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003199 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07003200 "Error updating torch status for camera \"%s\": %s (%d)", cameraId.c_str(),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003201 strerror(-err), err);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003202 }
3203
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003204 if (status == TorchModeStatus::NOT_AVAILABLE) {
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08003205 if (cameraStatus == StatusInternal::NOT_AVAILABLE) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003206 ALOGE("%s: torch mode of camera %s is not available because "
Austin Borgered99f642023-06-01 16:51:35 -07003207 "camera is in use", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003208 return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
3209 "Torch for camera \"%s\" is not available due to an existing camera user",
Austin Borgered99f642023-06-01 16:51:35 -07003210 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003211 } else {
3212 ALOGE("%s: torch mode of camera %s is not available due to "
Austin Borgered99f642023-06-01 16:51:35 -07003213 "insufficient resources", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003214 return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
3215 "Torch for camera \"%s\" is not available due to insufficient resources",
Austin Borgered99f642023-06-01 16:51:35 -07003216 cameraId.c_str());
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003217 }
3218 }
3219 }
3220
Ruben Brunk99e69712015-05-26 17:25:07 -07003221 {
3222 // Update UID map - this is used in the torch status changed callbacks, so must be done
3223 // before setTorchMode
Chien-Yu Chenfe751be2015-09-01 14:16:44 -07003224 Mutex::Autolock al(mTorchUidMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003225 updateTorchUidMapLocked(cameraId, uid);
Ruben Brunk99e69712015-05-26 17:25:07 -07003226 }
3227
Austin Borgered99f642023-06-01 16:51:35 -07003228 status_t err = mFlashlight->setTorchMode(cameraId, enabled);
Ruben Brunk99e69712015-05-26 17:25:07 -07003229
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003230 if (err != OK) {
3231 int32_t errorCode;
Austin Borgered99f642023-06-01 16:51:35 -07003232 std::string msg;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003233 switch (err) {
3234 case -ENOSYS:
Austin Borgered99f642023-06-01 16:51:35 -07003235 msg = fmt::sprintf("Camera \"%s\" has no flashlight",
3236 cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003237 errorCode = ERROR_ILLEGAL_ARGUMENT;
3238 break;
Dijack Dongc8a6f252021-09-17 16:21:16 +08003239 case -EBUSY:
Austin Borgered99f642023-06-01 16:51:35 -07003240 msg = fmt::sprintf("Camera \"%s\" is in use",
3241 cameraId.c_str());
Dijack Dongc8a6f252021-09-17 16:21:16 +08003242 errorCode = ERROR_CAMERA_IN_USE;
3243 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003244 default:
Austin Borgered99f642023-06-01 16:51:35 -07003245 msg = fmt::sprintf(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003246 "Setting torch mode of camera \"%s\" to %d failed: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -07003247 cameraId.c_str(), enabled, strerror(-err), err);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003248 errorCode = ERROR_INVALID_OPERATION;
3249 }
Austin Borgered99f642023-06-01 16:51:35 -07003250 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3251 logServiceError(msg, errorCode);
3252 return STATUS_ERROR(errorCode, msg.c_str());
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003253 }
3254
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003255 {
3256 // update the link to client's death
3257 Mutex::Autolock al(mTorchClientMapMutex);
Austin Borgered99f642023-06-01 16:51:35 -07003258 ssize_t index = mTorchClientMap.indexOfKey(cameraId);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003259 if (enabled) {
3260 if (index == NAME_NOT_FOUND) {
Austin Borgered99f642023-06-01 16:51:35 -07003261 mTorchClientMap.add(cameraId, clientBinder);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003262 } else {
Ruben Brunk99e69712015-05-26 17:25:07 -07003263 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08003264 mTorchClientMap.replaceValueAt(index, clientBinder);
3265 }
3266 clientBinder->linkToDeath(this);
3267 } else if (index != NAME_NOT_FOUND) {
Ruben Brunk99e69712015-05-26 17:25:07 -07003268 mTorchClientMap.valueAt(index)->unlinkToDeath(this);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003269 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003270 }
3271
Austin Borger22c5c852024-03-08 13:31:36 -08003272 int clientPid = getCallingPid();
Austin Borgered99f642023-06-01 16:51:35 -07003273 std::string torchState = enabled ? "on" : "off";
3274 ALOGI("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
3275 torchState.c_str(), clientPid);
3276 logTorchEvent(cameraId, torchState, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003277 return Status::ok();
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003278}
3279
Austin Borgered99f642023-06-01 16:51:35 -07003280void CameraService::updateTorchUidMapLocked(const std::string& cameraId, int uid) {
3281 if (mTorchUidMap.find(cameraId) == mTorchUidMap.end()) {
3282 mTorchUidMap[cameraId].first = uid;
3283 mTorchUidMap[cameraId].second = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003284 } else {
3285 // Set the pending UID
Austin Borgered99f642023-06-01 16:51:35 -07003286 mTorchUidMap[cameraId].first = uid;
Rucha Katakwar38284522021-11-10 11:25:21 -08003287 }
3288}
3289
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003290Status CameraService::notifySystemEvent(int32_t eventId,
3291 const std::vector<int32_t>& args) {
Austin Borger22c5c852024-03-08 13:31:36 -08003292 const int pid = getCallingPid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003293 const int selfPid = getpid();
3294
3295 // Permission checks
3296 if (pid != selfPid) {
3297 // Ensure we're being called by system_server, or similar process with
3298 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003299 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003300 const int uid = getCallingUid();
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003301 ALOGE("Permission Denial: cannot send updates to camera service about system"
3302 " events from pid=%d, uid=%d", pid, uid);
3303 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
Jeongik Chaaa1b8152018-11-21 10:02:25 +09003304 "No permission to send updates to camera service about system events"
3305 " from pid=%d, uid=%d", pid, uid);
Jeongik Chaaa5e64c2018-11-17 05:08:04 +09003306 }
3307 }
3308
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003309 ATRACE_CALL();
3310
Ruben Brunk36597b22015-03-20 22:15:57 -07003311 switch(eventId) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003312 case ICameraService::EVENT_USER_SWITCHED: {
Michael Grooverd1d435a2018-12-18 17:39:42 -08003313 // Try to register for UID and sensor privacy policy updates, in case we're recovering
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07003314 // from a system server crash
3315 mUidPolicy->registerSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -08003316 mSensorPrivacyPolicy->registerSelf();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003317 doUserSwitch(/*newUserIds*/ args);
Ruben Brunk36597b22015-03-20 22:15:57 -07003318 break;
3319 }
Valentin Iftime29e2e152021-08-13 15:17:33 +02003320 case ICameraService::EVENT_USB_DEVICE_ATTACHED:
3321 case ICameraService::EVENT_USB_DEVICE_DETACHED: {
Pawan Wagh99f44e22023-07-05 21:26:43 +00003322 if (args.size() != 1) {
3323 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT,
3324 "USB Device Event requires 1 argument");
3325 }
3326
Valentin Iftime29e2e152021-08-13 15:17:33 +02003327 // Notify CameraProviderManager for lazy HALs
3328 mCameraProviderManager->notifyUsbDeviceEvent(eventId,
3329 std::to_string(args[0]));
3330 break;
3331 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003332 case ICameraService::EVENT_NONE:
Ruben Brunk36597b22015-03-20 22:15:57 -07003333 default: {
3334 ALOGW("%s: Received invalid system event from system_server: %d", __FUNCTION__,
3335 eventId);
3336 break;
3337 }
3338 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003339 return Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07003340}
3341
Emilian Peev53722fa2019-02-22 17:47:20 -08003342void CameraService::notifyMonitoredUids() {
3343 Mutex::Autolock lock(mStatusListenerLock);
3344
3345 for (const auto& it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003346 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
Austin Borgere8e2c422022-05-12 13:45:24 -07003347 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3348 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Emilian Peev53722fa2019-02-22 17:47:20 -08003349 }
3350}
3351
Austin Borgerdddb7552023-03-30 17:53:01 -07003352void CameraService::notifyMonitoredUids(const std::unordered_set<uid_t> &notifyUidSet) {
3353 Mutex::Autolock lock(mStatusListenerLock);
3354
3355 for (const auto& it : mListenerList) {
3356 if (notifyUidSet.find(it->getListenerUid()) != notifyUidSet.end()) {
3357 ALOGV("%s: notifying uid %d", __FUNCTION__, it->getListenerUid());
3358 auto ret = it->getListener()->onCameraAccessPrioritiesChanged();
3359 it->handleBinderStatus(ret, "%s: Failed to trigger permission callback for %d:%d: %d",
3360 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
3361 }
3362 }
3363}
3364
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003365Status CameraService::notifyDeviceStateChange(int64_t newState) {
Austin Borger22c5c852024-03-08 13:31:36 -08003366 const int pid = getCallingPid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003367 const int selfPid = getpid();
3368
3369 // Permission checks
3370 if (pid != selfPid) {
3371 // Ensure we're being called by system_server, or similar process with
3372 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003373 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003374 const int uid = getCallingUid();
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003375 ALOGE("Permission Denial: cannot send updates to camera service about device"
3376 " state changes from pid=%d, uid=%d", pid, uid);
3377 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3378 "No permission to send updates to camera service about device state"
3379 " changes from pid=%d, uid=%d", pid, uid);
3380 }
3381 }
3382
3383 ATRACE_CALL();
3384
Austin Borger18b30a72022-10-27 12:20:29 -07003385 {
3386 Mutex::Autolock lock(mServiceLock);
3387 mDeviceState = newState;
3388 }
3389
Jayant Chowdhary0bd38522021-11-05 17:49:27 -07003390 mCameraProviderManager->notifyDeviceStateChange(newState);
Eino-Ville Talvala63f36112018-12-06 14:57:03 -08003391
3392 return Status::ok();
3393}
3394
Emilian Peev8b64f282021-03-25 16:49:57 -07003395Status CameraService::notifyDisplayConfigurationChange() {
3396 ATRACE_CALL();
Austin Borger22c5c852024-03-08 13:31:36 -08003397 const int callingPid = getCallingPid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003398 const int selfPid = getpid();
3399
3400 // Permission checks
3401 if (callingPid != selfPid) {
3402 // Ensure we're being called by system_server, or similar process with
3403 // permissions to notify the camera service about system events
Austin Borgered99f642023-06-01 16:51:35 -07003404 if (!checkCallingPermission(toString16(sCameraSendSystemEventsPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003405 const int uid = getCallingUid();
Emilian Peev8b64f282021-03-25 16:49:57 -07003406 ALOGE("Permission Denial: cannot send updates to camera service about orientation"
3407 " changes from pid=%d, uid=%d", callingPid, uid);
3408 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
3409 "No permission to send updates to camera service about orientation"
3410 " changes from pid=%d, uid=%d", callingPid, uid);
3411 }
3412 }
3413
3414 Mutex::Autolock lock(mServiceLock);
3415
3416 // Don't do anything if rotate-and-crop override via cmd is active
3417 if (mOverrideRotateAndCropMode != ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return Status::ok();
3418
3419 const auto clients = mActiveClientManager.getAll();
3420 for (auto& current : clients) {
3421 if (current != nullptr) {
3422 const auto basicClient = current->getValue();
Austin Borger18b30a72022-10-27 12:20:29 -07003423 if (basicClient.get() != nullptr && !basicClient->getOverrideToPortrait()) {
3424 basicClient->setRotateAndCropOverride(
3425 mCameraServiceProxyWrapper->getRotateAndCropOverride(
3426 basicClient->getPackageName(),
3427 basicClient->getCameraFacing(),
3428 multiuser_get_user_id(basicClient->getClientUid())));
Emilian Peev8b64f282021-03-25 16:49:57 -07003429 }
3430 }
3431 }
3432
3433 return Status::ok();
3434}
3435
Biswarup Pal37a75182024-01-16 15:53:35 +00003436// TODO(b/291736219): This to be made device-aware.
Emilian Peev8b64f282021-03-25 16:49:57 -07003437Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003438 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3439 ATRACE_CALL();
3440 if (!concurrentCameraIds) {
3441 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3442 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3443 }
3444
3445 if (!mInitialized) {
3446 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003447 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003448 return STATUS_ERROR(ERROR_DISCONNECTED,
3449 "Camera subsystem is not available");
3450 }
3451 // First call into the provider and get the set of concurrent camera
3452 // combinations
3453 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003454 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003455 for (auto &combination : concurrentCameraCombinations) {
3456 std::vector<std::string> validCombination;
3457 for (auto &cameraId : combination) {
3458 // if the camera state is not present, skip
Austin Borgered99f642023-06-01 16:51:35 -07003459 auto state = getCameraState(cameraId);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003460 if (state == nullptr) {
3461 ALOGW("%s: camera id %s does not exist", __FUNCTION__, cameraId.c_str());
3462 continue;
3463 }
3464 StatusInternal status = state->getStatus();
3465 if (status == StatusInternal::NOT_PRESENT || status == StatusInternal::ENUMERATING) {
3466 continue;
3467 }
Austin Borgered99f642023-06-01 16:51:35 -07003468 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003469 continue;
3470 }
3471 validCombination.push_back(cameraId);
3472 }
3473 if (validCombination.size() != 0) {
3474 concurrentCameraIds->push_back(std::move(validCombination));
3475 }
3476 }
3477 return Status::ok();
3478}
3479
3480Status CameraService::isConcurrentSessionConfigurationSupported(
3481 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003482 int targetSdkVersion, /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003483 if (!isSupported) {
3484 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3485 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3486 }
3487
3488 if (!mInitialized) {
3489 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3490 return STATUS_ERROR(ERROR_DISCONNECTED,
3491 "Camera subsystem is not available");
3492 }
3493
3494 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003495 int callingPid = getCallingPid();
3496 int callingUid = getCallingUid();
Biswarup Pale506e732024-03-27 13:46:20 +00003497 // TODO(b/291736219): Pass deviceId owning the camera if we make this method device-aware.
Austin Borger249e6592024-03-10 22:28:11 -07003498 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pale506e732024-03-27 13:46:20 +00003499 hasPermissionsForCamera(callingPid, callingUid, kDefaultDeviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003500 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003501 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3502 "android.permission.CAMERA needed to call"
3503 "isConcurrentSessionConfigurationSupported");
3504 }
3505
3506 status_t res =
3507 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003508 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3509 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003510 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003511 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003512 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003513 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3514 "support %s (%d)", strerror(-res), res);
3515 }
3516 return Status::ok();
3517}
3518
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003519Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3520 /*out*/
3521 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003522 return addListenerHelper(listener, cameraStatuses);
3523}
3524
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003525binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3526 std::vector<hardware::CameraStatus>* cameraStatuses) {
3527 return addListenerHelper(listener, cameraStatuses, false, true);
3528}
3529
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003530Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3531 /*out*/
3532 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003533 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003534 ATRACE_CALL();
3535
Igor Murashkinbfc99152013-02-27 12:55:20 -08003536 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003537
Ruben Brunk3450ba72015-06-16 11:00:37 -07003538 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003539 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003540 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003541 }
3542
Austin Borger22c5c852024-03-08 13:31:36 -08003543 auto clientPid = getCallingPid();
3544 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003545 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003546
Igor Murashkinbfc99152013-02-27 12:55:20 -08003547 Mutex::Autolock lock(mServiceLock);
3548
Ruben Brunkcc776712015-02-17 20:18:47 -08003549 {
3550 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003551 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003552 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003553 ALOGW("%s: Tried to add listener %p which was already subscribed",
3554 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003555 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003556 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003557 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003558
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003559 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003560 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3561 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003562 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003563 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003564 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003565 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003566 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3567 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3568 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003569 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003570 // The listener still needs to be added to the list of listeners, regardless of what
3571 // permissions the listener process has / whether it is a vendor listener. Since it might be
3572 // eligible to listen to other camera ids.
3573 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003574 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003575 }
3576
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003577 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003578 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003579 Mutex::Autolock lock(mCameraStatesLock);
3580 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003581 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3582 auto [deviceId, mappedCameraId] =
3583 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3584
3585 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003586 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003587 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3588 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003589 }
3590 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003591 // Remove the camera statuses that should be hidden from the client, we do
3592 // this after collecting the states in order to avoid holding
3593 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3594 // the same time.
3595 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3596 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003597 std::string cameraId = s.cameraId;
3598 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3599 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3600 clientUid);
3601 if (!cameraIdOptional.has_value()) {
3602 std::string msg =
3603 fmt::sprintf(
3604 "Camera %s: Invalid camera id for device id %d",
3605 s.cameraId.c_str(), s.deviceId);
3606 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3607 return true;
3608 }
3609 cameraId = cameraIdOptional.value();
3610 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3611 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3612 ALOGE("%s: Invalid camera id %s, skipping status update",
3613 __FUNCTION__, s.cameraId.c_str());
3614 return true;
3615 }
3616 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3617 clientUid);
3618 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003619
Biswarup Pal37a75182024-01-16 15:53:35 +00003620 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003621 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003622 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003623 // Add only default device cameras here, as virtual cameras currently don't support torch
3624 // anyway. Note that this is a simplification of the implementation here, and we should
3625 // change this when virtual cameras support torch.
3626 if (s.deviceId == kDefaultDeviceId) {
3627 idsChosenForCallback.insert(s.cameraId);
3628 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003629 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003630
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003631 /*
3632 * Immediately signal current torch status to this listener only
3633 * This may be a subset of all the devices, so don't include it in the response directly
3634 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003635 {
3636 Mutex::Autolock al(mTorchStatusMutex);
3637 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003638 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003639 // The camera id is visible to the client. Fine to send torch
3640 // callback.
3641 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003642 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3643 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003644 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003645 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003646 }
3647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003648 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003649}
Ruben Brunkcc776712015-02-17 20:18:47 -08003650
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003651Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003652 ATRACE_CALL();
3653
Igor Murashkinbfc99152013-02-27 12:55:20 -08003654 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3655
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003656 if (listener == 0) {
3657 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003658 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003659 }
3660
Igor Murashkinbfc99152013-02-27 12:55:20 -08003661 Mutex::Autolock lock(mServiceLock);
3662
Ruben Brunkcc776712015-02-17 20:18:47 -08003663 {
3664 Mutex::Autolock lock(mStatusListenerLock);
3665 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003666 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003667 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003668 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003669 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003670 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003671 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003672 }
3673 }
3674
3675 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3676 __FUNCTION__, listener.get());
3677
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003678 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003679}
3680
Austin Borgered99f642023-06-01 16:51:35 -07003681Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003682
3683 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003684 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3685
3686 if (parameters == NULL) {
3687 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003688 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003689 }
3690
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003691 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003692
3693 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003694 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003695 // Error logged by caller
3696 return ret;
3697 }
3698
3699 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003700
Austin Borgered99f642023-06-01 16:51:35 -07003701 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003702
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003703 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003704}
3705
Austin Borgered99f642023-06-01 16:51:35 -07003706Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003707 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003708 ATRACE_CALL();
3709
malikakashedb38962023-09-06 00:03:35 +00003710 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003711 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003712
Austin Borgered99f642023-06-01 16:51:35 -07003713 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003714
3715 switch (apiVersion) {
3716 case API_VERSION_1:
3717 case API_VERSION_2:
3718 break;
3719 default:
Austin Borgered99f642023-06-01 16:51:35 -07003720 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3721 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3722 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003723 }
3724
Austin Borger18b30a72022-10-27 12:20:29 -07003725 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003726 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003727 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003728 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3729 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3730 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003731 }
3732 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3733 int deviceVersion = deviceVersionAndTransport.first;
3734 switch (deviceVersion) {
3735 case CAMERA_DEVICE_API_VERSION_1_0:
3736 case CAMERA_DEVICE_API_VERSION_3_0:
3737 case CAMERA_DEVICE_API_VERSION_3_1:
3738 if (apiVersion == API_VERSION_2) {
3739 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003740 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003741 *isSupported = false;
3742 } else { // if (apiVersion == API_VERSION_1) {
3743 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003744 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003745 *isSupported = true;
3746 }
3747 break;
3748 case CAMERA_DEVICE_API_VERSION_3_2:
3749 case CAMERA_DEVICE_API_VERSION_3_3:
3750 case CAMERA_DEVICE_API_VERSION_3_4:
3751 case CAMERA_DEVICE_API_VERSION_3_5:
3752 case CAMERA_DEVICE_API_VERSION_3_6:
3753 case CAMERA_DEVICE_API_VERSION_3_7:
3754 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003755 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003756 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003757 break;
3758 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003759 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3760 deviceVersion, cameraId.c_str());
3761 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3762 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003763 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003764 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003765 } else {
3766 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003767 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003768 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003769}
3770
Austin Borgered99f642023-06-01 16:51:35 -07003771Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003772 /*out*/ bool *isSupported) {
3773 ATRACE_CALL();
3774
malikakashedb38962023-09-06 00:03:35 +00003775 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003776 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003777
Austin Borgered99f642023-06-01 16:51:35 -07003778 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3779 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003780
3781 return Status::ok();
3782}
3783
Cliff Wud8cae102021-03-11 01:37:42 +08003784Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003785 const std::string& packageName, const std::string& internalCamId,
3786 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003787 const sp<ICameraInjectionCallback>& callback,
3788 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003789 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003790 ATRACE_CALL();
3791
Austin Borgered99f642023-06-01 16:51:35 -07003792 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003793 const int pid = getCallingPid();
3794 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003795 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3796 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003797 "Permission Denial: no permission to inject camera");
3798 }
3799
3800 // Do not allow any camera injection that injects or replaces a virtual camera.
3801 auto [deviceIdForInternalCamera, _] =
3802 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3803 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3804 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3805 "Cannot replace a virtual camera");
3806 }
3807 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3808 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3809 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3810 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3811 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003812 }
3813
3814 ALOGV(
3815 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3816 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003817 __FUNCTION__, packageName.c_str(),
3818 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003819
Cliff Wud3a05312021-04-26 23:07:31 +08003820 {
3821 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003822 mInjectionInternalCamId = internalCamId;
3823 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003824 mInjectionStatusListener->addListener(callback);
3825 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003826 status_t res = NO_ERROR;
3827 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3828 // If the client already exists, we can directly connect to the camera device through the
3829 // client's injectCamera(), otherwise we need to wait until the client is established
3830 // (execute connectHelper()) before injecting the camera to the camera device.
3831 if (clientDescriptor != nullptr) {
3832 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003833 sp<BasicClient> clientSp = clientDescriptor->getValue();
3834 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3835 if(res != OK) {
3836 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3837 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003838 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003839 }
3840 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003841 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003842 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3843 }
3844 } else {
3845 mInjectionInitPending = true;
3846 }
3847 }
Cliff Wud8cae102021-03-11 01:37:42 +08003848
Cliff Wud3a05312021-04-26 23:07:31 +08003849 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003850}
3851
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003852Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003853 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003854 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3855 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3856 return Status::ok();
3857}
3858
Ruben Brunkcc776712015-02-17 20:18:47 -08003859void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003860 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003861 for (auto& i : mActiveClientManager.getAll()) {
3862 auto clientSp = i->getValue();
3863 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003864 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003865 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003866 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003867 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003868 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003869}
3870
Ruben Brunkcc776712015-02-17 20:18:47 -08003871bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003872 bool ret = false;
3873 {
3874 // Acquire mServiceLock and prevent other clients from connecting
3875 std::unique_ptr<AutoConditionLock> lock =
3876 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003877
Ruben Brunkcc776712015-02-17 20:18:47 -08003878 std::vector<sp<BasicClient>> evicted;
3879 for (auto& i : mActiveClientManager.getAll()) {
3880 auto clientSp = i->getValue();
3881 if (clientSp.get() == nullptr) {
3882 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3883 mActiveClientManager.remove(i);
3884 continue;
3885 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003886 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003887 mActiveClientManager.remove(i);
3888 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003889
Ruben Brunkcc776712015-02-17 20:18:47 -08003890 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003891 clientSp->notifyError(
3892 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003893 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003894 }
3895 }
3896
Ruben Brunkcc776712015-02-17 20:18:47 -08003897 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3898 // other clients from connecting in mServiceLockWrapper if held
3899 mServiceLock.unlock();
3900
Ruben Brunk36597b22015-03-20 22:15:57 -07003901 // Do not clear caller identity, remote caller should be client proccess
3902
Ruben Brunkcc776712015-02-17 20:18:47 -08003903 for (auto& i : evicted) {
3904 if (i.get() != nullptr) {
3905 i->disconnect();
3906 ret = true;
3907 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003908 }
3909
Ruben Brunkcc776712015-02-17 20:18:47 -08003910 // Reacquire mServiceLock
3911 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003912
Ruben Brunkcc776712015-02-17 20:18:47 -08003913 } // lock is destroyed, allow further connect calls
3914
3915 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003916}
3917
Ruben Brunkcc776712015-02-17 20:18:47 -08003918std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003919 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003920 std::shared_ptr<CameraState> state;
3921 {
3922 Mutex::Autolock lock(mCameraStatesLock);
3923 auto iter = mCameraStates.find(cameraId);
3924 if (iter != mCameraStates.end()) {
3925 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003926 }
3927 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003928 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003929}
3930
Austin Borgered99f642023-06-01 16:51:35 -07003931sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003932 // Remove from active clients list
3933 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3934 if (clientDescriptorPtr == nullptr) {
3935 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003936 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003937 return sp<BasicClient>{nullptr};
3938 }
3939
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003940 sp<BasicClient> client = clientDescriptorPtr->getValue();
3941 if (client.get() != nullptr) {
3942 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3943 }
3944 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003945}
3946
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003947void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003948 // Acquire mServiceLock and prevent other clients from connecting
3949 std::unique_ptr<AutoConditionLock> lock =
3950 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3951
Ruben Brunk6267b532015-04-30 17:44:07 -07003952 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003953 for (size_t i = 0; i < newUserIds.size(); i++) {
3954 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003955 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003956 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003957 return;
3958 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003959 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003960 }
3961
Ruben Brunka8ca9152015-04-07 14:23:40 -07003962
Ruben Brunk6267b532015-04-30 17:44:07 -07003963 if (newAllowedUsers == mAllowedUsers) {
3964 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3965 return;
3966 }
3967
3968 logUserSwitch(mAllowedUsers, newAllowedUsers);
3969
3970 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003971
3972 // Current user has switched, evict all current clients.
3973 std::vector<sp<BasicClient>> evicted;
3974 for (auto& i : mActiveClientManager.getAll()) {
3975 auto clientSp = i->getValue();
3976
3977 if (clientSp.get() == nullptr) {
3978 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3979 continue;
3980 }
3981
Ruben Brunk6267b532015-04-30 17:44:07 -07003982 // Don't evict clients that are still allowed.
3983 uid_t clientUid = clientSp->getClientUid();
3984 userid_t clientUserId = multiuser_get_user_id(clientUid);
3985 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
3986 continue;
3987 }
3988
Ruben Brunk36597b22015-03-20 22:15:57 -07003989 evicted.push_back(clientSp);
3990
Ruben Brunk36597b22015-03-20 22:15:57 -07003991 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07003992 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07003993
Ruben Brunk36597b22015-03-20 22:15:57 -07003994 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07003995 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00003996 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07003997 " to user switch.", i->getKey().c_str(),
3998 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00003999 i->getOwnerId(), i->getPriority().getScore(),
4000 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07004001
4002 }
4003
4004 // Do not hold mServiceLock while disconnecting clients, but retain the condition
4005 // blocking other clients from connecting in mServiceLockWrapper if held.
4006 mServiceLock.unlock();
4007
4008 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08004009 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07004010
4011 for (auto& i : evicted) {
4012 i->disconnect();
4013 }
4014
Austin Borger22c5c852024-03-08 13:31:36 -08004015 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07004016
4017 // Reacquire mServiceLock
4018 mServiceLock.lock();
4019}
Ruben Brunkcc776712015-02-17 20:18:47 -08004020
Austin Borgered99f642023-06-01 16:51:35 -07004021void CameraService::logEvent(const std::string &event) {
4022 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07004023 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07004024 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07004025 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07004026 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07004027 mEventLog.add(msg);
4028 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
4029 // Error event not added to the dumpsys log before
4030 mEventLog.add(msg);
4031 sServiceErrorEventSet.insert(msg);
4032 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004033}
4034
Austin Borgered99f642023-06-01 16:51:35 -07004035void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
4036 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004037 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004038 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4039 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004040}
4041
Austin Borgered99f642023-06-01 16:51:35 -07004042void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4043 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004044 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004045 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4046 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004047}
4048
Austin Borgered99f642023-06-01 16:51:35 -07004049void CameraService::logConnected(const std::string &cameraId, int clientPid,
4050 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004051 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004052 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4053 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004054}
4055
Austin Borgered99f642023-06-01 16:51:35 -07004056void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4057 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004058 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004059 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4060 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004061}
4062
Austin Borgered99f642023-06-01 16:51:35 -07004063void CameraService::logRejected(const std::string &cameraId, int clientPid,
4064 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004065 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004066 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4067 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004068}
4069
Austin Borgered99f642023-06-01 16:51:35 -07004070void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4071 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004072 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004073 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4074 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004075}
4076
Ruben Brunk6267b532015-04-30 17:44:07 -07004077void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4078 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004079 std::string newUsers = toString(newUserIds);
4080 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004081 if (oldUsers.size() == 0) {
4082 oldUsers = "<None>";
4083 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004084 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004085 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4086 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004087}
4088
Austin Borgered99f642023-06-01 16:51:35 -07004089void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004090 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004091 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004092}
4093
Austin Borgered99f642023-06-01 16:51:35 -07004094void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004095 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004096 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004097}
4098
Austin Borgered99f642023-06-01 16:51:35 -07004099void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004100 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004101 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004102}
4103
Austin Borgered99f642023-06-01 16:51:35 -07004104void CameraService::logServiceError(const std::string &msg, int errorCode) {
4105 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4106 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004107}
4108
Ruben Brunk36597b22015-03-20 22:15:57 -07004109status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4110 uint32_t flags) {
4111
Mathias Agopian65ab4712010-07-14 17:59:35 -07004112 // Permission checks
4113 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004114 case SHELL_COMMAND_TRANSACTION: {
4115 int in = data.readFileDescriptor();
4116 int out = data.readFileDescriptor();
4117 int err = data.readFileDescriptor();
4118 int argc = data.readInt32();
4119 Vector<String16> args;
4120 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4121 args.add(data.readString16());
4122 }
4123 sp<IBinder> unusedCallback;
4124 sp<IResultReceiver> resultReceiver;
4125 status_t status;
4126 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4127 return status;
4128 }
4129 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4130 return status;
4131 }
4132 status = shellCommand(in, out, err, args);
4133 if (resultReceiver != nullptr) {
4134 resultReceiver->send(status);
4135 }
4136 return NO_ERROR;
4137 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004138 }
4139
4140 return BnCameraService::onTransact(code, data, reply, flags);
4141}
4142
Mathias Agopian65ab4712010-07-14 17:59:35 -07004143// We share the media players for shutter and recording sound for all clients.
4144// A reference count is kept to determine when we will actually release the
4145// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004146sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4147 sp<MediaPlayer> mp = new MediaPlayer();
4148 status_t error;
4149 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004150 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004151 error = mp->prepare();
4152 }
4153 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004154 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004155 mp->disconnect();
4156 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004157 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004158 }
4159 return mp;
4160}
4161
username5755fea2018-12-27 09:48:08 +08004162void CameraService::increaseSoundRef() {
4163 Mutex::Autolock lock(mSoundLock);
4164 mSoundRef++;
4165}
4166
4167void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004168 ATRACE_CALL();
4169
username5755fea2018-12-27 09:48:08 +08004170 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4171 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4172 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4173 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4174 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4175 }
4176 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4177 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4178 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4179 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004180 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004181 }
4182 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4183 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4184 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4185 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4186 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004187 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004188}
4189
username5755fea2018-12-27 09:48:08 +08004190void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004191 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004192 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004193 if (--mSoundRef) return;
4194
4195 for (int i = 0; i < NUM_SOUNDS; i++) {
4196 if (mSoundPlayer[i] != 0) {
4197 mSoundPlayer[i]->disconnect();
4198 mSoundPlayer[i].clear();
4199 }
4200 }
4201}
4202
4203void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004204 ATRACE_CALL();
4205
Mathias Agopian65ab4712010-07-14 17:59:35 -07004206 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004207 if (kind < 0 || kind >= NUM_SOUNDS) {
4208 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4209 return;
4210 }
4211
Mathias Agopian65ab4712010-07-14 17:59:35 -07004212 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004213 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004214 sp<MediaPlayer> player = mSoundPlayer[kind];
4215 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004216 player->seekTo(0);
4217 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218 }
4219}
4220
4221// ----------------------------------------------------------------------------
4222
4223CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004224 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004225 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004226 const std::string& clientPackageName, bool systemNativeClient,
4227 const std::optional<std::string>& clientFeatureId,
4228 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004229 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004230 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004231 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004232 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004233 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004234 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004235 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004236 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004237 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004238 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004239 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004240{
Austin Borger22c5c852024-03-08 13:31:36 -08004241 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004242 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004244 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004245
username5755fea2018-12-27 09:48:08 +08004246 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004247
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004248 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004249}
4250
Mathias Agopian65ab4712010-07-14 17:59:35 -07004251// tear down the client
4252CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004253 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004254 mDestructionStarted = true;
4255
username5755fea2018-12-27 09:48:08 +08004256 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004257 // unconditionally disconnect. function is idempotent
4258 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004259}
4260
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004261sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4262
Igor Murashkin634a5152013-02-20 17:15:11 -08004263CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004264 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004265 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004266 const std::string& clientPackageName, bool nativeClient,
4267 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004268 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004269 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004270 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004271 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004272 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004273 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4274 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004275 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004276 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004277 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004278 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004279 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004280 mRemoteBinder(remoteCallback),
4281 mOpsActive(false),
4282 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004283{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004284 if (sCameraService == nullptr) {
4285 sCameraService = cameraService;
4286 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004287
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004288 // There are 2 scenarios in which a client won't have AppOps operations
4289 // (both scenarios : native clients)
4290 // 1) It's an system native client*, the package name will be empty
4291 // and it will return from this function in the previous if condition
4292 // (This is the same as the previously existing behavior).
4293 // 2) It is a system native client, but its package name has been
4294 // modified for debugging, however it still must not use AppOps since
4295 // the package name is not a real one.
4296 //
4297 // * system native client - native client with UID < AID_APP_START. It
4298 // doesn't exclude clients not on the system partition.
4299 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004300 mAppOpsManager = std::make_unique<AppOpsManager>();
4301 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004302
Charles Chenf075f082024-03-04 23:32:55 +00004303 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004304}
4305
4306CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004307 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004308 mDestructionStarted = true;
4309}
4310
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004311binder::Status CameraService::BasicClient::disconnect() {
4312 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004313 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004314 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004315 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004316 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004317
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004318 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004319 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004320 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004321 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004322
4323 sp<IBinder> remote = getRemote();
4324 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004325 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004326 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004327
4328 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004329 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004330 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004331 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004332 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004333
Igor Murashkincba2c162013-03-20 15:56:31 -07004334 // client shouldn't be able to call into us anymore
4335 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004336
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004337 const auto& mActivityManager = getActivityManager();
4338 if (mActivityManager) {
4339 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004340 getCallingUid(),
4341 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004342 }
4343
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004344 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004345}
4346
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004347status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4348 // No dumping of clients directly over Binder,
4349 // must go through CameraService::dump
4350 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004351 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004352 return OK;
4353}
4354
Austin Borgered99f642023-06-01 16:51:35 -07004355status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004356 // Can't watch tags directly, must go through CameraService::startWatchingTags
4357 return OK;
4358}
4359
4360status_t CameraService::BasicClient::stopWatchingTags(int) {
4361 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4362 return OK;
4363}
4364
4365status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4366 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4367 return OK;
4368}
4369
Austin Borgered99f642023-06-01 16:51:35 -07004370std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004371 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004372}
4373
Emilian Peev8b64f282021-03-25 16:49:57 -07004374int CameraService::BasicClient::getCameraFacing() const {
4375 return mCameraFacing;
4376}
4377
4378int CameraService::BasicClient::getCameraOrientation() const {
4379 return mOrientation;
4380}
Ruben Brunkcc776712015-02-17 20:18:47 -08004381
4382int CameraService::BasicClient::getClientPid() const {
4383 return mClientPid;
4384}
4385
Ruben Brunk6267b532015-04-30 17:44:07 -07004386uid_t CameraService::BasicClient::getClientUid() const {
4387 return mClientUid;
4388}
4389
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004390bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4391 // Defaults to API2.
4392 return level == API_2;
4393}
4394
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004395status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004396 {
4397 Mutex::Autolock l(mAudioRestrictionLock);
4398 mAudioRestriction = mode;
4399 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004400 sCameraService->updateAudioRestriction();
4401 return OK;
4402}
4403
4404int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004405 return sCameraService->updateAudioRestriction();
4406}
4407
4408int32_t CameraService::BasicClient::getAudioRestriction() const {
4409 Mutex::Autolock l(mAudioRestrictionLock);
4410 return mAudioRestriction;
4411}
4412
4413bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4414 switch (mode) {
4415 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4416 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4417 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4418 return true;
4419 default:
4420 return false;
4421 }
4422}
4423
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004424status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4425 if (mode == AppOpsManager::MODE_ERRORED) {
4426 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004427 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004428 return PERMISSION_DENIED;
4429 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4430 // If the calling Uid is trusted (a native service), the AppOpsManager could
4431 // return MODE_IGNORED. Do not treat such case as error.
4432 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4433 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004434
4435 bool isCameraPrivacyEnabled;
4436 if (flags::camera_privacy_allowlist()) {
4437 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4438 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4439 } else {
4440 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004441 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004442 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004443 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4444 // We prefer to successfully open the camera and perform camera muting
4445 // or blocking in connectHelper as handleAppOpMode can be called before the
4446 // connection has been fully established and at that time camera muting
4447 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004448 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004449 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4450 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4451 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4452 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004453 // Return the same error as for device policy manager rejection
4454 return -EACCES;
4455 }
4456 }
4457 return OK;
4458}
4459
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004460status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004461 ATRACE_CALL();
4462
Igor Murashkine6800ce2013-03-04 17:25:57 -08004463 {
4464 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004465 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004466 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004467 if (mAppOpsManager != nullptr) {
4468 // Notify app ops that the camera is not available
4469 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004470
4471 if (flags::watch_foreground_changes()) {
4472 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4473 toString16(mClientPackageName),
4474 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4475 } else {
4476 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004477 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004478 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004479
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004480 // Just check for camera acccess here on open - delay startOp until
4481 // camera frames start streaming in startCameraStreamingOps
4482 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004483 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004484 status_t res = handleAppOpMode(mode);
4485 if (res != OK) {
4486 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004487 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004488 }
4489
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004490 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004491
4492 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004493 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004494
Austin Borgerdddb7552023-03-30 17:53:01 -07004495 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004496
Shuzhen Wang695044d2020-03-06 09:02:23 -08004497 // Notify listeners of camera open/close status
4498 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4499
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004500 return OK;
4501}
4502
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004503status_t CameraService::BasicClient::startCameraStreamingOps() {
4504 ATRACE_CALL();
4505
4506 if (!mOpsActive) {
4507 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4508 return INVALID_OPERATION;
4509 }
4510 if (mOpsStreaming) {
4511 ALOGV("%s: Streaming already active!", __FUNCTION__);
4512 return OK;
4513 }
4514
4515 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004516 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004517
4518 if (mAppOpsManager != nullptr) {
4519 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004520 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4521 toString16(mClientFeatureId),
4522 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004523 status_t res = handleAppOpMode(mode);
4524 if (res != OK) {
4525 return res;
4526 }
4527 }
4528
4529 mOpsStreaming = true;
4530
4531 return OK;
4532}
4533
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004534status_t CameraService::BasicClient::noteAppOp() {
4535 ATRACE_CALL();
4536
4537 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004538 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004539
4540 // noteAppOp is only used for when camera mute is not supported, in order
4541 // to trigger the sensor privacy "Unblock" dialog
4542 if (mAppOpsManager != nullptr) {
4543 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004544 toString16(mClientPackageName), toString16(mClientFeatureId),
4545 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004546 status_t res = handleAppOpMode(mode);
4547 if (res != OK) {
4548 return res;
4549 }
4550 }
4551
4552 return OK;
4553}
4554
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004555status_t CameraService::BasicClient::finishCameraStreamingOps() {
4556 ATRACE_CALL();
4557
4558 if (!mOpsActive) {
4559 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4560 return INVALID_OPERATION;
4561 }
4562 if (!mOpsStreaming) {
4563 ALOGV("%s: Streaming not active!", __FUNCTION__);
4564 return OK;
4565 }
4566
4567 if (mAppOpsManager != nullptr) {
4568 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004569 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004570 mOpsStreaming = false;
4571 }
4572
4573 return OK;
4574}
4575
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004576status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004577 ATRACE_CALL();
4578
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004579 if (mOpsStreaming) {
4580 // Make sure we've notified everyone about camera stopping
4581 finishCameraStreamingOps();
4582 }
4583
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004584 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004585 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004586 mOpsActive = false;
4587
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004588 // This function is called when a client disconnects. This should
4589 // release the camera, but actually only if it was in a proper
4590 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004591 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004592 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004593
Ruben Brunkcc776712015-02-17 20:18:47 -08004594 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004595 sCameraService->updateStatus(StatusInternal::PRESENT,
4596 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004597 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004598 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004599 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4600 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004601 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004602 mOpsCallback.clear();
4603
Austin Borgerdddb7552023-03-30 17:53:01 -07004604 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004605
Shuzhen Wang695044d2020-03-06 09:02:23 -08004606 // Notify listeners of camera open/close status
4607 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4608
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004609 return OK;
4610}
4611
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004612void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004613 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004614 if (mAppOpsManager == nullptr) {
4615 return;
4616 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004617 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004618 if (op != AppOpsManager::OP_CAMERA) {
4619 ALOGW("Unexpected app ops notification received: %d", op);
4620 return;
4621 }
4622
4623 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004624 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004625 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004626 ALOGV("checkOp returns: %d, %s ", res,
4627 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4628 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4629 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4630 "UNKNOWN");
4631
Shuzhen Wang64900852021-02-05 09:03:29 -08004632 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004633 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4634 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004635 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004636 } else if (res == AppOpsManager::MODE_IGNORED) {
4637 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004638
Austin Borgerca1e0062023-06-28 11:32:55 -07004639 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4640 // If not visible, but still active, then we want to block instead of muting the camera.
4641 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4642 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4643
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004644 bool isCameraPrivacyEnabled;
4645 if (flags::camera_privacy_allowlist()) {
4646 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4647 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4648 } else {
4649 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004650 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004651 }
4652
4653 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004654 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4655 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4656 isCameraPrivacyEnabled);
4657 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4658 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4659 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004660 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004661 if (flags::watch_foreground_changes()) {
4662 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4663 setCameraMute(true);
4664 } else {
4665 block();
4666 }
4667 } else {
4668 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4669 setCameraMute(true);
4670 } else if (!isUidActive
4671 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4672 block();
4673 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004674 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004675 }
Evan Severson09ab4002021-02-10 14:15:19 -08004676 } else if (res == AppOpsManager::MODE_ALLOWED) {
4677 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004678 }
4679}
4680
Svet Ganova453d0d2018-01-11 15:37:58 -08004681void CameraService::BasicClient::block() {
4682 ATRACE_CALL();
4683
4684 // Reset the client PID to allow server-initiated disconnect,
4685 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004686 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004687 CaptureResultExtras resultExtras; // a dummy result (invalid)
4688 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4689 disconnect();
4690}
4691
Mathias Agopian65ab4712010-07-14 17:59:35 -07004692// ----------------------------------------------------------------------------
4693
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004694void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004695 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004696 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004697 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4698 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4699 api1ErrorCode = CAMERA_ERROR_DISABLED;
4700 }
4701 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004702 } else {
4703 ALOGE("mRemoteCallback is NULL!!");
4704 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004705}
4706
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004707// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004708binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004709 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004710 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004711}
4712
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004713bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4714 return level == API_1;
4715}
4716
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004717CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4718 mClient(client) {
4719}
4720
4721void CameraService::Client::OpsCallback::opChanged(int32_t op,
4722 const String16& packageName) {
4723 sp<BasicClient> client = mClient.promote();
4724 if (client != NULL) {
4725 client->opChanged(op, packageName);
4726 }
4727}
4728
Mathias Agopian65ab4712010-07-14 17:59:35 -07004729// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004730// UidPolicy
4731// ----------------------------------------------------------------------------
4732
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004733void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004734 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004735 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004736
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004737 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004738 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004739 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004740 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004741 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4742 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004743 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004744 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004745 if (res == OK) {
4746 mRegistered = true;
4747 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004748 } else {
4749 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004750 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004751}
4752
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004753void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004754 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004755 return;
4756 }
4757
4758 registerWithActivityManager();
4759}
4760
4761void CameraService::UidPolicy::registerSelf() {
4762 // Use check service to see if the activity service is available
4763 // If not available then register for notifications, instead of blocking
4764 // till the service is ready
4765 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004766 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004767 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004768 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004769 } else {
4770 registerWithActivityManager();
4771 }
4772}
4773
Svet Ganova453d0d2018-01-11 15:37:58 -08004774void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004775 Mutex::Autolock _l(mUidLock);
4776
Steven Moreland2f348142019-07-02 15:59:07 -07004777 mAm.unregisterUidObserver(this);
4778 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004779 mRegistered = false;
4780 mActiveUids.clear();
4781 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004782}
4783
4784void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4785 onUidIdle(uid, disabled);
4786}
4787
4788void CameraService::UidPolicy::onUidActive(uid_t uid) {
4789 Mutex::Autolock _l(mUidLock);
4790 mActiveUids.insert(uid);
4791}
4792
4793void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4794 bool deleted = false;
4795 {
4796 Mutex::Autolock _l(mUidLock);
4797 if (mActiveUids.erase(uid) > 0) {
4798 deleted = true;
4799 }
4800 }
4801 if (deleted) {
4802 sp<CameraService> service = mService.promote();
4803 if (service != nullptr) {
4804 service->blockClientsForUid(uid);
4805 }
4806 }
4807}
4808
Emilian Peev53722fa2019-02-22 17:47:20 -08004809void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004810 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004811 bool procStateChange = false;
4812 {
4813 Mutex::Autolock _l(mUidLock);
4814 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4815 mMonitoredUids[uid].procState != procState) {
4816 mMonitoredUids[uid].procState = procState;
4817 procStateChange = true;
4818 }
4819 }
4820
4821 if (procStateChange) {
4822 sp<CameraService> service = mService.promote();
4823 if (service != nullptr) {
4824 service->notifyMonitoredUids();
4825 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004826 }
4827}
4828
Austin Borgerdddb7552023-03-30 17:53:01 -07004829/**
4830 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4831 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4832 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4833 * monitoredUids. If it is revised above some other monitoredUid, signal
4834 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4835 * foreground apps in split screen - state changes will capture all other cases.
4836 */
4837void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4838 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004839 {
4840 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004841 auto it = mMonitoredUids.find(uid);
4842
4843 if (it != mMonitoredUids.end()) {
4844 if (it->second.hasCamera) {
4845 for (auto &monitoredUid : mMonitoredUids) {
4846 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004847 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004848 notifyUidSet.emplace(monitoredUid.first);
4849 }
4850 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004851 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004852 notifyUidSet.emplace(uid);
4853 } else {
4854 for (auto &monitoredUid : mMonitoredUids) {
4855 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004856 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004857 notifyUidSet.emplace(uid);
4858 }
4859 }
4860 }
4861 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004862 }
4863 }
4864
Austin Borgerdddb7552023-03-30 17:53:01 -07004865 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004866 sp<CameraService> service = mService.promote();
4867 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004868 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004869 }
4870 }
4871}
4872
Austin Borgerdddb7552023-03-30 17:53:01 -07004873/**
4874 * Register a uid for monitoring, and note whether it owns a camera.
4875 */
4876void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004877 Mutex::Autolock _l(mUidLock);
4878 auto it = mMonitoredUids.find(uid);
4879 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004880 it->second.refCount++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004881 } else {
Austin Borger65577682022-02-17 00:25:43 +00004882 MonitoredUid monitoredUid;
4883 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004884 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004885 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004886 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004887 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004888 if (res != OK) {
4889 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4890 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004891 }
4892
4893 if (openCamera) {
4894 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004895 }
4896}
4897
Austin Borgerdddb7552023-03-30 17:53:01 -07004898/**
4899 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4900 */
4901void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004902 Mutex::Autolock _l(mUidLock);
4903 auto it = mMonitoredUids.find(uid);
4904 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004905 it->second.refCount--;
4906 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004907 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004908 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004909 if (res != OK) {
4910 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4911 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004912 } else if (closeCamera) {
4913 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004914 }
4915 } else {
4916 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4917 }
4918}
4919
Austin Borgered99f642023-06-01 16:51:35 -07004920bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004921 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004922 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004923}
4924
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004925static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4926static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004927
Austin Borgered99f642023-06-01 16:51:35 -07004928bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004929 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004930 // If activity manager is unreachable, assume everything is active
4931 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004932 return true;
4933 }
4934 auto it = mOverrideUids.find(uid);
4935 if (it != mOverrideUids.end()) {
4936 return it->second;
4937 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004938 bool active = mActiveUids.find(uid) != mActiveUids.end();
4939 if (!active) {
4940 // We want active UIDs to always access camera with their first attempt since
4941 // there is no guarantee the app is robustly written and would retry getting
4942 // the camera on failure. The inverse case is not a problem as we would take
4943 // camera away soon once we get the callback that the uid is no longer active.
4944 ActivityManager am;
4945 // Okay to access with a lock held as UID changes are dispatched without
4946 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004947 int64_t startTimeMillis = 0;
4948 do {
4949 // TODO: Fix this b/109950150!
4950 // Okay this is a hack. There is a race between the UID turning active and
4951 // activity being resumed. The proper fix is very risky, so we temporary add
4952 // some polling which should happen pretty rarely anyway as the race is hard
4953 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004954 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004955 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004956 if (active) {
4957 break;
4958 }
4959 if (startTimeMillis <= 0) {
4960 startTimeMillis = uptimeMillis();
4961 }
4962 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004963 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004964 if (remainingTimeMillis <= 0) {
4965 break;
4966 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004967 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4968
4969 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004970 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004971 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004972 } while (true);
4973
Svet Ganov7b4ab782018-03-25 12:48:10 -07004974 if (active) {
4975 // Now that we found out the UID is actually active, cache that
4976 mActiveUids.insert(uid);
4977 }
4978 }
4979 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08004980}
4981
Varun Shahb42f1eb2019-04-16 14:45:13 -07004982int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
4983 Mutex::Autolock _l(mUidLock);
4984 return getProcStateLocked(uid);
4985}
4986
4987int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
4988 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
4989 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004990 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07004991 }
4992 return procState;
4993}
4994
Austin Borgered99f642023-06-01 16:51:35 -07004995void CameraService::UidPolicy::addOverrideUid(uid_t uid,
4996 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07004997 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08004998}
4999
Austin Borgered99f642023-06-01 16:51:35 -07005000void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005001 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005002}
5003
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005004void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5005 Mutex::Autolock _l(mUidLock);
5006 ALOGV("UidPolicy: ActivityManager has died");
5007 mRegistered = false;
5008 mActiveUids.clear();
5009}
5010
Austin Borgered99f642023-06-01 16:51:35 -07005011void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005012 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005013 bool wasActive = false;
5014 bool isActive = false;
5015 {
5016 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005017 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005018 mOverrideUids.erase(uid);
5019 if (insert) {
5020 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5021 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005022 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005023 }
5024 if (wasActive != isActive && !isActive) {
5025 sp<CameraService> service = mService.promote();
5026 if (service != nullptr) {
5027 service->blockClientsForUid(uid);
5028 }
5029 }
5030}
5031
5032// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005033// SensorPrivacyPolicy
5034// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005035
5036void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5037{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005038 Mutex::Autolock _l(mSensorPrivacyLock);
5039 if (mRegistered) {
5040 return;
5041 }
Evan Severson09ab4002021-02-10 14:15:19 -08005042 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005043 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005044 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005045 mSpm.addToggleSensorPrivacyListener(this);
5046 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005047 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005048 if (flags::camera_privacy_allowlist()) {
5049 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5050 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5051 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5052 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005053 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005054 if (res == OK) {
5055 mRegistered = true;
5056 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5057 }
5058}
5059
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005060void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5061 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005062 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005063 return;
5064 }
5065
5066 registerWithSensorPrivacyManager();
5067}
5068
5069void CameraService::SensorPrivacyPolicy::registerSelf() {
5070 // Use checkservice to see if the sensor_privacy service is available
5071 // If service is not available then register for notification
5072 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005073 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005074 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005075 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005076 } else {
5077 registerWithSensorPrivacyManager();
5078 }
5079}
5080
Michael Grooverd1d435a2018-12-18 17:39:42 -08005081void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5082 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005083 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005084 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005085 mSpm.removeToggleSensorPrivacyListener(this);
5086 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005087 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005088 mRegistered = false;
5089 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5090}
5091
5092bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005093 if (!mRegistered) {
5094 registerWithSensorPrivacyManager();
5095 }
5096
Michael Grooverd1d435a2018-12-18 17:39:42 -08005097 Mutex::Autolock _l(mSensorPrivacyLock);
5098 return mSensorPrivacyEnabled;
5099}
5100
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005101int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5102 if (!mRegistered) {
5103 registerWithSensorPrivacyManager();
5104 }
5105
5106 Mutex::Autolock _l(mSensorPrivacyLock);
5107 return mCameraPrivacyState;
5108}
5109
Evan Seversond0b69922022-01-27 10:47:34 -08005110bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005111 if (!hasCameraPrivacyFeature()) {
5112 return false;
5113 }
Evan Seversond0b69922022-01-27 10:47:34 -08005114 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005115}
5116
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005117bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5118 if (!hasCameraPrivacyFeature()) {
5119 return SensorPrivacyManager::DISABLED;
5120 }
5121 return mSpm.isCameraPrivacyEnabled(packageName);
5122}
5123
Evan Seversond0b69922022-01-27 10:47:34 -08005124binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005125 int toggleType, int sensor, bool enabled) {
5126 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5127 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5128 {
5129 Mutex::Autolock _l(mSensorPrivacyLock);
5130 mSensorPrivacyEnabled = enabled;
5131 }
5132 // if sensor privacy is enabled then block all clients from accessing the camera
5133 if (enabled) {
5134 sp<CameraService> service = mService.promote();
5135 if (service != nullptr) {
5136 service->blockAllClients();
5137 }
5138 }
5139 }
5140 return binder::Status::ok();
5141}
5142
5143binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5144 int, int sensor, int state) {
5145 if (!flags::camera_privacy_allowlist()
5146 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5147 return binder::Status::ok();
5148 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005149 {
5150 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005151 mCameraPrivacyState = state;
5152 }
5153 sp<CameraService> service = mService.promote();
5154 if (!service) {
5155 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005156 }
5157 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005158 if (state == SensorPrivacyManager::ENABLED) {
5159 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005160 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005161 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005162 }
5163 return binder::Status::ok();
5164}
5165
5166void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5167 Mutex::Autolock _l(mSensorPrivacyLock);
5168 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5169 mRegistered = false;
5170}
5171
Evan Severson09ab4002021-02-10 14:15:19 -08005172bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005173 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5174 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5175 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5176 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5177 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005178}
5179
Michael Grooverd1d435a2018-12-18 17:39:42 -08005180// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005181// CameraState
5182// ----------------------------------------------------------------------------
5183
Austin Borgered99f642023-06-01 16:51:35 -07005184CameraService::CameraState::CameraState(const std::string& id, int cost,
5185 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005186 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005187 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005188 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005189
5190CameraService::CameraState::~CameraState() {}
5191
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005192CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005193 Mutex::Autolock lock(mStatusLock);
5194 return mStatus;
5195}
5196
Austin Borgered99f642023-06-01 16:51:35 -07005197std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005198 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005199 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005200 return res;
5201}
5202
Ruben Brunkcc776712015-02-17 20:18:47 -08005203CameraParameters CameraService::CameraState::getShimParams() const {
5204 return mShimParams;
5205}
5206
5207void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5208 mShimParams = params;
5209}
5210
5211int CameraService::CameraState::getCost() const {
5212 return mCost;
5213}
5214
Austin Borgered99f642023-06-01 16:51:35 -07005215std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005216 return mConflicting;
5217}
5218
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005219SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5220 return mSystemCameraKind;
5221}
5222
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005223bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5224 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5225 != mPhysicalCameras.end();
5226}
5227
Austin Borgered99f642023-06-01 16:51:35 -07005228bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005229 Mutex::Autolock lock(mStatusLock);
5230 auto result = mUnavailablePhysicalIds.insert(physicalId);
5231 return result.second;
5232}
5233
Austin Borgered99f642023-06-01 16:51:35 -07005234bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005235 Mutex::Autolock lock(mStatusLock);
5236 auto count = mUnavailablePhysicalIds.erase(physicalId);
5237 return count > 0;
5238}
5239
Austin Borgered99f642023-06-01 16:51:35 -07005240void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005241 Mutex::Autolock lock(mStatusLock);
5242 mClientPackage = clientPackage;
5243}
5244
Austin Borgered99f642023-06-01 16:51:35 -07005245std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005246 Mutex::Autolock lock(mStatusLock);
5247 return mClientPackage;
5248}
5249
Ruben Brunkcc776712015-02-17 20:18:47 -08005250// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005251// ClientEventListener
5252// ----------------------------------------------------------------------------
5253
5254void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005255 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005256 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005257 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005258 if (basicClient.get() != nullptr) {
5259 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005260 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005261 static_cast<int>(basicClient->getClientUid()));
5262 }
5263}
5264
5265void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005266 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005267 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005268 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005269 if (basicClient.get() != nullptr) {
5270 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005271 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005272 static_cast<int>(basicClient->getClientUid()));
5273 }
5274}
5275
Ruben Brunk99e69712015-05-26 17:25:07 -07005276// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005277// CameraClientManager
5278// ----------------------------------------------------------------------------
5279
Ruben Brunk99e69712015-05-26 17:25:07 -07005280CameraService::CameraClientManager::CameraClientManager() {
5281 setListener(std::make_shared<ClientEventListener>());
5282}
5283
Ruben Brunkcc776712015-02-17 20:18:47 -08005284CameraService::CameraClientManager::~CameraClientManager() {}
5285
5286sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005287 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005288 auto descriptor = get(id);
5289 if (descriptor == nullptr) {
5290 return sp<BasicClient>{nullptr};
5291 }
5292 return descriptor->getValue();
5293}
5294
Austin Borgered99f642023-06-01 16:51:35 -07005295std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005296 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005297 std::ostringstream ret;
5298 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005299 bool hasAny = false;
5300 for (auto& i : all) {
5301 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005302 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005303 int32_t cost = i->getCost();
5304 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005305 int32_t score = i->getPriority().getScore();
5306 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005307 auto conflicting = i->getConflicting();
5308 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005309 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005310 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005311 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005312 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005313 uid_t clientUid = clientSp->getClientUid();
5314 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005315 }
Austin Borgered99f642023-06-01 16:51:35 -07005316 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5317 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005318
Ruben Brunk6267b532015-04-30 17:44:07 -07005319 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005320 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005321 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005322 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005323 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005324 }
5325
Austin Borgered99f642023-06-01 16:51:35 -07005326 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005327 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005328 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005329 }
Austin Borgered99f642023-06-01 16:51:35 -07005330 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005331 }
Austin Borgered99f642023-06-01 16:51:35 -07005332 if (hasAny) ret << "\n";
5333 ret << "]\n";
5334 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005335}
5336
5337CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005338 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5339 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005340 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005341
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005342 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005343 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005344
Austin Borgered99f642023-06-01 16:51:35 -07005345 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005346 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5347 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005348}
5349
5350CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005351 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005352 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005353 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005354 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005355 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5356 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005357}
5358
5359// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005360// InjectionStatusListener
5361// ----------------------------------------------------------------------------
5362
5363void CameraService::InjectionStatusListener::addListener(
5364 const sp<ICameraInjectionCallback>& callback) {
5365 Mutex::Autolock lock(mListenerLock);
5366 if (mCameraInjectionCallback) return;
5367 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5368 if (res == OK) {
5369 mCameraInjectionCallback = callback;
5370 }
5371}
5372
5373void CameraService::InjectionStatusListener::removeListener() {
5374 Mutex::Autolock lock(mListenerLock);
5375 if (mCameraInjectionCallback == nullptr) {
5376 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5377 return;
5378 }
5379 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5380 mCameraInjectionCallback = nullptr;
5381}
5382
5383void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005384 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005385 if (mCameraInjectionCallback == nullptr) {
5386 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5387 return;
5388 }
Cliff Wud3a05312021-04-26 23:07:31 +08005389
5390 switch (err) {
5391 case -ENODEV:
5392 mCameraInjectionCallback->onInjectionError(
5393 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5394 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005395 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005396 break;
5397 case -EBUSY:
5398 mCameraInjectionCallback->onInjectionError(
5399 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5400 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005401 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005402 break;
5403 case DEAD_OBJECT:
5404 mCameraInjectionCallback->onInjectionError(
5405 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5406 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005407 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005408 break;
5409 case INVALID_OPERATION:
5410 mCameraInjectionCallback->onInjectionError(
5411 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5412 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005413 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005414 break;
5415 case UNKNOWN_TRANSACTION:
5416 mCameraInjectionCallback->onInjectionError(
5417 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5418 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005419 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005420 break;
5421 default:
5422 mCameraInjectionCallback->onInjectionError(
5423 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5424 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005425 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005426 }
Cliff Wud8cae102021-03-11 01:37:42 +08005427}
5428
5429void CameraService::InjectionStatusListener::binderDied(
5430 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005431 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5432 auto parent = mParent.promote();
5433 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005434 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5435 if (clientDescriptor != nullptr) {
5436 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5437 baseClientPtr->stopInjection();
5438 }
Cliff Wu3b268182021-07-06 15:44:43 +08005439 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005440 }
5441}
5442
5443// ----------------------------------------------------------------------------
5444// CameraInjectionSession
5445// ----------------------------------------------------------------------------
5446
5447binder::Status CameraService::CameraInjectionSession::stopInjection() {
5448 Mutex::Autolock lock(mInjectionSessionLock);
5449 auto parent = mParent.promote();
5450 if (parent == nullptr) {
5451 ALOGE("CameraInjectionSession: Parent is gone");
5452 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5453 "Camera service encountered error");
5454 }
Cliff Wud3a05312021-04-26 23:07:31 +08005455
5456 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005457 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5458 if (clientDescriptor != nullptr) {
5459 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5460 res = baseClientPtr->stopInjection();
5461 if (res != OK) {
5462 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5463 " ret != NO_ERROR: %d", res);
5464 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5465 "Camera session encountered error");
5466 }
5467 }
Cliff Wu3b268182021-07-06 15:44:43 +08005468 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005469 return binder::Status::ok();
5470}
5471
5472// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005473
5474static const int kDumpLockRetries = 50;
5475static const int kDumpLockSleep = 60000;
5476
5477static bool tryLock(Mutex& mutex)
5478{
5479 bool locked = false;
5480 for (int i = 0; i < kDumpLockRetries; ++i) {
5481 if (mutex.tryLock() == NO_ERROR) {
5482 locked = true;
5483 break;
5484 }
5485 usleep(kDumpLockSleep);
5486 }
5487 return locked;
5488}
5489
Rucha Katakwardf223072021-06-15 10:21:00 -07005490void CameraService::cacheDump() {
5491 if (mMemFd != -1) {
5492 const Vector<String16> args;
5493 ATRACE_CALL();
5494 // Acquiring service lock here will avoid the deadlock since
5495 // cacheDump will not be called during the second disconnect.
5496 Mutex::Autolock lock(mServiceLock);
5497
5498 Mutex::Autolock l(mCameraStatesLock);
5499 // Start collecting the info for open sessions and store it in temp file.
5500 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005501 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005502 auto clientDescriptor = mActiveClientManager.get(cameraId);
5503 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005504 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005505 // Log the current open session info before device is disconnected.
5506 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5507 }
5508 }
5509 }
5510}
5511
Mathias Agopian65ab4712010-07-14 17:59:35 -07005512status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005513 ATRACE_CALL();
5514
Austin Borgered99f642023-06-01 16:51:35 -07005515 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005516 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005517 getCallingPid(),
5518 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005519 return NO_ERROR;
5520 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005521 bool locked = tryLock(mServiceLock);
5522 // failed to lock - CameraService is probably deadlocked
5523 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005524 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005525 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005526
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005527 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005528 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005529
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005530 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005531 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005532
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005533 if (locked) mServiceLock.unlock();
5534 return NO_ERROR;
5535 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005536 dprintf(fd, "\n== Service global info: ==\n\n");
5537 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005538 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005539 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5540 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005541 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5542 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5543 }
Austin Borgered99f642023-06-01 16:51:35 -07005544 std::string activeClientString = mActiveClientManager.toString();
5545 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5546 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005547 if (mStreamUseCaseOverrides.size() > 0) {
5548 dprintf(fd, "Active stream use case overrides:");
5549 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5550 dprintf(fd, " %" PRId64, useCaseOverride);
5551 }
5552 dprintf(fd, "\n");
5553 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005554
5555 dumpEventLog(fd);
5556
5557 bool stateLocked = tryLock(mCameraStatesLock);
5558 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005559 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005560 }
5561
Emilian Peevbd8c5032018-02-14 23:05:40 +00005562 int argSize = args.size();
5563 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005564 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005565 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005566 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005567 }
5568 break;
5569 }
5570 }
5571
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005572 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005573 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005574
Austin Borgered99f642023-06-01 16:51:35 -07005575 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005576
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005577 CameraParameters p = state.second->getShimParams();
5578 if (!p.isEmpty()) {
5579 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5580 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005581 }
5582
5583 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005584 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005585 // log the current open session info
5586 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005587 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005588 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005589 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005590
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005591 }
5592
5593 if (stateLocked) mCameraStatesLock.unlock();
5594
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005595 if (locked) mServiceLock.unlock();
5596
Emilian Peevf53f66e2017-04-11 14:29:43 +01005597 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005598
5599 dprintf(fd, "\n== Vendor tags: ==\n\n");
5600
5601 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5602 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005603 sp<VendorTagDescriptorCache> cache =
5604 VendorTagDescriptorCache::getGlobalVendorTagCache();
5605 if (cache == NULL) {
5606 dprintf(fd, "No vendor tags.\n");
5607 } else {
5608 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5609 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005610 } else {
5611 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5612 }
5613
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005614 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005615 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005616 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005617
5618 // Process dump arguments, if any
5619 int n = args.size();
5620 String16 verboseOption("-v");
5621 String16 unreachableOption("--unreachable");
5622 for (int i = 0; i < n; i++) {
5623 if (args[i] == verboseOption) {
5624 // change logging level
5625 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005626 std::string levelStr = toStdString(args[i+1]);
5627 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005628 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005629 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005630 } else if (args[i] == unreachableOption) {
5631 // Dump memory analysis
5632 // TODO - should limit be an argument parameter?
5633 UnreachableMemoryInfo info;
5634 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5635 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005636 dprintf(fd, "\n== Unable to dump unreachable memory. "
5637 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005638 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005639 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005640 std::string s = info.ToString(/*log_contents*/ true);
5641 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005642 }
5643 }
5644 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005645
5646 bool serviceLocked = tryLock(mServiceLock);
5647
5648 // Dump info from previous open sessions.
5649 // Reposition the offset to beginning of the file before reading
5650
5651 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5652 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5653 ssize_t size_read;
5654 char buf[4096];
5655 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5656 // Read data from file to a small buffer and write it to fd.
5657 write(fd, buf, size_read);
5658 if (size_read == -1) {
5659 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5660 break;
5661 }
5662 }
5663 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5664 } else {
5665 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5666 }
5667
5668 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005669 return NO_ERROR;
5670}
5671
Rucha Katakwardf223072021-06-15 10:21:00 -07005672void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005673 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005674 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005675 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005676 getFormattedCurrentTime().c_str(),
5677 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005678 dprintf(fd, " Client priority score: %d state: %d\n",
5679 clientDescriptor->getPriority().getScore(),
5680 clientDescriptor->getPriority().getState());
5681 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5682
5683 auto client = clientDescriptor->getValue();
5684 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005685 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005686
5687 client->dumpClient(fd, args);
5688}
5689
Austin Borgered99f642023-06-01 16:51:35 -07005690void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005691 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005692 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005693}
5694
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005695void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005696 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005697
5698 Mutex::Autolock l(mLogLock);
5699 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005700 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005701 }
5702
5703 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005704 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005705 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005706 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005707 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005708 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005709}
5710
Austin Borgered99f642023-06-01 16:51:35 -07005711void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005712 Mutex::Autolock lock(mLogLock);
5713 if (!isClientWatchedLocked(client)) { return; }
5714
5715 std::vector<std::string> dumpVector;
5716 client->dumpWatchedEventsToVector(dumpVector);
5717
5718 if (dumpVector.empty()) { return; }
5719
Austin Borgered99f642023-06-01 16:51:35 -07005720 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005721
Austin Borgered99f642023-06-01 16:51:35 -07005722 std::string currentTime = getFormattedCurrentTime();
5723 dumpString << "Cached @ ";
5724 dumpString << currentTime;
5725 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005726
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005727 size_t i = dumpVector.size();
5728
5729 // Store the string in reverse order (latest last)
5730 while (i > 0) {
5731 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005732 dumpString << cameraId;
5733 dumpString << ":";
5734 dumpString << client->getPackageName();
5735 dumpString << " ";
5736 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005737 }
5738
Austin Borgered99f642023-06-01 16:51:35 -07005739 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005740}
5741
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005742void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005743 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005744 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5745 if (mTorchClientMap[i] == who) {
5746 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005747 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005748 status_t res = mFlashlight->setTorchMode(cameraId, false);
5749 if (res) {
5750 ALOGE("%s: torch client died but couldn't turn off torch: "
5751 "%s (%d)", __FUNCTION__, strerror(-res), res);
5752 return;
5753 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005754 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005755 break;
5756 }
5757 }
5758}
5759
Ruben Brunkcc776712015-02-17 20:18:47 -08005760/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005761
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005762 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005763 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5764 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005765 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005766 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005767 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005768
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005769 // check torch client
5770 handleTorchClientBinderDied(who);
5771
5772 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005773 if(!evictClientIdByRemote(who)) {
5774 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005775 return;
5776 }
5777
Ruben Brunkcc776712015-02-17 20:18:47 -08005778 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5779 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005780}
5781
Austin Borgered99f642023-06-01 16:51:35 -07005782void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005783 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005784}
5785
Austin Borgered99f642023-06-01 16:51:35 -07005786void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005787 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005788 // Do not lock mServiceLock here or can get into a deadlock from
5789 // connect() -> disconnect -> updateStatus
5790
5791 auto state = getCameraState(cameraId);
5792
5793 if (state == nullptr) {
5794 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005795 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005796 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005797 }
5798
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005799 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5800 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5801 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005802 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005803 return;
5804 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005805
Biswarup Pal37a75182024-01-16 15:53:35 +00005806 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5807 CameraMetadata cameraInfo;
5808 status_t res = mCameraProviderManager->getCameraCharacteristics(
5809 cameraId, false, &cameraInfo, false);
5810 if (res != OK) {
5811 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5812 __FUNCTION__, cameraId.c_str());
5813 } else {
5814 int32_t deviceId = getDeviceId(cameraInfo);
5815 if (deviceId != kDefaultDeviceId) {
5816 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5817 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5818 static_cast<camera_metadata_enum_android_lens_facing_t>(
5819 lensFacingEntry.data.u8[0]);
5820 std::string mappedCameraId;
5821 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5822 mappedCameraId = kVirtualDeviceBackCameraId;
5823 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5824 mappedCameraId = kVirtualDeviceFrontCameraId;
5825 } else {
5826 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5827 __func__);
5828 }
5829 if (!mappedCameraId.empty()) {
5830 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5831 }
5832 }
5833 }
5834 }
5835
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005836 // Collect the logical cameras without holding mStatusLock in updateStatus
5837 // as that can lead to a deadlock(b/162192331).
5838 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005839 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005840 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005841 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005842 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005843 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005844 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5845 auto [deviceId, mappedCameraId] =
5846 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005847
Biswarup Pal37a75182024-01-16 15:53:35 +00005848 if (status != StatusInternal::ENUMERATING) {
5849 // Update torch status if it has a flash unit.
5850 Mutex::Autolock al(mTorchStatusMutex);
5851 TorchModeStatus torchStatus;
5852 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5853 NAME_NOT_FOUND) {
5854 TorchModeStatus newTorchStatus =
5855 status == StatusInternal::PRESENT ?
5856 TorchModeStatus::AVAILABLE_OFF :
5857 TorchModeStatus::NOT_AVAILABLE;
5858 if (torchStatus != newTorchStatus) {
5859 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5860 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005861 }
5862 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005863
Biswarup Pal37a75182024-01-16 15:53:35 +00005864 Mutex::Autolock lock(mStatusListenerLock);
5865 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5866 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005867
Biswarup Pal37a75182024-01-16 15:53:35 +00005868 for (auto& listener : mListenerList) {
5869 bool isVendorListener = listener->isVendorListener();
5870 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5871 listener->getListenerPid(), listener->getListenerUid())) {
5872 ALOGV("Skipping discovery callback for system-only camera device %s",
5873 cameraId.c_str());
5874 continue;
5875 }
5876
5877 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5878 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005879 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005880 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005881 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5882 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005883
5884 // Only cameras of the default device can be remapped to a different camera
5885 // (using remapCameraIds method), so do the following only if the camera is
5886 // associated with the default device.
5887 if (deviceId == kDefaultDeviceId) {
5888 // For the default device, also trigger the callbacks for cameras that were
5889 // remapped to the current cameraId for the specific package that this
5890 // listener belongs to.
5891 std::vector<std::string> remappedCameraIds =
5892 findOriginalIdsForRemappedCameraId(cameraId,
5893 listener->getListenerUid());
5894 for (auto &remappedCameraId: remappedCameraIds) {
5895 ret = listener->getListener()->onStatusChanged(
5896 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5897 listener->handleBinderStatus(ret,
5898 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5899 __FUNCTION__, listener->getListenerUid(),
5900 listener->getListenerPid(), ret.exceptionCode());
5901 }
5902 }
malikakash82ed4352023-07-21 22:44:34 +00005903 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005904 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005905}
5906
Austin Borgered99f642023-06-01 16:51:35 -07005907void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5908 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005909 auto state = getCameraState(cameraId);
5910 if (state == nullptr) {
5911 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005912 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005913 return;
5914 }
5915 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005916 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005917 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005918 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005919 }
5920
Biswarup Pal37a75182024-01-16 15:53:35 +00005921 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5922 auto [deviceId, mappedCameraId] =
5923 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5924
Shuzhen Wang695044d2020-03-06 09:02:23 -08005925 Mutex::Autolock lock(mStatusListenerLock);
5926
5927 for (const auto& it : mListenerList) {
5928 if (!it->isOpenCloseCallbackAllowed()) {
5929 continue;
5930 }
5931
5932 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005933 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005934 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5935 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005936 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005937 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005938 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005939
5940 it->handleBinderStatus(ret,
5941 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5942 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005943 }
5944}
5945
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005946template<class Func>
5947void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005948 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005949 std::initializer_list<StatusInternal> rejectSourceStates,
5950 Func onStatusUpdatedLocked) {
5951 Mutex::Autolock lock(mStatusLock);
5952 StatusInternal oldStatus = mStatus;
5953 mStatus = status;
5954
5955 if (oldStatus == status) {
5956 return;
5957 }
5958
5959 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005960 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005961
5962 if (oldStatus == StatusInternal::NOT_PRESENT &&
5963 (status != StatusInternal::PRESENT &&
5964 status != StatusInternal::ENUMERATING)) {
5965
5966 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5967 __FUNCTION__);
5968 mStatus = oldStatus;
5969 return;
5970 }
5971
5972 /**
5973 * Sometimes we want to conditionally do a transition.
5974 * For example if a client disconnects, we want to go to PRESENT
5975 * only if we weren't already in NOT_PRESENT or ENUMERATING.
5976 */
5977 for (auto& rejectStatus : rejectSourceStates) {
5978 if (oldStatus == rejectStatus) {
5979 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07005980 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005981 mStatus = oldStatus;
5982 return;
5983 }
5984 }
5985
5986 onStatusUpdatedLocked(cameraId, status);
5987}
5988
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005989status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07005990 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005991 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005992 if (!status) {
5993 return BAD_VALUE;
5994 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005995 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
5996 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005997 // invalid camera ID or the camera doesn't have a flash unit
5998 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005999 }
6000
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006001 *status = mTorchStatusMap.valueAt(index);
6002 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006003}
6004
Austin Borgered99f642023-06-01 16:51:35 -07006005status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006006 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006007 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6008 if (index == NAME_NOT_FOUND) {
6009 return BAD_VALUE;
6010 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006011 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006012
6013 return OK;
6014}
6015
Austin Borgered99f642023-06-01 16:51:35 -07006016std::list<std::string> CameraService::getLogicalCameras(
6017 const std::string& physicalCameraId) {
6018 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006019 Mutex::Autolock lock(mCameraStatesLock);
6020 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006021 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6022 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006023 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006024 }
6025 return retList;
6026}
6027
6028void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006029 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006030 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006031 // mStatusListenerLock is expected to be locked
6032 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006033 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006034 // Note: we check only the deviceKind of the physical camera id
6035 // since, logical camera ids and their physical camera ids are
6036 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006037 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6038 listener->getListenerPid(), listener->getListenerUid())) {
6039 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006040 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006041 continue;
6042 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006043 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006044 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006045 listener->handleBinderStatus(ret,
6046 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6047 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6048 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006049 }
6050 }
6051}
6052
Svet Ganova453d0d2018-01-11 15:37:58 -08006053void CameraService::blockClientsForUid(uid_t uid) {
6054 const auto clients = mActiveClientManager.getAll();
6055 for (auto& current : clients) {
6056 if (current != nullptr) {
6057 const auto basicClient = current->getValue();
6058 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6059 basicClient->block();
6060 }
6061 }
6062 }
6063}
6064
Michael Grooverd1d435a2018-12-18 17:39:42 -08006065void CameraService::blockAllClients() {
6066 const auto clients = mActiveClientManager.getAll();
6067 for (auto& current : clients) {
6068 if (current != nullptr) {
6069 const auto basicClient = current->getValue();
6070 if (basicClient.get() != nullptr) {
6071 basicClient->block();
6072 }
6073 }
6074 }
6075}
6076
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006077void CameraService::blockPrivacyEnabledClients() {
6078 const auto clients = mActiveClientManager.getAll();
6079 for (auto& current : clients) {
6080 if (current != nullptr) {
6081 const auto basicClient = current->getValue();
6082 if (basicClient.get() != nullptr) {
6083 std::string pkgName = basicClient->getPackageName();
6084 bool cameraPrivacyEnabled =
6085 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6086 if (cameraPrivacyEnabled) {
6087 basicClient->block();
6088 }
6089 }
6090 }
6091 }
6092}
6093
Svet Ganova453d0d2018-01-11 15:37:58 -08006094// NOTE: This is a remote API - make sure all args are validated
6095status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006096 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006097 return PERMISSION_DENIED;
6098 }
6099 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6100 return BAD_VALUE;
6101 }
Austin Borgered99f642023-06-01 16:51:35 -07006102 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006103 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006104 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006105 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006106 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006107 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006108 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006109 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006110 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006111 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006112 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006113 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006114 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006115 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006116 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006117 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006118 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006119 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006120 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006121 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006122 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006123 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006124 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006125 handleClearStreamUseCaseOverrides();
6126 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006127 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006128 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006129 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006130 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006131 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006132 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006133 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006134 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006135 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006136 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006137 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006138 }
6139 printHelp(err);
6140 return BAD_VALUE;
6141}
6142
malikakash82ed4352023-07-21 22:44:34 +00006143status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6144 uid_t uid = IPCThreadState::self()->getCallingUid();
6145 if (uid != AID_ROOT) {
6146 dprintf(err, "Must be adb root\n");
6147 return PERMISSION_DENIED;
6148 }
6149 if (args.size() != 4) {
6150 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6151 return BAD_VALUE;
6152 }
Austin Borgered99f642023-06-01 16:51:35 -07006153 std::string packageName = toStdString(args[1]);
6154 std::string cameraIdToReplace = toStdString(args[2]);
6155 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006156 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6157 return OK;
6158}
6159
Svet Ganova453d0d2018-01-11 15:37:58 -08006160status_t CameraService::handleSetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006161 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006162
Svet Ganova453d0d2018-01-11 15:37:58 -08006163 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006164 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006165 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006166 } else if ((args[2] != toString16("idle"))) {
6167 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006168 return BAD_VALUE;
6169 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006170
6171 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006172 if (args.size() >= 5 && args[3] == toString16("--user")) {
6173 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006174 }
6175
6176 uid_t uid;
6177 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6178 return BAD_VALUE;
6179 }
6180
6181 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006182 return NO_ERROR;
6183}
6184
6185status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006186 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006187
6188 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006189 if (args.size() >= 4 && args[2] == toString16("--user")) {
6190 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006191 }
6192
6193 uid_t uid;
6194 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006195 return BAD_VALUE;
6196 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006197
6198 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006199 return NO_ERROR;
6200}
6201
6202status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006203 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006204
6205 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006206 if (args.size() >= 4 && args[2] == toString16("--user")) {
6207 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006208 }
6209
6210 uid_t uid;
6211 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006212 return BAD_VALUE;
6213 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006214
6215 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006216 return dprintf(out, "active\n");
6217 } else {
6218 return dprintf(out, "idle\n");
6219 }
6220}
6221
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006222status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006223 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006224 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6225 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6226 Mutex::Autolock lock(mServiceLock);
6227
6228 mOverrideRotateAndCropMode = rotateValue;
6229
6230 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6231
6232 const auto clients = mActiveClientManager.getAll();
6233 for (auto& current : clients) {
6234 if (current != nullptr) {
6235 const auto basicClient = current->getValue();
6236 if (basicClient.get() != nullptr) {
6237 basicClient->setRotateAndCropOverride(rotateValue);
6238 }
6239 }
6240 }
6241
6242 return OK;
6243}
6244
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006245status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6246 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006247 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006248 if ((*end != '\0') ||
6249 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6250 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6251 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6252 return BAD_VALUE;
6253 }
6254
6255 Mutex::Autolock lock(mServiceLock);
6256 mOverrideAutoframingMode = autoframingValue;
6257
6258 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6259
6260 const auto clients = mActiveClientManager.getAll();
6261 for (auto& current : clients) {
6262 if (current != nullptr) {
6263 const auto basicClient = current->getValue();
6264 if (basicClient.get() != nullptr) {
6265 basicClient->setAutoframingOverride(autoframingValue);
6266 }
6267 }
6268 }
6269
6270 return OK;
6271}
6272
Ravneetaeb20dc2022-03-30 05:33:03 +00006273status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006274 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006275
6276 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6277
6278 Mutex::Autolock lock(mServiceLock);
6279
6280 mCameraServiceWatchdogEnabled = enableWatchdog;
6281
6282 const auto clients = mActiveClientManager.getAll();
6283 for (auto& current : clients) {
6284 if (current != nullptr) {
6285 const auto basicClient = current->getValue();
6286 if (basicClient.get() != nullptr) {
6287 basicClient->setCameraServiceWatchdog(enableWatchdog);
6288 }
6289 }
6290 }
6291
6292 return OK;
6293}
6294
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006295status_t CameraService::handleGetRotateAndCrop(int out) {
6296 Mutex::Autolock lock(mServiceLock);
6297
6298 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6299}
6300
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006301status_t CameraService::handleGetAutoframing(int out) {
6302 Mutex::Autolock lock(mServiceLock);
6303
6304 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6305}
6306
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006307status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6308 char *endPtr;
6309 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006310 std::string maskString = toStdString(args[1]);
6311 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006312
6313 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006314 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006315 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6316
6317 Mutex::Autolock lock(mServiceLock);
6318
6319 mImageDumpMask = maskValue;
6320
6321 return OK;
6322}
6323
6324status_t CameraService::handleGetImageDumpMask(int out) {
6325 Mutex::Autolock lock(mServiceLock);
6326
6327 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6328}
6329
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006330status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006331 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006332 if (errno != 0) return BAD_VALUE;
6333
6334 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6335 Mutex::Autolock lock(mServiceLock);
6336
6337 mOverrideCameraMuteMode = (muteValue == 1);
6338
6339 const auto clients = mActiveClientManager.getAll();
6340 for (auto& current : clients) {
6341 if (current != nullptr) {
6342 const auto basicClient = current->getValue();
6343 if (basicClient.get() != nullptr) {
6344 if (basicClient->supportsCameraMute()) {
6345 basicClient->setCameraMute(mOverrideCameraMuteMode);
6346 }
6347 }
6348 }
6349 }
6350
6351 return OK;
6352}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006353
Shuzhen Wang16610a62022-12-15 22:38:07 -08006354status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6355 std::vector<int64_t> useCasesOverride;
6356 for (size_t i = 1; i < args.size(); i++) {
6357 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006358 std::string arg = toStdString(args[i]);
6359 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006360 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006361 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006362 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006363 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006364 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006365 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006366 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006367 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006368 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006369 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006370 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006371 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006372 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6373 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006374 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006375 return BAD_VALUE;
6376 }
6377 useCasesOverride.push_back(useCase);
6378 }
6379
6380 Mutex::Autolock lock(mServiceLock);
6381 mStreamUseCaseOverrides = std::move(useCasesOverride);
6382
6383 return OK;
6384}
6385
6386void CameraService::handleClearStreamUseCaseOverrides() {
6387 Mutex::Autolock lock(mServiceLock);
6388 mStreamUseCaseOverrides.clear();
6389}
6390
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006391status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6392 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006393 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006394 if ((*end != '\0') ||
6395 (zoomOverrideValue != -1 &&
6396 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6397 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6398 return BAD_VALUE;
6399 }
6400
6401 Mutex::Autolock lock(mServiceLock);
6402 mZoomOverrideValue = zoomOverrideValue;
6403
6404 const auto clients = mActiveClientManager.getAll();
6405 for (auto& current : clients) {
6406 if (current != nullptr) {
6407 const auto basicClient = current->getValue();
6408 if (basicClient.get() != nullptr) {
6409 if (basicClient->supportsZoomOverride()) {
6410 basicClient->setZoomOverride(mZoomOverrideValue);
6411 }
6412 }
6413 }
6414 }
6415
6416 return OK;
6417}
6418
Avichal Rakesh84147132021-11-11 17:47:11 -08006419status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006420 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006421 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006422 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006423 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006424 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006425 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006426 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006427 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006428 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006429 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006430 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006431 dprintf(outFd, "Camera service watch commands:\n"
6432 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6433 " starts watching the provided tags for clients with provided package\n"
6434 " recognizes tag shorthands like '3a'\n"
6435 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006436 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006437 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006438 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006439 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006440 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006441 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006442 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006443}
6444
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006445status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6446 Mutex::Autolock lock(mLogLock);
6447 size_t tagsIdx; // index of '-m'
6448 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006449 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006450 if (tagsIdx < args.size() - 1) {
6451 tags = args[tagsIdx + 1];
6452 } else {
6453 dprintf(outFd, "No tags provided.\n");
6454 return BAD_VALUE;
6455 }
6456
6457 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006458 // watch all clients if no clients are provided
6459 String16 clients = toString16(kWatchAllClientsFlag);
6460 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006461 clientsIdx++);
6462 if (clientsIdx < args.size() - 1) {
6463 clients = args[clientsIdx + 1];
6464 }
Austin Borgered99f642023-06-01 16:51:35 -07006465 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006466
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006467 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006468 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006469
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006470 bool serviceLock = tryLock(mServiceLock);
6471 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006472 auto cameraClients = mActiveClientManager.getAll();
6473 for (const auto &clientDescriptor: cameraClients) {
6474 if (clientDescriptor == nullptr) { continue; }
6475 sp<BasicClient> client = clientDescriptor->getValue();
6476 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006477
6478 if (isClientWatchedLocked(client.get())) {
6479 client->startWatchingTags(mMonitorTags, outFd);
6480 numWatchedClients++;
6481 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006482 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006483 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6484
6485 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006486 return OK;
6487}
6488
6489status_t CameraService::stopWatchingTags(int outFd) {
6490 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006491 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006492 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006493
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006494 mWatchedClientPackages.clear();
6495 mWatchedClientsDumpCache.clear();
6496
6497 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006498 auto cameraClients = mActiveClientManager.getAll();
6499 for (const auto &clientDescriptor : cameraClients) {
6500 if (clientDescriptor == nullptr) { continue; }
6501 sp<BasicClient> client = clientDescriptor->getValue();
6502 if (client.get() == nullptr) { continue; }
6503 client->stopWatchingTags(outFd);
6504 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006505 dprintf(outFd, "Stopped watching all clients.\n");
6506 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006507 return OK;
6508}
6509
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006510status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6511 Mutex::Autolock lock(mLogLock);
6512 size_t clearedSize = mWatchedClientsDumpCache.size();
6513 mWatchedClientsDumpCache.clear();
6514 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6515 return OK;
6516}
6517
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006518status_t CameraService::printWatchedTags(int outFd) {
6519 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006520 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006521
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006522 bool printedSomething = false; // tracks if any monitoring information was printed
6523 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006524
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006525 bool serviceLock = tryLock(mServiceLock);
6526 // get all watched clients that are currently connected
6527 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6528 if (clientDescriptor == nullptr) { continue; }
6529
6530 sp<BasicClient> client = clientDescriptor->getValue();
6531 if (client.get() == nullptr) { continue; }
6532 if (!isClientWatchedLocked(client.get())) { continue; }
6533
6534 std::vector<std::string> dumpVector;
6535 client->dumpWatchedEventsToVector(dumpVector);
6536
6537 size_t printIdx = dumpVector.size();
6538 if (printIdx == 0) {
6539 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006540 }
6541
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006542 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006543 const std::string &cameraId = clientDescriptor->getKey();
6544 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006545 while(printIdx > 0) {
6546 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006547 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006548 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006549 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006550 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006551 printedSomething = true;
6552
6553 connectedMonitoredClients.emplace(client->getPackageName());
6554 }
6555 if (serviceLock) { mServiceLock.unlock(); }
6556
6557 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6558 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006559 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006560 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6561 continue;
6562 }
6563
Austin Borgered99f642023-06-01 16:51:35 -07006564 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006565 dprintf(outFd, "%s\n", kv.second.c_str());
6566 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006567 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006568
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006569 if (!printedSomething) {
6570 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006571 }
6572
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006573 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006574}
6575
Avichal Rakesh84147132021-11-11 17:47:11 -08006576// Print all events in vector `events' that came after lastPrintedEvent
6577void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006578 const std::string &cameraId,
6579 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006580 const std::vector<std::string> &events,
6581 const std::string &lastPrintedEvent) {
6582 if (events.empty()) { return; }
6583
6584 // index of lastPrintedEvent in events.
6585 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6586 size_t lastPrintedIdx;
6587 for (lastPrintedIdx = 0;
6588 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6589 lastPrintedIdx++);
6590
6591 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6592
Avichal Rakesh84147132021-11-11 17:47:11 -08006593 // print events in chronological order (latest event last)
6594 size_t idxToPrint = lastPrintedIdx;
6595 do {
6596 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006597 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6598 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006599 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006600}
6601
6602// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6603// command should be interrupted if the user presses the return key, or if user loses any way to
6604// signal interrupt.
6605// If timeoutMs == 0, this function will always return false
6606bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6607 struct timeval startTime;
6608 int startTimeError = gettimeofday(&startTime, nullptr);
6609 if (startTimeError) {
6610 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6611 return true;
6612 }
6613
6614 const nfds_t numFds = 1;
6615 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6616
6617 struct timeval currTime;
6618 char buffer[2];
6619 while(true) {
6620 int currTimeError = gettimeofday(&currTime, nullptr);
6621 if (currTimeError) {
6622 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6623 return true;
6624 }
6625
6626 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6627 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6628 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6629
6630 if (remainingTimeMs <= 0) {
6631 // No user interrupt within timeoutMs, don't interrupt watch command
6632 return false;
6633 }
6634
6635 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6636 if (numFdsUpdated < 0) {
6637 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6638 return true;
6639 }
6640
6641 if (numFdsUpdated == 0) {
6642 // No user input within timeoutMs, don't interrupt watch command
6643 return false;
6644 }
6645
6646 if (!(pollFd.revents & POLLIN)) {
6647 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6648 return true;
6649 }
6650
6651 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6652 if (sizeRead < 0) {
6653 dprintf(outFd, "Error reading user input. Exiting.\n");
6654 return true;
6655 }
6656
6657 if (sizeRead == 0) {
6658 // Reached end of input fd (can happen if input is piped)
6659 // User has no way to signal an interrupt, so interrupt here
6660 return true;
6661 }
6662
6663 if (buffer[0] == '\n') {
6664 // User pressed return, interrupt watch command.
6665 return true;
6666 }
6667 }
6668}
6669
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006670status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6671 int inFd, int outFd) {
6672 // Figure out refresh interval, if present in args
6673 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006674 if (args.size() > 2) {
6675 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006676 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006677 intervalIdx++);
6678
6679 size_t intervalValIdx = intervalIdx + 1;
6680 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006681 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006682 if (errno) { return BAD_VALUE; }
6683 }
6684 }
6685
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006686 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6687 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006688
Avichal Rakesh84147132021-11-11 17:47:11 -08006689 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006690 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006691
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006692 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006693 bool serviceLock = tryLock(mServiceLock);
6694 auto cameraClients = mActiveClientManager.getAll();
6695 if (serviceLock) { mServiceLock.unlock(); }
6696
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006697 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006698 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006699 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006700
6701 sp<BasicClient> client = clientDescriptor->getValue();
6702 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006703 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006704
Austin Borgered99f642023-06-01 16:51:35 -07006705 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006706 // This also initializes the map entries with an empty string
6707 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6708
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006709 std::vector<std::string> latestEvents;
6710 client->dumpWatchedEventsToVector(latestEvents);
6711
6712 if (!latestEvents.empty()) {
6713 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006714 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006715 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006716 latestEvents,
6717 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006718 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006719 }
6720 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006721 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006722 break;
6723 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006724 }
6725 return OK;
6726}
6727
Austin Borgered99f642023-06-01 16:51:35 -07006728void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006729 mWatchedClientPackages.clear();
6730
Austin Borgered99f642023-06-01 16:51:35 -07006731 std::istringstream iss(clients);
6732 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006733
Austin Borgered99f642023-06-01 16:51:35 -07006734 while (std::getline(iss, nextClient, ',')) {
6735 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006736 // Don't need to track any other package if 'all' is present
6737 mWatchedClientPackages.clear();
6738 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6739 break;
6740 }
6741
6742 // track package names
6743 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006744 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006745}
6746
Svet Ganova453d0d2018-01-11 15:37:58 -08006747status_t CameraService::printHelp(int out) {
6748 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006749 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6750 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6751 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006752 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6753 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6754 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006755 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6756 " Valid values 0=false, 1=true, 2=auto\n"
6757 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006758 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6759 " Valid values 0=OFF, 1=ON for JPEG\n"
6760 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006761 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006762 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6763 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6764 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6765 " on. In case the number of usecases is smaller than the number of streams, the\n"
6766 " last use case is assigned to all the remaining streams. In case of multiple\n"
6767 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6768 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6769 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6770 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006771 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6772 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006773 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6774 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006775 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006776 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006777 " help print this message\n");
6778}
6779
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006780bool CameraService::isClientWatched(const BasicClient *client) {
6781 Mutex::Autolock lock(mLogLock);
6782 return isClientWatchedLocked(client);
6783}
6784
6785bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6786 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6787 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6788}
6789
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006790int32_t CameraService::updateAudioRestriction() {
6791 Mutex::Autolock lock(mServiceLock);
6792 return updateAudioRestrictionLocked();
6793}
6794
6795int32_t CameraService::updateAudioRestrictionLocked() {
6796 int32_t mode = 0;
6797 // iterate through all active client
6798 for (const auto& i : mActiveClientManager.getAll()) {
6799 const auto clientSp = i->getValue();
6800 mode |= clientSp->getAudioRestriction();
6801 }
6802
6803 bool modeChanged = (mAudioRestriction != mode);
6804 mAudioRestriction = mode;
6805 if (modeChanged) {
6806 mAppOps.setCameraAudioRestriction(mode);
6807 }
6808 return mode;
6809}
6810
Austin Borgered99f642023-06-01 16:51:35 -07006811status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006812 sp<BasicClient> clientSp) {
6813 std::unique_ptr<AutoConditionLock> lock =
6814 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6815 status_t res = NO_ERROR;
6816 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006817 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006818 mInjectionStatusListener->notifyInjectionError(
6819 externalCamId, UNKNOWN_TRANSACTION);
6820 clientSp->notifyError(
6821 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6822 CaptureResultExtras());
6823
6824 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6825 // other clients from connecting in mServiceLockWrapper if held
6826 mServiceLock.unlock();
6827
6828 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006829 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006830 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006831 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006832
6833 // Reacquire mServiceLock
6834 mServiceLock.lock();
6835 }
6836
6837 return res;
6838}
6839
Cliff Wud3a05312021-04-26 23:07:31 +08006840void CameraService::clearInjectionParameters() {
6841 {
6842 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006843 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006844 mInjectionInternalCamId = "";
6845 }
6846 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006847 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006848}
6849
Biswarup Pal37a75182024-01-16 15:53:35 +00006850} // namespace android