blob: fbb485c9c603769174ee7afe399d68c251716eb1 [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"
Igor Murashkinff3e31d2013-10-23 16:40:06 -070085#include "utils/CameraTraces.h"
Emilian Peevbd8c5032018-02-14 23:05:40 +000086#include "utils/TagMonitor.h"
Shuzhen Wang316781a2020-08-18 18:11:01 -070087#include "utils/CameraServiceProxyWrapper.h"
Shuzhen Wang045be6c2023-10-12 10:01:10 -070088#include "utils/SessionConfigurationUtils.h"
Mathias Agopian65ab4712010-07-14 17:59:35 -070089
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -080090namespace {
91 const char* kPermissionServiceName = "permission";
Jyoti Bhayanacde601c2022-12-07 10:03:42 -080092 const char* kActivityServiceName = "activity";
93 const char* kSensorPrivacyServiceName = "sensor_privacy";
94 const char* kAppopsServiceName = "appops";
Jyoti Bhayanada519ab2023-05-15 15:49:15 -070095 const char* kProcessInfoServiceName = "processinfo";
Biswarup Pal37a75182024-01-16 15:53:35 +000096 const char* kVirtualDeviceBackCameraId = "0";
97 const char* kVirtualDeviceFrontCameraId = "1";
98
99 int32_t getDeviceId(const android::CameraMetadata& cameraInfo) {
100 if (!cameraInfo.exists(ANDROID_INFO_DEVICE_ID)) {
101 return android::kDefaultDeviceId;
102 }
103
104 const auto &deviceIdEntry = cameraInfo.find(ANDROID_INFO_DEVICE_ID);
105 return deviceIdEntry.data.i32[0];
106 }
107} // namespace anonymous
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -0800108
Mathias Agopian65ab4712010-07-14 17:59:35 -0700109namespace android {
110
Austin Borgerea931242021-12-13 23:10:41 +0000111using namespace camera3;
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700112using namespace camera3::SessionConfigurationUtils;
113
114using binder::Status;
Biswarup Pal37a75182024-01-16 15:53:35 +0000115using companion::virtualnative::IVirtualDeviceManagerNative;
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700116using frameworks::cameraservice::service::V2_0::implementation::HidlCameraService;
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700117using frameworks::cameraservice::service::implementation::AidlCameraService;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800118using hardware::ICamera;
119using hardware::ICameraClient;
120using hardware::ICameraServiceListener;
Cliff Wud8cae102021-03-11 01:37:42 +0800121using hardware::camera2::ICameraInjectionCallback;
122using hardware::camera2::ICameraInjectionSession;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -0800123using hardware::camera2::utils::CameraIdAndSessionConfiguration;
124using hardware::camera2::utils::ConcurrentCameraIdCombination;
Biswarup Pal37a75182024-01-16 15:53:35 +0000125
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -0700126namespace flags = com::android::internal::camera::flags;
Biswarup Pal37a75182024-01-16 15:53:35 +0000127namespace vd_flags = android::companion::virtualdevice::flags;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800128
Mathias Agopian65ab4712010-07-14 17:59:35 -0700129// ----------------------------------------------------------------------------
130// Logging support -- this is for debugging only
131// Use "adb shell dumpsys media.camera -v 1" to change it.
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700132volatile int32_t gLogLevel = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -0700133
Steve Blockb8a80522011-12-20 16:23:08 +0000134#define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
135#define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700136
137static void setLogLevel(int level) {
138 android_atomic_write(level, &gLogLevel);
139}
140
Henri Chataingbcb99452023-11-01 17:40:30 +0000141int32_t format_as(CameraService::StatusInternal s) {
142 return fmt::underlying(s);
143}
144
Mathias Agopian65ab4712010-07-14 17:59:35 -0700145// ----------------------------------------------------------------------------
146
Austin Borger249e6592024-03-10 22:28:11 -0700147// Permission strings (references to AttributionAndPermissionUtils for brevity)
148static const std::string &sDumpPermission =
149 AttributionAndPermissionUtils::sDumpPermission;
150static const std::string &sManageCameraPermission =
151 AttributionAndPermissionUtils::sManageCameraPermission;
152static const std::string &sCameraSendSystemEventsPermission =
153 AttributionAndPermissionUtils::sCameraSendSystemEventsPermission;
154static const std::string &sCameraInjectExternalCameraPermission =
155 AttributionAndPermissionUtils::sCameraInjectExternalCameraPermission;
156
Kunal Malhotrabfc96052023-02-28 23:25:34 +0000157// Constant integer for FGS Logging, used to denote the API type for logger
158static const int LOG_FGS_CAMERA_API = 1;
Rucha Katakwardf223072021-06-15 10:21:00 -0700159const char *sFileName = "lastOpenSessionDumpFile";
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -0800160static constexpr int32_t kSystemNativeClientScore = resource_policy::PERCEPTIBLE_APP_ADJ;
161static constexpr int32_t kSystemNativeClientState =
162 ActivityManager::PROCESS_STATE_PERSISTENT_UI;
Austin Borgered99f642023-06-01 16:51:35 -0700163static const std::string kServiceName("cameraserver");
Eino-Ville Talvala7c602c32021-03-20 17:00:18 -0700164
Austin Borgered99f642023-06-01 16:51:35 -0700165const std::string CameraService::kOfflineDevice("offline-");
166const std::string CameraService::kWatchAllClientsFlag("all");
Jayant Chowdharyc578a502019-05-08 10:57:54 -0700167
Biswarup Pal7d072862024-04-17 15:24:47 +0000168constexpr int32_t kInvalidDeviceId = -1;
169
Rucha Katakward9ea6452021-05-06 11:57:16 -0700170// Set to keep track of logged service error events.
Austin Borgered99f642023-06-01 16:51:35 -0700171static std::set<std::string> sServiceErrorEventSet;
Rucha Katakward9ea6452021-05-06 11:57:16 -0700172
Austin Borger74fca042022-05-23 12:41:21 -0700173CameraService::CameraService(
Austin Borger249e6592024-03-10 22:28:11 -0700174 std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
175 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils) :
176 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils == nullptr ?
177 std::make_shared<AttributionAndPermissionUtils>()\
178 : attributionAndPermissionUtils),
Austin Borger74fca042022-05-23 12:41:21 -0700179 mCameraServiceProxyWrapper(cameraServiceProxyWrapper == nullptr ?
180 std::make_shared<CameraServiceProxyWrapper>() : cameraServiceProxyWrapper),
Eino-Ville Talvala49c97052016-01-12 14:29:40 -0800181 mEventLog(DEFAULT_EVENT_LOG_LENGTH),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800182 mNumberOfCameras(0),
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700183 mNumberOfCamerasWithoutSystemCamera(0),
Yin-Chia Yehdba03232019-08-19 15:54:28 -0700184 mSoundRef(0), mInitialized(false),
185 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE) {
Steve Blockdf64d152012-01-04 20:05:49 +0000186 ALOGI("CameraService started (pid=%d)", getpid());
Austin Borger249e6592024-03-10 22:28:11 -0700187 mAttributionAndPermissionUtils->setCameraService(this);
Ruben Brunkcc776712015-02-17 20:18:47 -0800188 mServiceLockWrapper = std::make_shared<WaitableMutexWrapper>(&mServiceLock);
Rucha Katakwardf223072021-06-15 10:21:00 -0700189 mMemFd = memfd_create(sFileName, MFD_ALLOW_SEALING);
190 if (mMemFd == -1) {
191 ALOGE("%s: Error while creating the file: %s", __FUNCTION__, sFileName);
192 }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700193}
194
Charles Chena7b613c2023-01-24 21:57:33 +0000195// Enable processes with isolated AID to request the binder
196void CameraService::instantiate() {
197 CameraService::publish(true);
198}
199
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800200void CameraService::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -0700201 if (name != toString16(kAppopsServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800202 return;
203 }
204
205 ALOGV("appops service registered. setting camera audio restriction");
206 mAppOps.setCameraAudioRestriction(mAudioRestriction);
207}
208
Iliyan Malchev8951a972011-04-14 16:55:59 -0700209void CameraService::onFirstRef()
210{
Ruben Brunkcc776712015-02-17 20:18:47 -0800211 ALOGI("CameraService process starting");
Igor Murashkin634a5152013-02-20 17:15:11 -0800212
Iliyan Malchev8951a972011-04-14 16:55:59 -0700213 BnCameraService::onFirstRef();
214
Ruben Brunk99e69712015-05-26 17:25:07 -0700215 // Update battery life tracking if service is restarting
216 BatteryNotifier& notifier(BatteryNotifier::getInstance());
217 notifier.noteResetCamera();
218 notifier.noteResetFlashlight();
219
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800220 status_t res = INVALID_OPERATION;
Eino-Ville Talvala9cbbc832017-01-23 15:39:53 -0800221
Emilian Peevf53f66e2017-04-11 14:29:43 +0100222 res = enumerateProviders();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800223 if (res == OK) {
224 mInitialized = true;
225 }
226
Svet Ganova453d0d2018-01-11 15:37:58 -0800227 mUidPolicy = new UidPolicy(this);
228 mUidPolicy->registerSelf();
Austin Borger249e6592024-03-10 22:28:11 -0700229 mSensorPrivacyPolicy = new SensorPrivacyPolicy(this, mAttributionAndPermissionUtils);
Michael Grooverd1d435a2018-12-18 17:39:42 -0800230 mSensorPrivacyPolicy->registerSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800231 mInjectionStatusListener = new InjectionStatusListener(this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800232
233 // appops function setCamerAudioRestriction uses getService which
234 // is blocking till the appops service is ready. To enable early
235 // boot availability for cameraservice, use checkService which is
236 // non blocking and register for notifications
237 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -0700238 sp<IBinder> binder = sm->checkService(toString16(kAppopsServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800239 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -0700240 sm->registerForNotifications(toString16(kAppopsServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -0800241 } else {
242 mAppOps.setCameraAudioRestriction(mAudioRestriction);
243 }
244
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700245 sp<HidlCameraService> hcs = HidlCameraService::getInstance(this);
246 if (hcs->registerAsService() != android::OK) {
Devin Moorea1350e72023-01-11 23:40:42 +0000247 // Deprecated, so it will fail to register on newer devices
248 ALOGW("%s: Did not register default android.frameworks.cameraservice.service@2.2",
Jayant Chowdharybe543d42018-08-15 13:16:14 -0700249 __FUNCTION__);
250 }
Shuzhen Wang24b44152019-09-20 10:38:11 -0700251
Avichal Rakeshfcb78cb2022-10-27 15:45:54 -0700252 if (!AidlCameraService::registerService(this)) {
253 ALOGE("%s: Failed to register default AIDL VNDK CameraService", __FUNCTION__);
254 }
255
Shuzhen Wang24b44152019-09-20 10:38:11 -0700256 // This needs to be last call in this function, so that it's as close to
257 // ServiceManager::addService() as possible.
Austin Borger74fca042022-05-23 12:41:21 -0700258 mCameraServiceProxyWrapper->pingCameraServiceProxy();
Shuzhen Wang24b44152019-09-20 10:38:11 -0700259 ALOGI("CameraService pinged cameraservice proxy");
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800260}
261
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800262status_t CameraService::enumerateProviders() {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800263 status_t res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100264
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800265 std::vector<std::string> deviceIds;
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000266 std::unordered_map<std::string, std::set<std::string>> unavailPhysicalIds;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800267 {
268 Mutex::Autolock l(mServiceLock);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800269
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800270 if (nullptr == mCameraProviderManager.get()) {
271 mCameraProviderManager = new CameraProviderManager();
272 res = mCameraProviderManager->initialize(this);
273 if (res != OK) {
274 ALOGE("%s: Unable to initialize camera provider manager: %s (%d)",
275 __FUNCTION__, strerror(-res), res);
Austin Borgered99f642023-06-01 16:51:35 -0700276 logServiceError("Unable to initialize camera provider manager",
277 ERROR_DISCONNECTED);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800278 return res;
Emilian Peevaee727d2017-05-04 16:35:48 +0100279 }
280 }
281
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800282 // Setup vendor tags before we call get_camera_info the first time
283 // because HAL might need to setup static vendor keys in get_camera_info
284 // TODO: maybe put this into CameraProviderManager::initialize()?
285 mCameraProviderManager->setUpVendorTags();
286
287 if (nullptr == mFlashlight.get()) {
288 mFlashlight = new CameraFlashlight(mCameraProviderManager, this);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700289 }
290
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800291 res = mFlashlight->findFlashUnits();
292 if (res != OK) {
293 ALOGE("Failed to enumerate flash units: %s (%d)", strerror(-res), res);
294 }
295
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000296 deviceIds = mCameraProviderManager->getCameraDeviceIds(&unavailPhysicalIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800297 }
298
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800299 for (auto& cameraId : deviceIds) {
Austin Borgered99f642023-06-01 16:51:35 -0700300 if (getCameraState(cameraId) == nullptr) {
301 onDeviceStatusChanged(cameraId, CameraDeviceStatus::PRESENT);
Shuzhen Wang6ba3f5e2018-11-20 10:04:08 -0800302 }
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000303 if (unavailPhysicalIds.count(cameraId) > 0) {
304 for (const auto& physicalId : unavailPhysicalIds[cameraId]) {
Austin Borgered99f642023-06-01 16:51:35 -0700305 onDeviceStatusChanged(cameraId, physicalId, CameraDeviceStatus::NOT_PRESENT);
Shuzhen Wang3d316f32022-10-25 20:33:34 +0000306 }
307 }
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800308 }
309
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700310 // Derive primary rear/front cameras, and filter their charactierstics.
311 // This needs to be done after all cameras are enumerated and camera ids are sorted.
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700312 if (SessionConfigurationUtils::IS_PERF_CLASS) {
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700313 // Assume internal cameras are advertised from the same
314 // provider. If multiple providers are registered at different time,
315 // and each provider contains multiple internal color cameras, the current
316 // logic may filter the characteristics of more than one front/rear color
317 // cameras.
318 Mutex::Autolock l(mServiceLock);
319 filterSPerfClassCharacteristicsLocked();
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700320 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700321
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -0800322 return OK;
323}
324
Austin Borgered99f642023-06-01 16:51:35 -0700325void CameraService::broadcastTorchModeStatus(const std::string& cameraId, TorchModeStatus status,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700326 SystemCameraKind systemCameraKind) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000327 // Get the device id and app-visible camera id for the given HAL-visible camera id.
328 auto [deviceId, mappedCameraId] =
329 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
330
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800331 Mutex::Autolock lock(mStatusListenerLock);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800332 for (auto& i : mListenerList) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700333 if (shouldSkipStatusUpdates(systemCameraKind, i->isVendorListener(), i->getListenerPid(),
334 i->getListenerUid())) {
malikakash82ed4352023-07-21 22:44:34 +0000335 ALOGV("%s: Skipping torch callback for system-only camera device %s",
336 __FUNCTION__, cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700337 continue;
338 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000339
Austin Borgere8e2c422022-05-12 13:45:24 -0700340 auto ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
Biswarup Pal37a75182024-01-16 15:53:35 +0000341 mappedCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700342 i->handleBinderStatus(ret, "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
343 __FUNCTION__, i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +0000344
345 // Only cameras of the default device can be remapped to a different camera (using
346 // remapCameraIds method), so do the following only if the camera is associated with the
347 // default device.
348 if (deviceId == kDefaultDeviceId) {
349 // For the default device, also trigger the torch callbacks for cameras that were
350 // remapped to the current cameraId for the specific package that this listener belongs
351 // to.
352 std::vector<std::string> remappedCameraIds =
353 findOriginalIdsForRemappedCameraId(cameraId, i->getListenerUid());
354 for (auto &remappedCameraId: remappedCameraIds) {
355 ret = i->getListener()->onTorchStatusChanged(mapToInterface(status),
356 remappedCameraId, kDefaultDeviceId);
357 i->handleBinderStatus(ret,
358 "%s: Failed to trigger onTorchStatusChanged for %d:%d: %d",
359 __FUNCTION__, i->getListenerUid(), i->getListenerPid(),
360 ret.exceptionCode());
361 }
malikakash82ed4352023-07-21 22:44:34 +0000362 }
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800363 }
364}
365
Mathias Agopian65ab4712010-07-14 17:59:35 -0700366CameraService::~CameraService() {
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800367 VendorTagDescriptor::clearGlobalVendorTagDescriptor();
Svet Ganova453d0d2018-01-11 15:37:58 -0800368 mUidPolicy->unregisterSelf();
Michael Grooverd1d435a2018-12-18 17:39:42 -0800369 mSensorPrivacyPolicy->unregisterSelf();
Cliff Wud8cae102021-03-11 01:37:42 +0800370 mInjectionStatusListener->removeListener();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700371}
372
Emilian Peevaee727d2017-05-04 16:35:48 +0100373void CameraService::onNewProviderRegistered() {
374 enumerateProviders();
375}
376
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700377void CameraService::filterAPI1SystemCameraLocked(
378 const std::vector<std::string> &normalDeviceIds) {
379 mNormalDeviceIdsWithoutSystemCamera.clear();
Biswarup Pal37a75182024-01-16 15:53:35 +0000380 for (auto &cameraId : normalDeviceIds) {
381 if (vd_flags::camera_device_awareness()) {
382 CameraMetadata cameraInfo;
383 status_t res = mCameraProviderManager->getCameraCharacteristics(
384 cameraId, false, &cameraInfo, false);
385 int32_t deviceId = kDefaultDeviceId;
386 if (res != OK) {
387 ALOGW("%s: Not able to get camera characteristics for camera id %s",
388 __FUNCTION__, cameraId.c_str());
389 } else {
390 deviceId = getDeviceId(cameraInfo);
391 }
392 // Cameras associated with non-default device id's (i.e., virtual cameras) can never be
393 // system cameras, so skip for non-default device id's.
394 if (deviceId != kDefaultDeviceId) {
395 continue;
396 }
397 }
398
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700399 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Biswarup Pal37a75182024-01-16 15:53:35 +0000400 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
401 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700402 continue;
403 }
404 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700405 // All system camera ids will necessarily come after public camera
406 // device ids as per the HAL interface contract.
407 break;
408 }
Biswarup Pal37a75182024-01-16 15:53:35 +0000409 mNormalDeviceIdsWithoutSystemCamera.push_back(cameraId);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700410 }
411 ALOGV("%s: number of API1 compatible public cameras is %zu", __FUNCTION__,
412 mNormalDeviceIdsWithoutSystemCamera.size());
413}
414
Austin Borgered99f642023-06-01 16:51:35 -0700415status_t CameraService::getSystemCameraKind(const std::string& cameraId,
416 SystemCameraKind *kind) const {
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700417 auto state = getCameraState(cameraId);
418 if (state != nullptr) {
419 *kind = state->getSystemCameraKind();
420 return OK;
421 }
422 // Hidden physical camera ids won't have CameraState
Austin Borgered99f642023-06-01 16:51:35 -0700423 return mCameraProviderManager->getSystemCameraKind(cameraId, kind);
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700424}
425
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800426void CameraService::updateCameraNumAndIds() {
427 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700428 std::pair<int, int> systemAndNonSystemCameras = mCameraProviderManager->getCameraCount();
429 // Excludes hidden secure cameras
430 mNumberOfCameras =
431 systemAndNonSystemCameras.first + systemAndNonSystemCameras.second;
432 mNumberOfCamerasWithoutSystemCamera = systemAndNonSystemCameras.second;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800433 mNormalDeviceIds =
434 mCameraProviderManager->getAPI1CompatibleCameraDeviceIds();
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700435 filterAPI1SystemCameraLocked(mNormalDeviceIds);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800436}
437
Shuzhen Wangb38b53f2021-07-15 12:46:09 -0700438void CameraService::filterSPerfClassCharacteristicsLocked() {
Shuzhen Wang89db2992021-05-20 13:09:48 -0700439 // To claim to be S Performance primary cameras, the cameras must be
440 // backward compatible. So performance class primary camera Ids must be API1
441 // compatible.
442 bool firstRearCameraSeen = false, firstFrontCameraSeen = false;
443 for (const auto& cameraId : mNormalDeviceIdsWithoutSystemCamera) {
444 int facing = -1;
445 int orientation = 0;
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800446 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -0700447 getDeviceVersion(cameraId, /*overrideToPortrait*/false, /*out*/&portraitRotation,
Shuzhen Wangf221e8d2022-12-15 13:26:29 -0800448 /*out*/&facing, /*out*/&orientation);
Shuzhen Wang89db2992021-05-20 13:09:48 -0700449 if (facing == -1) {
450 ALOGE("%s: Unable to get camera device \"%s\" facing", __FUNCTION__, cameraId.c_str());
451 return;
452 }
453
454 if ((facing == hardware::CAMERA_FACING_BACK && !firstRearCameraSeen) ||
455 (facing == hardware::CAMERA_FACING_FRONT && !firstFrontCameraSeen)) {
Shuzhen Wangd4abdf72021-05-28 11:22:50 -0700456 status_t res = mCameraProviderManager->filterSmallJpegSizes(cameraId);
457 if (res == OK) {
458 mPerfClassPrimaryCameraIds.insert(cameraId);
459 } else {
460 ALOGE("%s: Failed to filter small JPEG sizes for performance class primary "
461 "camera %s: %s(%d)", __FUNCTION__, cameraId.c_str(), strerror(-res), res);
462 break;
463 }
Shuzhen Wang89db2992021-05-20 13:09:48 -0700464
465 if (facing == hardware::CAMERA_FACING_BACK) {
466 firstRearCameraSeen = true;
467 }
468 if (facing == hardware::CAMERA_FACING_FRONT) {
469 firstFrontCameraSeen = true;
470 }
471 }
472
473 if (firstRearCameraSeen && firstFrontCameraSeen) {
474 break;
475 }
476 }
477}
478
Austin Borgered99f642023-06-01 16:51:35 -0700479void CameraService::addStates(const std::string& cameraId) {
Jayant Chowdhary0bd38522021-11-05 17:49:27 -0700480 CameraResourceCost cost;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100481 status_t res = mCameraProviderManager->getResourceCost(cameraId, &cost);
482 if (res != OK) {
483 ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
484 return;
485 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000486 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -0700487 res = mCameraProviderManager->getSystemCameraKind(cameraId, &deviceKind);
488 if (res != OK) {
489 ALOGE("Failed to query device kind: %s (%d)", strerror(-res), res);
490 return;
491 }
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000492 std::vector<std::string> physicalCameraIds;
493 mCameraProviderManager->isLogicalCamera(cameraId, &physicalCameraIds);
Austin Borgered99f642023-06-01 16:51:35 -0700494 std::set<std::string> conflicting;
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100495 for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -0700496 conflicting.emplace(cost.conflictingDevices[i]);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100497 }
498
499 {
500 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700501 mCameraStates.emplace(cameraId, std::make_shared<CameraState>(cameraId, cost.resourceCost,
Shuzhen Wang403af6d2021-12-21 00:08:43 +0000502 conflicting, deviceKind, physicalCameraIds));
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100503 }
504
Austin Borgered99f642023-06-01 16:51:35 -0700505 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100506 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700507 mTorchStatusMap.add(cameraId, TorchModeStatus::AVAILABLE_OFF);
Shuzhen Wang7d859d42018-11-06 15:33:23 -0800508
Austin Borgered99f642023-06-01 16:51:35 -0700509 broadcastTorchModeStatus(cameraId, TorchModeStatus::AVAILABLE_OFF, deviceKind);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100510 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800511
512 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700513 logDeviceAdded(cameraId, "Device added");
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100514}
515
Austin Borgered99f642023-06-01 16:51:35 -0700516void CameraService::removeStates(const std::string& cameraId) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800517 updateCameraNumAndIds();
Austin Borgered99f642023-06-01 16:51:35 -0700518 if (mFlashlight->hasFlashUnit(cameraId)) {
Emilian Peev7f25e5f2018-04-11 16:50:34 +0100519 Mutex::Autolock al(mTorchStatusMutex);
Austin Borgered99f642023-06-01 16:51:35 -0700520 mTorchStatusMap.removeItem(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100521 }
522
523 {
524 Mutex::Autolock lock(mCameraStatesLock);
Austin Borgered99f642023-06-01 16:51:35 -0700525 mCameraStates.erase(cameraId);
Guennadi Liakhovetski6034bf52017-12-07 10:28:29 +0100526 }
527}
528
Austin Borgered99f642023-06-01 16:51:35 -0700529void CameraService::onDeviceStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800530 CameraDeviceStatus newHalStatus) {
531 ALOGI("%s: Status changed for cameraId=%s, newStatus=%d", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700532 cameraId.c_str(), newHalStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700533
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800534 StatusInternal newStatus = mapToInternal(newHalStatus);
535
Austin Borgered99f642023-06-01 16:51:35 -0700536 std::shared_ptr<CameraState> state = getCameraState(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800537
538 if (state == nullptr) {
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700539 if (newStatus == StatusInternal::PRESENT) {
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100540 ALOGI("%s: Unknown camera ID %s, a new camera is added",
Austin Borgered99f642023-06-01 16:51:35 -0700541 __FUNCTION__, cameraId.c_str());
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100542
543 // First add as absent to make sure clients are notified below
Austin Borgered99f642023-06-01 16:51:35 -0700544 addStates(cameraId);
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +0100545
Austin Borgered99f642023-06-01 16:51:35 -0700546 updateStatus(newStatus, cameraId);
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700547 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700548 ALOGE("%s: Bad camera ID %s", __FUNCTION__, cameraId.c_str());
Yin-Chia Yeh92e33212017-05-24 15:54:15 -0700549 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700550 return;
551 }
552
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800553 StatusInternal oldStatus = state->getStatus();
Ruben Brunkcc776712015-02-17 20:18:47 -0800554
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800555 if (oldStatus == newStatus) {
Ruben Brunkcc776712015-02-17 20:18:47 -0800556 ALOGE("%s: State transition to the same status %#x not allowed", __FUNCTION__, newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700557 return;
558 }
559
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800560 if (newStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000561 logDeviceRemoved(cameraId, fmt::format("Device status changed from {} to {}",
562 oldStatus, newStatus));
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800563 // Set the device status to NOT_PRESENT, clients will no longer be able to connect
564 // to this device until the status changes
Austin Borgered99f642023-06-01 16:51:35 -0700565 updateStatus(StatusInternal::NOT_PRESENT, cameraId);
Biswarup Pal37a75182024-01-16 15:53:35 +0000566 mVirtualDeviceCameraIdMapper.removeCamera(cameraId);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -0800567
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800568 sp<BasicClient> clientToDisconnectOnline, clientToDisconnectOffline;
Igor Murashkincba2c162013-03-20 15:56:31 -0700569 {
Ruben Brunkcc776712015-02-17 20:18:47 -0800570 // Don't do this in updateStatus to avoid deadlock over mServiceLock
571 Mutex::Autolock lock(mServiceLock);
Igor Murashkincba2c162013-03-20 15:56:31 -0700572
Ruben Brunkcc776712015-02-17 20:18:47 -0800573 // Remove cached shim parameters
574 state->setShimParams(CameraParameters());
Igor Murashkincba2c162013-03-20 15:56:31 -0700575
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800576 // Remove online as well as offline client from the list of active clients,
577 // if they are present
Austin Borgered99f642023-06-01 16:51:35 -0700578 clientToDisconnectOnline = removeClientLocked(cameraId);
579 clientToDisconnectOffline = removeClientLocked(kOfflineDevice + cameraId);
Eino-Ville Talvala8d942f92017-03-13 10:09:51 -0700580 }
Ruben Brunkcc776712015-02-17 20:18:47 -0800581
Austin Borgered99f642023-06-01 16:51:35 -0700582 disconnectClient(cameraId, clientToDisconnectOnline);
583 disconnectClient(kOfflineDevice + cameraId, clientToDisconnectOffline);
Igor Murashkincba2c162013-03-20 15:56:31 -0700584
Austin Borgered99f642023-06-01 16:51:35 -0700585 removeStates(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -0800586 } else {
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800587 if (oldStatus == StatusInternal::NOT_PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000588 logDeviceAdded(cameraId, fmt::format("Device status changed from {} to {}",
589 oldStatus, newStatus));
Ruben Brunka8ca9152015-04-07 14:23:40 -0700590 }
Austin Borgered99f642023-06-01 16:51:35 -0700591 updateStatus(newStatus, cameraId);
Igor Murashkincba2c162013-03-20 15:56:31 -0700592 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800593}
Igor Murashkincba2c162013-03-20 15:56:31 -0700594
Austin Borgered99f642023-06-01 16:51:35 -0700595void CameraService::onDeviceStatusChanged(const std::string& id,
596 const std::string& physicalId,
Shuzhen Wang43858162020-01-10 13:42:15 -0800597 CameraDeviceStatus newHalStatus) {
598 ALOGI("%s: Status changed for cameraId=%s, physicalCameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700599 __FUNCTION__, id.c_str(), physicalId.c_str(), newHalStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800600
601 StatusInternal newStatus = mapToInternal(newHalStatus);
602
603 std::shared_ptr<CameraState> state = getCameraState(id);
604
605 if (state == nullptr) {
606 ALOGE("%s: Physical camera id %s status change on a non-present ID %s",
Austin Borgered99f642023-06-01 16:51:35 -0700607 __FUNCTION__, physicalId.c_str(), id.c_str());
Shuzhen Wang43858162020-01-10 13:42:15 -0800608 return;
609 }
610
611 StatusInternal logicalCameraStatus = state->getStatus();
612 if (logicalCameraStatus != StatusInternal::PRESENT &&
613 logicalCameraStatus != StatusInternal::NOT_AVAILABLE) {
614 ALOGE("%s: Physical camera id %s status %d change for an invalid logical camera state %d",
Austin Borgered99f642023-06-01 16:51:35 -0700615 __FUNCTION__, physicalId.c_str(), newHalStatus, logicalCameraStatus);
Shuzhen Wang43858162020-01-10 13:42:15 -0800616 return;
617 }
618
619 bool updated = false;
620 if (newStatus == StatusInternal::PRESENT) {
621 updated = state->removeUnavailablePhysicalId(physicalId);
622 } else {
623 updated = state->addUnavailablePhysicalId(physicalId);
624 }
625
626 if (updated) {
Austin Borgered99f642023-06-01 16:51:35 -0700627 std::string idCombo = id + " : " + physicalId;
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800628 if (newStatus == StatusInternal::PRESENT) {
Henri Chataingbcb99452023-11-01 17:40:30 +0000629 logDeviceAdded(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800630 } else {
Henri Chataingbcb99452023-11-01 17:40:30 +0000631 logDeviceRemoved(idCombo, fmt::format("Device status changed to {}", newStatus));
Shuzhen Wang4fa28d22020-01-23 15:57:25 -0800632 }
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700633 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
634 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
635 if (getSystemCameraKind(id, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -0700636 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, id.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700637 return;
638 }
Shuzhen Wang43858162020-01-10 13:42:15 -0800639 Mutex::Autolock lock(mStatusListenerLock);
640 for (auto& listener : mListenerList) {
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -0700641 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
642 listener->getListenerPid(), listener->getListenerUid())) {
643 ALOGV("Skipping discovery callback for system-only camera device %s",
644 id.c_str());
645 continue;
646 }
Austin Borgere8e2c422022-05-12 13:45:24 -0700647 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(
Biswarup Pal37a75182024-01-16 15:53:35 +0000648 mapToInterface(newStatus), id, physicalId, kDefaultDeviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700649 listener->handleBinderStatus(ret,
650 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
651 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
652 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -0800653 }
654 }
Igor Murashkincba2c162013-03-20 15:56:31 -0700655}
656
Austin Borgered99f642023-06-01 16:51:35 -0700657void CameraService::disconnectClient(const std::string& id, sp<BasicClient> clientToDisconnect) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800658 if (clientToDisconnect.get() != nullptr) {
659 ALOGI("%s: Client for camera ID %s evicted due to device status change from HAL",
Austin Borgered99f642023-06-01 16:51:35 -0700660 __FUNCTION__, id.c_str());
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800661 // Notify the client of disconnection
662 clientToDisconnect->notifyError(
663 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
664 CaptureResultExtras{});
Emilian Peevb2bc5a42019-11-20 16:02:14 -0800665 clientToDisconnect->disconnect();
666 }
667}
668
Austin Borgered99f642023-06-01 16:51:35 -0700669void CameraService::onTorchStatusChanged(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800670 TorchModeStatus newStatus) {
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700671 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
672 status_t res = getSystemCameraKind(cameraId, &systemCameraKind);
673 if (res != OK) {
674 ALOGE("%s: Could not get system camera kind for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -0700675 cameraId.c_str());
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700676 return;
677 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800678 Mutex::Autolock al(mTorchStatusMutex);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700679 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800680}
681
Austin Borgered99f642023-06-01 16:51:35 -0700682void CameraService::onTorchStatusChanged(const std::string& cameraId,
Jayant Chowdhary46ef0f52021-10-05 14:36:13 -0700683 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
684 Mutex::Autolock al(mTorchStatusMutex);
685 onTorchStatusChangedLocked(cameraId, newStatus, systemCameraKind);
686}
687
Austin Borgered99f642023-06-01 16:51:35 -0700688void CameraService::broadcastTorchStrengthLevel(const std::string& cameraId,
Rucha Katakwar38284522021-11-10 11:25:21 -0800689 int32_t newStrengthLevel) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000690 // Get the device id and app-visible camera id for the given HAL-visible camera id.
691 auto [deviceId, mappedCameraId] =
692 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
693
Rucha Katakwar38284522021-11-10 11:25:21 -0800694 Mutex::Autolock lock(mStatusListenerLock);
695 for (auto& i : mListenerList) {
Biswarup Pal37a75182024-01-16 15:53:35 +0000696 auto ret = i->getListener()->onTorchStrengthLevelChanged(mappedCameraId,
697 newStrengthLevel, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -0700698 i->handleBinderStatus(ret,
699 "%s: Failed to trigger onTorchStrengthLevelChanged for %d:%d: %d", __FUNCTION__,
700 i->getListenerUid(), i->getListenerPid(), ret.exceptionCode());
Rucha Katakwar38284522021-11-10 11:25:21 -0800701 }
702}
703
Austin Borgered99f642023-06-01 16:51:35 -0700704void CameraService::onTorchStatusChangedLocked(const std::string& cameraId,
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700705 TorchModeStatus newStatus, SystemCameraKind systemCameraKind) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800706 ALOGI("%s: Torch status changed for cameraId=%s, newStatus=%d",
Austin Borgered99f642023-06-01 16:51:35 -0700707 __FUNCTION__, cameraId.c_str(), newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800708
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800709 TorchModeStatus status;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800710 status_t res = getTorchStatusLocked(cameraId, &status);
711 if (res) {
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -0700712 ALOGE("%s: cannot get torch status of camera %s: %s (%d)",
Austin Borgered99f642023-06-01 16:51:35 -0700713 __FUNCTION__, cameraId.c_str(), strerror(-res), res);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800714 return;
715 }
716 if (status == newStatus) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800717 return;
718 }
719
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800720 res = setTorchStatusLocked(cameraId, newStatus);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800721 if (res) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -0800722 ALOGE("%s: Failed to set the torch status to %d: %s (%d)", __FUNCTION__,
723 (uint32_t)newStatus, strerror(-res), res);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800724 return;
725 }
726
Ruben Brunkcc776712015-02-17 20:18:47 -0800727 {
Ruben Brunk99e69712015-05-26 17:25:07 -0700728 // Update battery life logging for flashlight
Chien-Yu Chenfe751be2015-09-01 14:16:44 -0700729 Mutex::Autolock al(mTorchUidMapMutex);
Ruben Brunk99e69712015-05-26 17:25:07 -0700730 auto iter = mTorchUidMap.find(cameraId);
731 if (iter != mTorchUidMap.end()) {
732 int oldUid = iter->second.second;
733 int newUid = iter->second.first;
734 BatteryNotifier& notifier(BatteryNotifier::getInstance());
735 if (oldUid != newUid) {
736 // If the UID has changed, log the status and update current UID in mTorchUidMap
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800737 if (status == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700738 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700739 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800740 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700741 notifier.noteFlashlightOn(toString8(cameraId), newUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700742 }
743 iter->second.second = newUid;
744 } else {
745 // If the UID has not changed, log the status
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -0800746 if (newStatus == TorchModeStatus::AVAILABLE_ON) {
Austin Borgered99f642023-06-01 16:51:35 -0700747 notifier.noteFlashlightOn(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700748 } else {
Austin Borgered99f642023-06-01 16:51:35 -0700749 notifier.noteFlashlightOff(toString8(cameraId), oldUid);
Ruben Brunk99e69712015-05-26 17:25:07 -0700750 }
751 }
752 }
753 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -0700754 broadcastTorchModeStatus(cameraId, newStatus, systemCameraKind);
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800755}
756
Austin Borger249e6592024-03-10 22:28:11 -0700757bool CameraService::isAutomotiveExteriorSystemCamera(const std::string& cam_id) const {
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700758 // Returns false if this is not an automotive device type.
759 if (!isAutomotiveDevice())
760 return false;
761
762 // Returns false if no camera id is provided.
Austin Borger1c1bee02023-06-01 16:51:35 -0700763 if (cam_id.empty())
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700764 return false;
765
766 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
767 if (getSystemCameraKind(cam_id, &systemCameraKind) != OK) {
768 // This isn't a known camera ID, so it's not a system camera.
769 ALOGE("%s: Unknown camera id %s, ", __FUNCTION__, cam_id.c_str());
770 return false;
771 }
772
773 if (systemCameraKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) {
774 ALOGE("%s: camera id %s is not a system camera", __FUNCTION__, cam_id.c_str());
775 return false;
776 }
777
778 CameraMetadata cameraInfo;
779 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borger1c1bee02023-06-01 16:51:35 -0700780 cam_id, false, &cameraInfo, false);
Jyoti Bhayanafeb73922023-03-16 13:01:38 -0700781 if (res != OK){
782 ALOGE("%s: Not able to get camera characteristics for camera id %s",__FUNCTION__,
783 cam_id.c_str());
784 return false;
785 }
786
787 camera_metadata_entry auto_location = cameraInfo.find(ANDROID_AUTOMOTIVE_LOCATION);
788 if (auto_location.count != 1)
789 return false;
790
791 uint8_t location = auto_location.data.u8[0];
792 if ((location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_FRONT) &&
793 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_REAR) &&
794 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_LEFT) &&
795 (location != ANDROID_AUTOMOTIVE_LOCATION_EXTERIOR_RIGHT)) {
796 return false;
797 }
798
799 return true;
800}
801
Biswarup Pal37a75182024-01-16 15:53:35 +0000802Status CameraService::getNumberOfCameras(int32_t type, int32_t deviceId, int32_t devicePolicy,
803 int32_t* numCameras) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -0700804 ATRACE_CALL();
Biswarup Pal37a75182024-01-16 15:53:35 +0000805 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
806 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
807 *numCameras = mVirtualDeviceCameraIdMapper.getNumberOfCameras(deviceId);
808 return Status::ok();
809 }
810
Emilian Peevaee727d2017-05-04 16:35:48 +0100811 Mutex::Autolock l(mServiceLock);
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700812 bool hasSystemCameraPermissions =
Austin Borger22c5c852024-03-08 13:31:36 -0800813 hasPermissionsForSystemCamera(std::string(), getCallingPid(),
814 getCallingUid());
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700815 switch (type) {
816 case CAMERA_TYPE_BACKWARD_COMPATIBLE:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700817 if (hasSystemCameraPermissions) {
818 *numCameras = static_cast<int>(mNormalDeviceIds.size());
819 } else {
820 *numCameras = static_cast<int>(mNormalDeviceIdsWithoutSystemCamera.size());
821 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800822 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700823 case CAMERA_TYPE_ALL:
Jayant Chowdhary847947d2019-08-30 18:02:59 -0700824 if (hasSystemCameraPermissions) {
825 *numCameras = mNumberOfCameras;
826 } else {
827 *numCameras = mNumberOfCamerasWithoutSystemCamera;
828 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800829 break;
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700830 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800831 ALOGW("%s: Unknown camera type %d",
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700832 __FUNCTION__, type);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800833 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
834 "Unknown camera type %d", type);
Eino-Ville Talvalabad43582015-08-14 13:12:32 -0700835 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800836 return Status::ok();
Mathias Agopian65ab4712010-07-14 17:59:35 -0700837}
838
malikakash73125c62023-07-21 22:44:34 +0000839Status CameraService::remapCameraIds(const hardware::CameraIdRemapping& cameraIdRemapping) {
Austin Borgered99f642023-06-01 16:51:35 -0700840 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -0800841 const int pid = getCallingPid();
842 const int uid = getCallingUid();
malikakash82ed4352023-07-21 22:44:34 +0000843 ALOGE("%s: Permission Denial: can't configure camera ID mapping pid=%d, uid=%d",
844 __FUNCTION__, pid, uid);
845 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
846 "Permission Denial: no permission to configure camera id mapping");
847 }
848 TCameraIdRemapping cameraIdRemappingMap{};
malikakash214f6e62023-08-10 23:50:56 +0000849 binder::Status parseStatus = parseCameraIdRemapping(cameraIdRemapping, &cameraIdRemappingMap);
malikakash82ed4352023-07-21 22:44:34 +0000850 if (!parseStatus.isOk()) {
851 return parseStatus;
852 }
853 remapCameraIds(cameraIdRemappingMap);
854 return Status::ok();
855}
856
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700857Status CameraService::createDefaultRequest(const std::string& unresolvedCameraId, int templateId,
Biswarup Pal37a75182024-01-16 15:53:35 +0000858 int32_t deviceId, int32_t devicePolicy,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700859 /* out */
860 hardware::camera2::impl::CameraMetadataNative* request) {
861 ATRACE_CALL();
862
863 if (!flags::feature_combination_query()) {
864 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
865 "Camera subsystem doesn't support this method!");
866 }
867 if (!mInitialized) {
868 ALOGE("%s: Camera subsystem is not available", __FUNCTION__);
869 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
870 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
871 }
872
Biswarup Pal37a75182024-01-16 15:53:35 +0000873 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
874 devicePolicy, getCallingUid());
875 if (!cameraIdOptional.has_value()) {
876 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
877 unresolvedCameraId.c_str(), deviceId);
878 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
879 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
880 }
881 std::string cameraId = cameraIdOptional.value();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700882
883 binder::Status res;
884 if (request == nullptr) {
885 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
886 "Camera %s: Error creating default request", cameraId.c_str());
887 return res;
888 }
889 camera_request_template_t tempId = camera_request_template_t::CAMERA_TEMPLATE_COUNT;
890 res = SessionConfigurationUtils::mapRequestTemplateFromClient(
891 cameraId, templateId, &tempId);
892 if (!res.isOk()) {
893 ALOGE("%s: Camera %s: failed to map request Template %d",
894 __FUNCTION__, cameraId.c_str(), templateId);
895 return res;
896 }
897
898 if (shouldRejectSystemCameraConnection(cameraId)) {
899 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to create default"
900 "request for system only device %s: ", cameraId.c_str());
901 }
902
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700903 CameraMetadata metadata;
904 status_t err = mCameraProviderManager->createDefaultRequest(cameraId, tempId, &metadata);
905 if (err == OK) {
906 request->swap(metadata);
907 } else if (err == BAD_VALUE) {
908 res = STATUS_ERROR_FMT(CameraService::ERROR_ILLEGAL_ARGUMENT,
909 "Camera %s: Template ID %d is invalid or not supported: %s (%d)",
910 cameraId.c_str(), templateId, strerror(-err), err);
911 } else {
912 res = STATUS_ERROR_FMT(CameraService::ERROR_INVALID_OPERATION,
913 "Camera %s: Error creating default request for template %d: %s (%d)",
914 cameraId.c_str(), templateId, strerror(-err), err);
915 }
916 return res;
917}
918
919Status CameraService::isSessionConfigurationWithParametersSupported(
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700920 const std::string& unresolvedCameraId, int targetSdkVersion,
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700921 const SessionConfiguration& sessionConfiguration,
Biswarup Pal37a75182024-01-16 15:53:35 +0000922 int32_t deviceId, int32_t devicePolicy,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700923 /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700924 ATRACE_CALL();
925
926 if (!flags::feature_combination_query()) {
927 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION,
928 "Camera subsystem doesn't support this method!");
929 }
930 if (!mInitialized) {
931 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
932 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
933 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
934 }
935
Biswarup Pal37a75182024-01-16 15:53:35 +0000936 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
937 devicePolicy, getCallingUid());
938 if (!cameraIdOptional.has_value()) {
939 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
940 unresolvedCameraId.c_str(), deviceId);
941 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
942 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
943 }
944 std::string cameraId = cameraIdOptional.value();
945
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700946 if (supported == nullptr) {
947 std::string msg = fmt::sprintf("Camera %s: Invalid 'support' input!",
948 unresolvedCameraId.c_str());
949 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
950 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
951 }
952
953 if (shouldRejectSystemCameraConnection(cameraId)) {
954 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query "
955 "session configuration with parameters support for system only device %s: ",
956 cameraId.c_str());
957 }
958
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700959 bool overrideForPerfClass = flags::calculate_perf_override_during_session_support() &&
960 SessionConfigurationUtils::targetPerfClassPrimaryCamera(
961 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
962
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700963 return isSessionConfigurationWithParametersSupportedUnsafe(cameraId, sessionConfiguration,
Avichal Rakeshcaf179b2024-04-04 18:42:46 -0700964 overrideForPerfClass, supported);
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700965}
966
967Status CameraService::isSessionConfigurationWithParametersSupportedUnsafe(
968 const std::string& cameraId, const SessionConfiguration& sessionConfiguration,
969 bool overrideForPerfClass, /*out*/ bool* supported) {
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700970 *supported = false;
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700971 status_t ret = mCameraProviderManager->isSessionConfigurationSupported(
972 cameraId, sessionConfiguration, overrideForPerfClass,
973 /*checkSessionParams=*/true, supported);
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700974 binder::Status res;
975 switch (ret) {
976 case OK:
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700977 // Expected. Do Nothing.
978 return Status::ok();
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700979 case INVALID_OPERATION: {
980 std::string msg = fmt::sprintf(
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700981 "Camera %s: Session configuration with parameters supported query not "
982 "supported!",
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700983 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700984 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
985 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
986 *supported = false;
987 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700988 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700989 break;
990 case NAME_NOT_FOUND: {
991 std::string msg = fmt::sprintf("Camera %s: Unknown camera ID.", cameraId.c_str());
992 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
993 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
994 *supported = false;
995 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
996 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -0700997 break;
998 default: {
Avichal Rakesh8fbda412024-04-04 17:16:33 -0700999 std::string msg = fmt::sprintf(
1000 "Unable to retrieve session configuration support for camera "
1001 "device %s: Error: %s (%d)",
1002 cameraId.c_str(), strerror(-ret), ret);
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001003 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001004 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1005 *supported = false;
1006 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001007 }
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001008 break;
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001009 }
Shuzhen Wang045be6c2023-10-12 10:01:10 -07001010}
1011
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001012Status CameraService::getSessionCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001013 int targetSdkVersion, bool overrideToPortrait,
1014 const SessionConfiguration& sessionConfiguration, int32_t deviceId, int32_t devicePolicy,
1015 /*out*/ CameraMetadata* outMetadata) {
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001016 ATRACE_CALL();
1017
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001018 if (outMetadata == nullptr) {
1019 std::string msg =
1020 fmt::sprintf("Camera %s: Invalid 'outMetadata' input!", unresolvedCameraId.c_str());
1021 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1022 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1023 }
1024
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001025 if (!mInitialized) {
1026 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1027 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
1028 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem is not available");
1029 }
1030
Biswarup Pal37a75182024-01-16 15:53:35 +00001031 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001032 devicePolicy, getCallingUid());
Biswarup Pal37a75182024-01-16 15:53:35 +00001033 if (!cameraIdOptional.has_value()) {
1034 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001035 unresolvedCameraId.c_str(), deviceId);
Biswarup Pal37a75182024-01-16 15:53:35 +00001036 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1037 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1038 }
1039 std::string cameraId = cameraIdOptional.value();
1040
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001041 if (shouldRejectSystemCameraConnection(cameraId)) {
1042 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1043 "Unable to retrieve camera"
1044 "characteristics for system only device %s: ",
1045 cameraId.c_str());
1046 }
1047
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001048 bool overrideForPerfClass = SessionConfigurationUtils::targetPerfClassPrimaryCamera(
1049 mPerfClassPrimaryCameraIds, cameraId, targetSdkVersion);
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001050 if (flags::check_session_support_before_session_char()) {
1051 bool sessionConfigSupported;
1052 Status res = isSessionConfigurationWithParametersSupportedUnsafe(
1053 cameraId, sessionConfiguration, overrideForPerfClass, &sessionConfigSupported);
1054 if (!res.isOk()) {
1055 // isSessionConfigurationWithParametersSupportedUnsafe should log what went wrong and
1056 // report the correct Status to send to the client. Simply forward the error to
1057 // the client.
1058 outMetadata->clear();
1059 return res;
1060 }
1061 if (!sessionConfigSupported) {
1062 std::string msg = fmt::sprintf(
1063 "Session configuration not supported for camera device %s.", cameraId.c_str());
1064 outMetadata->clear();
1065 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1066 }
1067 }
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001068
1069 status_t ret = mCameraProviderManager->getSessionCharacteristics(
1070 cameraId, sessionConfiguration, overrideForPerfClass, overrideToPortrait, outMetadata);
1071
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001072 switch (ret) {
1073 case OK:
1074 // Expected, no handling needed.
1075 break;
1076 case INVALID_OPERATION: {
1077 std::string msg = fmt::sprintf(
1078 "Camera %s: Session characteristics query not supported!",
1079 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001080 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001081 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1082 outMetadata->clear();
1083 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
1084 }
1085 break;
1086 case NAME_NOT_FOUND: {
1087 std::string msg = fmt::sprintf(
1088 "Camera %s: Unknown camera ID.",
1089 cameraId.c_str());
Avichal Rakesh8fbda412024-04-04 17:16:33 -07001090 ALOGW("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001091 logServiceError(msg, CameraService::ERROR_ILLEGAL_ARGUMENT);
1092 outMetadata->clear();
1093 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001094 }
1095 break;
1096 default: {
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001097 std::string msg = fmt::sprintf(
1098 "Unable to retrieve session characteristics for camera device %s: "
1099 "Error: %s (%d)",
1100 cameraId.c_str(), strerror(-ret), ret);
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001101 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001102 logServiceError(msg, CameraService::ERROR_INVALID_OPERATION);
1103 outMetadata->clear();
1104 return STATUS_ERROR(CameraService::ERROR_INVALID_OPERATION, msg.c_str());
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001105 }
1106 }
1107
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001108 return filterSensitiveMetadataIfNeeded(cameraId, outMetadata);
1109}
1110
1111Status CameraService::filterSensitiveMetadataIfNeeded(
1112 const std::string& cameraId, CameraMetadata* metadata) {
1113 int callingPid = getCallingPid();
1114 int callingUid = getCallingUid();
1115
1116 if (callingPid == getpid()) {
1117 // Caller is cameraserver; no need to remove keys
1118 return Status::ok();
1119 }
1120
1121 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1122 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
1123 ALOGE("%s: Couldn't get camera kind for camera id %s", __FUNCTION__, cameraId.c_str());
1124 metadata->clear();
1125 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1126 "Unable to retrieve camera kind for device %s", cameraId.c_str());
1127 }
1128 if (deviceKind == SystemCameraKind::SYSTEM_ONLY_CAMERA) {
1129 // Attempting to query system only camera without system camera permission would have
1130 // failed the shouldRejectSystemCameraConnection in the caller. So if we get here
1131 // for a system only camera, then the caller has the required permission.
1132 // No need to remove keys
1133 return Status::ok();
1134 }
1135
1136 std::vector<int32_t> tagsRemoved;
Biswarup Pale506e732024-03-27 13:46:20 +00001137 // Get the device id that owns this camera.
1138 auto [cameraOwnerDeviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1139 cameraId);
1140 bool hasCameraPermission = hasPermissionsForCamera(cameraId, callingPid, callingUid,
1141 cameraOwnerDeviceId);
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001142 if (hasCameraPermission) {
1143 // Caller has camera permission; no need to remove keys
1144 return Status::ok();
1145 }
1146
1147 status_t ret = metadata->removePermissionEntries(
1148 mCameraProviderManager->getProviderTagIdLocked(cameraId), &tagsRemoved);
1149 if (ret != OK) {
1150 metadata->clear();
1151 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1152 "Failed to remove camera characteristics needing camera permission "
1153 "for device %s:%s (%d)",
1154 cameraId.c_str(), strerror(-ret), ret);
1155 }
1156
1157 if (!tagsRemoved.empty()) {
1158 ret = metadata->update(ANDROID_REQUEST_CHARACTERISTIC_KEYS_NEEDING_PERMISSION,
1159 tagsRemoved.data(), tagsRemoved.size());
1160 if (ret != OK) {
1161 metadata->clear();
1162 return STATUS_ERROR_FMT(
1163 ERROR_INVALID_OPERATION,
1164 "Failed to insert camera keys needing permission for device %s: %s (%d)",
1165 cameraId.c_str(), strerror(-ret), ret);
1166 }
1167 }
1168 return Status::ok();
Avichal Rakesh3c522e22024-02-07 16:40:46 -08001169}
1170
malikakash82ed4352023-07-21 22:44:34 +00001171Status CameraService::parseCameraIdRemapping(
1172 const hardware::CameraIdRemapping& cameraIdRemapping,
malikakash214f6e62023-08-10 23:50:56 +00001173 /* out */ TCameraIdRemapping* cameraIdRemappingMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001174 std::string packageName;
1175 std::string cameraIdToReplace, updatedCameraId;
Biswarup Pal37a75182024-01-16 15:53:35 +00001176 for (const auto& packageIdRemapping: cameraIdRemapping.packageIdRemappings) {
malikakash82ed4352023-07-21 22:44:34 +00001177 packageName = packageIdRemapping.packageName;
malikakash0894f5b2023-08-10 22:46:47 +00001178 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001179 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1180 "CameraIdRemapping: Package name cannot be empty");
1181 }
malikakash214f6e62023-08-10 23:50:56 +00001182 if (packageIdRemapping.cameraIdsToReplace.size()
1183 != packageIdRemapping.updatedCameraIds.size()) {
malikakash82ed4352023-07-21 22:44:34 +00001184 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1185 "CameraIdRemapping: Mismatch in CameraId Remapping lists sizes for package %s",
malikakash73125c62023-07-21 22:44:34 +00001186 packageName.c_str());
malikakash82ed4352023-07-21 22:44:34 +00001187 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001188 for (size_t i = 0; i < packageIdRemapping.cameraIdsToReplace.size(); i++) {
Austin Borgered99f642023-06-01 16:51:35 -07001189 cameraIdToReplace = packageIdRemapping.cameraIdsToReplace[i];
1190 updatedCameraId = packageIdRemapping.updatedCameraIds[i];
malikakash0894f5b2023-08-10 22:46:47 +00001191 if (cameraIdToReplace.empty() || updatedCameraId.empty()) {
malikakash214f6e62023-08-10 23:50:56 +00001192 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1193 "CameraIdRemapping: Camera Id cannot be empty for package %s",
Austin Borgered99f642023-06-01 16:51:35 -07001194 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001195 }
1196 if (cameraIdToReplace == updatedCameraId) {
1197 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
1198 "CameraIdRemapping: CameraIdToReplace cannot be the same"
1199 " as updatedCameraId for %s",
Austin Borgered99f642023-06-01 16:51:35 -07001200 packageName.c_str());
malikakash214f6e62023-08-10 23:50:56 +00001201 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001202
1203 // Do not allow any camera remapping that involves a virtual camera.
1204 auto [deviceIdForCameraToReplace, _] =
1205 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(
1206 cameraIdToReplace);
1207 if (deviceIdForCameraToReplace != kDefaultDeviceId) {
1208 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1209 "CameraIdRemapping: CameraIdToReplace cannot be a virtual camera");
1210 }
1211 [[maybe_unused]] auto [deviceIdForUpdatedCamera, unusedMappedCameraId] =
1212 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(updatedCameraId);
1213 if (deviceIdForUpdatedCamera != kDefaultDeviceId) {
1214 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1215 "CameraIdRemapping: UpdatedCameraId cannot be a virtual camera");
1216 }
1217
malikakash214f6e62023-08-10 23:50:56 +00001218 (*cameraIdRemappingMap)[packageName][cameraIdToReplace] = updatedCameraId;
malikakash82ed4352023-07-21 22:44:34 +00001219 }
1220 }
1221 return Status::ok();
1222}
1223
1224void CameraService::remapCameraIds(const TCameraIdRemapping& cameraIdRemapping) {
1225 // Acquire mServiceLock and prevent other clients from connecting
1226 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1227 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1228
malikakashedb38962023-09-06 00:03:35 +00001229 // Collect all existing clients for camera Ids that are being
1230 // remapped in the new cameraIdRemapping, but only if they were being used by a
1231 // targeted packageName.
malikakash82ed4352023-07-21 22:44:34 +00001232 std::vector<sp<BasicClient>> clientsToDisconnect;
Austin Borgered99f642023-06-01 16:51:35 -07001233 std::vector<std::string> cameraIdsToUpdate;
malikakash82ed4352023-07-21 22:44:34 +00001234 for (const auto& [packageName, injectionMap] : cameraIdRemapping) {
1235 for (auto& [id0, id1] : injectionMap) {
Austin Borgered99f642023-06-01 16:51:35 -07001236 ALOGI("%s: UPDATE:= %s: %s: %s", __FUNCTION__, packageName.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001237 id0.c_str(), id1.c_str());
1238 auto clientDescriptor = mActiveClientManager.get(id0);
1239 if (clientDescriptor != nullptr) {
1240 sp<BasicClient> clientSp = clientDescriptor->getValue();
1241 if (clientSp->getPackageName() == packageName) {
malikakashedb38962023-09-06 00:03:35 +00001242 // This camera is being used by a targeted packageName and
1243 // being remapped to a new camera Id. We should disconnect it.
malikakash82ed4352023-07-21 22:44:34 +00001244 clientsToDisconnect.push_back(clientSp);
1245 cameraIdsToUpdate.push_back(id0);
1246 }
1247 }
1248 }
1249 }
1250
malikakashedb38962023-09-06 00:03:35 +00001251 for (auto& clientSp : clientsToDisconnect) {
malikakashf4c80f22023-09-25 21:50:28 +00001252 // Notify the clients about the disconnection.
1253 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
malikakashedb38962023-09-06 00:03:35 +00001254 CaptureResultExtras{});
1255 }
malikakash82ed4352023-07-21 22:44:34 +00001256
1257 // Do not hold mServiceLock while disconnecting clients, but retain the condition
1258 // blocking other clients from connecting in mServiceLockWrapper if held.
1259 mServiceLock.unlock();
1260
malikakashedb38962023-09-06 00:03:35 +00001261 // Clear calling identity for disconnect() PID checks.
Austin Borger22c5c852024-03-08 13:31:36 -08001262 int64_t token = clearCallingIdentity();
malikakashedb38962023-09-06 00:03:35 +00001263
malikakash82ed4352023-07-21 22:44:34 +00001264 // Disconnect clients.
1265 for (auto& clientSp : clientsToDisconnect) {
malikakashedb38962023-09-06 00:03:35 +00001266 // This also triggers a call to updateStatus() which also reads mCameraIdRemapping
1267 // and requires mCameraIdRemappingLock.
malikakash82ed4352023-07-21 22:44:34 +00001268 clientSp->disconnect();
1269 }
1270
malikakashedb38962023-09-06 00:03:35 +00001271 // Invoke destructors (which call disconnect()) now while we don't hold the mServiceLock.
1272 clientsToDisconnect.clear();
1273
Austin Borger22c5c852024-03-08 13:31:36 -08001274 restoreCallingIdentity(token);
malikakash82ed4352023-07-21 22:44:34 +00001275 mServiceLock.lock();
malikakashedb38962023-09-06 00:03:35 +00001276
1277 {
1278 Mutex::Autolock lock(mCameraIdRemappingLock);
1279 // Update mCameraIdRemapping.
1280 mCameraIdRemapping.clear();
1281 mCameraIdRemapping.insert(cameraIdRemapping.begin(), cameraIdRemapping.end());
1282 }
malikakash82ed4352023-07-21 22:44:34 +00001283}
1284
malikakash22af94c2023-12-04 18:13:14 +00001285Status CameraService::injectSessionParams(
Biswarup Pal37a75182024-01-16 15:53:35 +00001286 const std::string& cameraId,
1287 const CameraMetadata& sessionParams) {
1288 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08001289 const int pid = getCallingPid();
1290 const int uid = getCallingUid();
malikakash22af94c2023-12-04 18:13:14 +00001291 ALOGE("%s: Permission Denial: can't inject session params pid=%d, uid=%d",
1292 __FUNCTION__, pid, uid);
1293 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
1294 "Permission Denial: no permission to inject session params");
1295 }
1296
Biswarup Pal37a75182024-01-16 15:53:35 +00001297 // Do not allow session params injection for a virtual camera.
1298 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1299 if (deviceId != kDefaultDeviceId) {
1300 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1301 "Cannot inject session params for a virtual camera");
1302 }
1303
malikakash22af94c2023-12-04 18:13:14 +00001304 std::unique_ptr<AutoConditionLock> serviceLockWrapper =
1305 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
1306
1307 auto clientDescriptor = mActiveClientManager.get(cameraId);
1308 if (clientDescriptor == nullptr) {
1309 ALOGI("%s: No active client for camera id %s", __FUNCTION__, cameraId.c_str());
1310 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1311 "No active client for camera id %s", cameraId.c_str());
1312 }
1313
1314 sp<BasicClient> clientSp = clientDescriptor->getValue();
1315 status_t res = clientSp->injectSessionParams(sessionParams);
1316
1317 if (res != OK) {
1318 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1319 "Error injecting session params into camera \"%s\": %s (%d)",
1320 cameraId.c_str(), strerror(-res), res);
1321 }
1322 return Status::ok();
1323}
1324
Austin Borgered99f642023-06-01 16:51:35 -07001325std::vector<std::string> CameraService::findOriginalIdsForRemappedCameraId(
1326 const std::string& inputCameraId, int clientUid) {
1327 std::string packageName = getPackageNameFromUid(clientUid);
1328 std::vector<std::string> cameraIds;
malikakash82ed4352023-07-21 22:44:34 +00001329 Mutex::Autolock lock(mCameraIdRemappingLock);
1330 if (auto packageMapIter = mCameraIdRemapping.find(packageName);
1331 packageMapIter != mCameraIdRemapping.end()) {
1332 for (auto& [id0, id1]: packageMapIter->second) {
1333 if (id1 == inputCameraId) {
1334 cameraIds.push_back(id0);
1335 }
1336 }
1337 }
1338 return cameraIds;
1339}
1340
Austin Borgered99f642023-06-01 16:51:35 -07001341std::string CameraService::resolveCameraId(
1342 const std::string& inputCameraId,
malikakashedb38962023-09-06 00:03:35 +00001343 int clientUid,
Austin Borgered99f642023-06-01 16:51:35 -07001344 const std::string& packageName) {
1345 std::string packageNameVal = packageName;
malikakashedb38962023-09-06 00:03:35 +00001346 if (packageName.empty()) {
malikakash82ed4352023-07-21 22:44:34 +00001347 packageNameVal = getPackageNameFromUid(clientUid);
1348 }
malikakash65d20692023-09-07 01:06:33 +00001349 if (clientUid < AID_APP_START || packageNameVal.empty()) {
malikakashedb38962023-09-06 00:03:35 +00001350 // We shouldn't remap cameras for processes with system/vendor UIDs.
1351 return inputCameraId;
1352 }
malikakash82ed4352023-07-21 22:44:34 +00001353 Mutex::Autolock lock(mCameraIdRemappingLock);
1354 if (auto packageMapIter = mCameraIdRemapping.find(packageNameVal);
1355 packageMapIter != mCameraIdRemapping.end()) {
malikakash82ed4352023-07-21 22:44:34 +00001356 auto packageMap = packageMapIter->second;
1357 if (auto replacementIdIter = packageMap.find(inputCameraId);
1358 replacementIdIter != packageMap.end()) {
malikakashedb38962023-09-06 00:03:35 +00001359 ALOGI("%s: resolveCameraId: remapping cameraId %s for %s to %s",
malikakash82ed4352023-07-21 22:44:34 +00001360 __FUNCTION__, inputCameraId.c_str(),
malikakashedb38962023-09-06 00:03:35 +00001361 packageNameVal.c_str(),
malikakash82ed4352023-07-21 22:44:34 +00001362 replacementIdIter->second.c_str());
1363 return replacementIdIter->second;
1364 }
1365 }
1366 return inputCameraId;
1367}
1368
Biswarup Pal37a75182024-01-16 15:53:35 +00001369std::optional<std::string> CameraService::resolveCameraId(
1370 const std::string& inputCameraId,
1371 int32_t deviceId,
1372 int32_t devicePolicy,
1373 int clientUid,
1374 const std::string& packageName) {
1375 if ((deviceId == kDefaultDeviceId)
1376 || (devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1377 auto [storedDeviceId, _] =
1378 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(inputCameraId);
1379 if (storedDeviceId != kDefaultDeviceId) {
1380 // Trying to access a virtual camera from default-policy device context, we should fail.
1381 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1382 inputCameraId.c_str(), deviceId);
1383 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1384 return std::nullopt;
1385 }
1386 return resolveCameraId(inputCameraId, clientUid, packageName);
1387 }
1388
1389 return mVirtualDeviceCameraIdMapper.getActualCameraId(deviceId, inputCameraId);
1390}
1391
1392Status CameraService::getCameraInfo(int cameraId, bool overrideToPortrait, int32_t deviceId,
1393 int32_t devicePolicy, CameraInfo* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001394 ATRACE_CALL();
Emilian Peevaee727d2017-05-04 16:35:48 +01001395 Mutex::Autolock l(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001396 std::string cameraIdStr = cameraIdIntToStrLocked(cameraId, deviceId, devicePolicy);
1397 if (cameraIdStr.empty()) {
1398 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
1399 cameraId, deviceId);
1400 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1401 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1402 }
malikakashedb38962023-09-06 00:03:35 +00001403
Austin Borgered99f642023-06-01 16:51:35 -07001404 if (shouldRejectSystemCameraConnection(cameraIdStr)) {
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001405 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
1406 "characteristics for system only device %s: ", cameraIdStr.c_str());
1407 }
Emilian Peevaee727d2017-05-04 16:35:48 +01001408
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001409 if (!mInitialized) {
Austin Borgered99f642023-06-01 16:51:35 -07001410 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001411 return STATUS_ERROR(ERROR_DISCONNECTED,
1412 "Camera subsystem is not available");
Iliyan Malchev8951a972011-04-14 16:55:59 -07001413 }
Austin Borger1c1bee02023-06-01 16:51:35 -07001414 bool hasSystemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraId),
Austin Borger22c5c852024-03-08 13:31:36 -08001415 getCallingPid(), getCallingUid());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001416 int cameraIdBound = mNumberOfCamerasWithoutSystemCamera;
1417 if (hasSystemCameraPermissions) {
1418 cameraIdBound = mNumberOfCameras;
1419 }
1420 if (cameraId < 0 || cameraId >= cameraIdBound) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001421 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1422 "CameraId is not valid");
Mathias Agopian65ab4712010-07-14 17:59:35 -07001423 }
1424
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001425 Status ret = Status::ok();
Austin Borger18b30a72022-10-27 12:20:29 -07001426 int portraitRotation;
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001427 status_t err = mCameraProviderManager->getCameraInfo(
Austin Borgered99f642023-06-01 16:51:35 -07001428 cameraIdStr, overrideToPortrait, &portraitRotation, cameraInfo);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001429 if (err != OK) {
1430 ret = STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1431 "Error retrieving camera info from device %d: %s (%d)", cameraId,
1432 strerror(-err), err);
Austin Borgered99f642023-06-01 16:51:35 -07001433 logServiceError(std::string("Error retrieving camera info from device ")
1434 + std::to_string(cameraId), ERROR_INVALID_OPERATION);
Ruben Brunkcc776712015-02-17 20:18:47 -08001435 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001436
Ruben Brunkcc776712015-02-17 20:18:47 -08001437 return ret;
1438}
Ruben Brunkb2119af2014-05-09 19:57:56 -07001439
Biswarup Pal37a75182024-01-16 15:53:35 +00001440std::string CameraService::cameraIdIntToStrLocked(int cameraIdInt,
1441 int32_t deviceId, int32_t devicePolicy) {
1442 if (vd_flags::camera_device_awareness() && (deviceId != kDefaultDeviceId)
1443 && (devicePolicy != IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT)) {
1444 std::optional<std::string> cameraIdOptional =
1445 mVirtualDeviceCameraIdMapper.getActualCameraId(cameraIdInt, deviceId);
1446 return cameraIdOptional.has_value() ? cameraIdOptional.value() : std::string{};
1447 }
1448
1449 const std::vector<std::string> *cameraIds = &mNormalDeviceIdsWithoutSystemCamera;
Austin Borger22c5c852024-03-08 13:31:36 -08001450 auto callingPid = getCallingPid();
1451 auto callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07001452 bool systemCameraPermissions = hasPermissionsForSystemCamera(std::to_string(cameraIdInt),
1453 callingPid, callingUid, /* checkCameraPermissions= */ false);
1454 if (systemCameraPermissions || getpid() == callingPid) {
Biswarup Pal37a75182024-01-16 15:53:35 +00001455 cameraIds = &mNormalDeviceIds;
Jayant Chowdhary847947d2019-08-30 18:02:59 -07001456 }
Biswarup Pal37a75182024-01-16 15:53:35 +00001457 if (cameraIdInt < 0 || cameraIdInt >= static_cast<int>(cameraIds->size())) {
1458 ALOGE("%s: input id %d invalid: valid range (0, %zu)",
1459 __FUNCTION__, cameraIdInt, cameraIds->size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001460 return std::string{};
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001461 }
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001462
Biswarup Pal37a75182024-01-16 15:53:35 +00001463 std::string unresolvedCameraId = (*cameraIds)[cameraIdInt];
1464 return resolveCameraId(unresolvedCameraId, getCallingUid());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001465}
1466
Biswarup Pal37a75182024-01-16 15:53:35 +00001467std::string CameraService::cameraIdIntToStr(int cameraIdInt, int32_t deviceId,
1468 int32_t devicePolicy) {
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08001469 Mutex::Autolock lock(mServiceLock);
Biswarup Pal37a75182024-01-16 15:53:35 +00001470 return cameraIdIntToStrLocked(cameraIdInt, deviceId, devicePolicy);
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001471}
1472
Austin Borgered99f642023-06-01 16:51:35 -07001473Status CameraService::getCameraCharacteristics(const std::string& unresolvedCameraId,
Biswarup Pal37a75182024-01-16 15:53:35 +00001474 int targetSdkVersion, bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
1475 CameraMetadata* cameraInfo) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001476 ATRACE_CALL();
Austin Borgered99f642023-06-01 16:51:35 -07001477
Zhijun He2b59be82013-09-25 10:14:30 -07001478 if (!cameraInfo) {
1479 ALOGE("%s: cameraInfo is NULL", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001480 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "cameraInfo is NULL");
Zhijun He2b59be82013-09-25 10:14:30 -07001481 }
1482
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001483 if (!mInitialized) {
1484 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07001485 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001486 return STATUS_ERROR(ERROR_DISCONNECTED,
1487 "Camera subsystem is not available");;
Zhijun He2b59be82013-09-25 10:14:30 -07001488 }
1489
Biswarup Pal37a75182024-01-16 15:53:35 +00001490 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1491 devicePolicy, getCallingUid());
1492 if (!cameraIdOptional.has_value()) {
1493 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1494 unresolvedCameraId.c_str(), deviceId);
1495 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1496 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1497 }
1498 std::string cameraId = cameraIdOptional.value();
1499
Austin Borgered99f642023-06-01 16:51:35 -07001500 if (shouldRejectSystemCameraConnection(cameraId)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001501 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera"
Austin Borgered99f642023-06-01 16:51:35 -07001502 "characteristics for system only device %s: ", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001503 }
1504
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001505 bool overrideForPerfClass =
1506 SessionConfigurationUtils::targetPerfClassPrimaryCamera(mPerfClassPrimaryCameraIds,
Austin Borgered99f642023-06-01 16:51:35 -07001507 cameraId, targetSdkVersion);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001508 status_t res = mCameraProviderManager->getCameraCharacteristics(
Austin Borgered99f642023-06-01 16:51:35 -07001509 cameraId, overrideForPerfClass, cameraInfo, overrideToPortrait);
Emilian Peevf53f66e2017-04-11 14:29:43 +01001510 if (res != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001511 if (res == NAME_NOT_FOUND) {
1512 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001513 "characteristics for unknown device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001514 strerror(-res), res);
1515 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001516 logServiceError(fmt::sprintf("Unable to retrieve camera characteristics for device %s.",
1517 cameraId.c_str()), ERROR_INVALID_OPERATION);
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001518 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve camera "
Austin Borgered99f642023-06-01 16:51:35 -07001519 "characteristics for device %s: %s (%d)", cameraId.c_str(),
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07001520 strerror(-res), res);
1521 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07001522 }
Emilian Peeve20c6372018-08-14 18:45:53 +01001523
Avichal Rakesh4baf7262024-03-20 19:16:04 -07001524 return filterSensitiveMetadataIfNeeded(cameraId, cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -07001525}
1526
Biswarup Pal37a75182024-01-16 15:53:35 +00001527Status CameraService::getTorchStrengthLevel(const std::string& unresolvedCameraId, int32_t deviceId,
1528 int32_t devicePolicy, int32_t* torchStrength) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001529 ATRACE_CALL();
1530 Mutex::Autolock l(mServiceLock);
Austin Borger249e6592024-03-10 22:28:11 -07001531
Biswarup Pal37a75182024-01-16 15:53:35 +00001532 std::optional<std::string> cameraIdOptional = resolveCameraId(unresolvedCameraId, deviceId,
1533 devicePolicy, getCallingUid());
1534 if (!cameraIdOptional.has_value()) {
1535 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
1536 unresolvedCameraId.c_str(), deviceId);
1537 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
1538 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
1539 }
1540 std::string cameraId = cameraIdOptional.value();
1541
Rucha Katakwar38284522021-11-10 11:25:21 -08001542 if (!mInitialized) {
1543 ALOGE("%s: Camera HAL couldn't be initialized.", __FUNCTION__);
1544 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera HAL couldn't be initialized.");
1545 }
1546
Biswarup Pal37a75182024-01-16 15:53:35 +00001547 if (torchStrength == NULL) {
Rucha Katakwar38284522021-11-10 11:25:21 -08001548 ALOGE("%s: strength level must not be null.", __FUNCTION__);
1549 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Strength level should not be null.");
1550 }
1551
Austin Borgered99f642023-06-01 16:51:35 -07001552 status_t res = mCameraProviderManager->getTorchStrengthLevel(cameraId, torchStrength);
Rucha Katakwar38284522021-11-10 11:25:21 -08001553 if (res != OK) {
1554 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to retrieve torch "
Austin Borgered99f642023-06-01 16:51:35 -07001555 "strength level for device %s: %s (%d)", cameraId.c_str(),
Rucha Katakwar38284522021-11-10 11:25:21 -08001556 strerror(-res), res);
1557 }
1558 ALOGI("%s: Torch strength level is: %d", __FUNCTION__, *torchStrength);
1559 return Status::ok();
1560}
1561
Austin Borgered99f642023-06-01 16:51:35 -07001562std::string CameraService::getFormattedCurrentTime() {
Ruben Brunkcc776712015-02-17 20:18:47 -08001563 time_t now = time(nullptr);
1564 char formattedTime[64];
1565 strftime(formattedTime, sizeof(formattedTime), "%m-%d %H:%M:%S", localtime(&now));
Austin Borgered99f642023-06-01 16:51:35 -07001566 return std::string(formattedTime);
Ruben Brunkcc776712015-02-17 20:18:47 -08001567}
1568
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001569Status CameraService::getCameraVendorTagDescriptor(
1570 /*out*/
1571 hardware::camera2::params::VendorTagDescriptor* desc) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001572 ATRACE_CALL();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001573 if (!mInitialized) {
1574 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001575 return STATUS_ERROR(ERROR_DISCONNECTED, "Camera subsystem not available");
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001576 }
Eino-Ville Talvala1e74e242016-03-03 11:24:28 -08001577 sp<VendorTagDescriptor> globalDescriptor = VendorTagDescriptor::getGlobalVendorTagDescriptor();
1578 if (globalDescriptor != nullptr) {
1579 *desc = *(globalDescriptor.get());
1580 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001581 return Status::ok();
Ruben Brunkd1176ef2014-02-21 10:51:38 -08001582}
1583
Emilian Peev71c73a22017-03-21 16:35:51 +00001584Status CameraService::getCameraVendorTagCache(
1585 /*out*/ hardware::camera2::params::VendorTagDescriptorCache* cache) {
1586 ATRACE_CALL();
1587 if (!mInitialized) {
1588 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
1589 return STATUS_ERROR(ERROR_DISCONNECTED,
1590 "Camera subsystem not available");
1591 }
1592 sp<VendorTagDescriptorCache> globalCache =
1593 VendorTagDescriptorCache::getGlobalVendorTagCache();
1594 if (globalCache != nullptr) {
1595 *cache = *(globalCache.get());
1596 }
1597 return Status::ok();
1598}
1599
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07001600void CameraService::clearCachedVariables() {
1601 BasicClient::BasicClient::sCameraService = nullptr;
1602}
1603
Austin Borgered99f642023-06-01 16:51:35 -07001604std::pair<int, IPCTransport> CameraService::getDeviceVersion(const std::string& cameraId,
Austin Borger18b30a72022-10-27 12:20:29 -07001605 bool overrideToPortrait, int* portraitRotation, int* facing, int* orientation) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07001606 ATRACE_CALL();
Igor Murashkin634a5152013-02-20 17:15:11 -08001607
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001608 int deviceVersion = 0;
1609
Emilian Peevf53f66e2017-04-11 14:29:43 +01001610 status_t res;
1611 hardware::hidl_version maxVersion{0,0};
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001612 IPCTransport transport = IPCTransport::INVALID;
Austin Borgered99f642023-06-01 16:51:35 -07001613 res = mCameraProviderManager->getHighestSupportedVersion(cameraId, &maxVersion, &transport);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001614 if (res != OK || transport == IPCTransport::INVALID) {
1615 ALOGE("%s: Unable to get highest supported version for camera id %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07001616 cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001617 return std::make_pair(-1, IPCTransport::INVALID) ;
1618 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001619 deviceVersion = HARDWARE_DEVICE_API_VERSION(maxVersion.get_major(), maxVersion.get_minor());
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001620
Emilian Peevf53f66e2017-04-11 14:29:43 +01001621 hardware::CameraInfo info;
1622 if (facing) {
Austin Borgered99f642023-06-01 16:51:35 -07001623 res = mCameraProviderManager->getCameraInfo(cameraId, overrideToPortrait,
Austin Borger18b30a72022-10-27 12:20:29 -07001624 portraitRotation, &info);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001625 if (res != OK) {
1626 return std::make_pair(-1, IPCTransport::INVALID);
1627 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001628 *facing = info.facing;
Emilian Peevb91f1802021-03-23 14:50:28 -07001629 if (orientation) {
1630 *orientation = info.orientation;
1631 }
Igor Murashkin634a5152013-02-20 17:15:11 -08001632 }
Emilian Peevf53f66e2017-04-11 14:29:43 +01001633
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001634 return std::make_pair(deviceVersion, transport);
Igor Murashkin634a5152013-02-20 17:15:11 -08001635}
1636
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001637Status CameraService::filterGetInfoErrorCode(status_t err) {
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001638 switch(err) {
1639 case NO_ERROR:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001640 return Status::ok();
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001641 case BAD_VALUE:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001642 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT,
1643 "CameraId is not valid for HAL module");
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001644 case NO_INIT:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001645 return STATUS_ERROR(ERROR_DISCONNECTED,
1646 "Camera device not available");
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001647 default:
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001648 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1649 "Camera HAL encountered error %d: %s",
1650 err, strerror(-err));
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07001651 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08001652}
1653
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001654Status CameraService::makeClient(const sp<CameraService>& cameraService,
Austin Borgered99f642023-06-01 16:51:35 -07001655 const sp<IInterface>& cameraCb, const std::string& packageName, bool systemNativeClient,
1656 const std::optional<std::string>& featureId, const std::string& cameraId,
Emilian Peev8b64f282021-03-25 16:49:57 -07001657 int api1CameraId, int facing, int sensorOrientation, int clientPid, uid_t clientUid,
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001658 int servicePid, std::pair<int, IPCTransport> deviceVersionAndTransport,
Austin Borger18b30a72022-10-27 12:20:29 -07001659 apiLevel effectiveApiLevel, bool overrideForPerfClass, bool overrideToPortrait,
malikakash73125c62023-07-21 22:44:34 +00001660 bool forceSlowJpegMode, const std::string& originalCameraId,
1661 /*out*/sp<BasicClient>* client) {
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001662 // For HIDL devices
1663 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
1664 // Create CameraClient based on device version reported by the HAL.
1665 int deviceVersion = deviceVersionAndTransport.first;
1666 switch(deviceVersion) {
1667 case CAMERA_DEVICE_API_VERSION_1_0:
1668 ALOGE("Camera using old HAL version: %d", deviceVersion);
1669 return STATUS_ERROR_FMT(ERROR_DEPRECATED_HAL,
1670 "Camera device \"%s\" HAL version %d no longer supported",
Austin Borgered99f642023-06-01 16:51:35 -07001671 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001672 break;
1673 case CAMERA_DEVICE_API_VERSION_3_0:
1674 case CAMERA_DEVICE_API_VERSION_3_1:
1675 case CAMERA_DEVICE_API_VERSION_3_2:
1676 case CAMERA_DEVICE_API_VERSION_3_3:
1677 case CAMERA_DEVICE_API_VERSION_3_4:
1678 case CAMERA_DEVICE_API_VERSION_3_5:
1679 case CAMERA_DEVICE_API_VERSION_3_6:
1680 case CAMERA_DEVICE_API_VERSION_3_7:
1681 break;
1682 default:
1683 // Should not be reachable
1684 ALOGE("Unknown camera device HAL version: %d", deviceVersion);
1685 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
1686 "Camera device \"%s\" has unknown HAL version %d",
Austin Borgered99f642023-06-01 16:51:35 -07001687 cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001688 }
1689 }
1690 if (effectiveApiLevel == API_1) { // Camera1 API route
1691 sp<ICameraClient> tmp = static_cast<ICameraClient*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001692 *client = new Camera2Client(cameraService, tmp, cameraService->mCameraServiceProxyWrapper,
Austin Borger249e6592024-03-10 22:28:11 -07001693 cameraService->mAttributionAndPermissionUtils, packageName, featureId, cameraId,
Austin Borgered99f642023-06-01 16:51:35 -07001694 api1CameraId, facing, sensorOrientation,
Chengfei Taobe683db2023-01-31 18:52:49 +00001695 clientPid, clientUid, servicePid, overrideForPerfClass, overrideToPortrait,
1696 forceSlowJpegMode);
1697 ALOGI("%s: Camera1 API (legacy), override to portrait %d, forceSlowJpegMode %d",
1698 __FUNCTION__, overrideToPortrait, forceSlowJpegMode);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00001699 } else { // Camera2 API route
1700 sp<hardware::camera2::ICameraDeviceCallbacks> tmp =
1701 static_cast<hardware::camera2::ICameraDeviceCallbacks*>(cameraCb.get());
Austin Borger74fca042022-05-23 12:41:21 -07001702 *client = new CameraDeviceClient(cameraService, tmp,
Austin Borger249e6592024-03-10 22:28:11 -07001703 cameraService->mCameraServiceProxyWrapper,
1704 cameraService->mAttributionAndPermissionUtils, packageName, systemNativeClient,
Austin Borger74fca042022-05-23 12:41:21 -07001705 featureId, cameraId, facing, sensorOrientation, clientPid, clientUid, servicePid,
malikakash82ed4352023-07-21 22:44:34 +00001706 overrideForPerfClass, overrideToPortrait, originalCameraId);
Austin Borger18b30a72022-10-27 12:20:29 -07001707 ALOGI("%s: Camera2 API, override to portrait %d", __FUNCTION__, overrideToPortrait);
Ruben Brunkcc776712015-02-17 20:18:47 -08001708 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001709 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001710}
1711
Austin Borgered99f642023-06-01 16:51:35 -07001712std::string CameraService::toString(std::set<userid_t> intSet) {
1713 std::ostringstream s;
Ruben Brunk6267b532015-04-30 17:44:07 -07001714 bool first = true;
1715 for (userid_t i : intSet) {
1716 if (first) {
Austin Borgered99f642023-06-01 16:51:35 -07001717 s << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001718 first = false;
1719 } else {
Austin Borgered99f642023-06-01 16:51:35 -07001720 s << ", " << std::to_string(i);
Ruben Brunk6267b532015-04-30 17:44:07 -07001721 }
1722 }
Austin Borgered99f642023-06-01 16:51:35 -07001723 return std::move(s.str());
Ruben Brunk6267b532015-04-30 17:44:07 -07001724}
1725
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08001726int32_t CameraService::mapToInterface(TorchModeStatus status) {
1727 int32_t serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1728 switch (status) {
1729 case TorchModeStatus::NOT_AVAILABLE:
1730 serviceStatus = ICameraServiceListener::TORCH_STATUS_NOT_AVAILABLE;
1731 break;
1732 case TorchModeStatus::AVAILABLE_OFF:
1733 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_OFF;
1734 break;
1735 case TorchModeStatus::AVAILABLE_ON:
1736 serviceStatus = ICameraServiceListener::TORCH_STATUS_AVAILABLE_ON;
1737 break;
1738 default:
1739 ALOGW("Unknown new flash status: %d", status);
1740 }
1741 return serviceStatus;
1742}
1743
1744CameraService::StatusInternal CameraService::mapToInternal(CameraDeviceStatus status) {
1745 StatusInternal serviceStatus = StatusInternal::NOT_PRESENT;
1746 switch (status) {
1747 case CameraDeviceStatus::NOT_PRESENT:
1748 serviceStatus = StatusInternal::NOT_PRESENT;
1749 break;
1750 case CameraDeviceStatus::PRESENT:
1751 serviceStatus = StatusInternal::PRESENT;
1752 break;
1753 case CameraDeviceStatus::ENUMERATING:
1754 serviceStatus = StatusInternal::ENUMERATING;
1755 break;
1756 default:
1757 ALOGW("Unknown new HAL device status: %d", status);
1758 }
1759 return serviceStatus;
1760}
1761
1762int32_t CameraService::mapToInterface(StatusInternal status) {
1763 int32_t serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1764 switch (status) {
1765 case StatusInternal::NOT_PRESENT:
1766 serviceStatus = ICameraServiceListener::STATUS_NOT_PRESENT;
1767 break;
1768 case StatusInternal::PRESENT:
1769 serviceStatus = ICameraServiceListener::STATUS_PRESENT;
1770 break;
1771 case StatusInternal::ENUMERATING:
1772 serviceStatus = ICameraServiceListener::STATUS_ENUMERATING;
1773 break;
1774 case StatusInternal::NOT_AVAILABLE:
1775 serviceStatus = ICameraServiceListener::STATUS_NOT_AVAILABLE;
1776 break;
1777 case StatusInternal::UNKNOWN:
1778 serviceStatus = ICameraServiceListener::STATUS_UNKNOWN;
1779 break;
1780 default:
1781 ALOGW("Unknown new internal device status: %d", status);
1782 }
1783 return serviceStatus;
1784}
1785
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001786Status CameraService::initializeShimMetadata(int cameraId) {
Austin Borger22c5c852024-03-08 13:31:36 -08001787 int uid = getCallingUid();
Ruben Brunkb2119af2014-05-09 19:57:56 -07001788
Austin Borgered99f642023-06-01 16:51:35 -07001789 std::string cameraIdStr = std::to_string(cameraId);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001790 Status ret = Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08001791 sp<Client> tmp = nullptr;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001792 if (!(ret = connectHelper<ICameraClient,Client>(
Austin Borgered99f642023-06-01 16:51:35 -07001793 sp<ICameraClient>{nullptr}, cameraIdStr, cameraId,
1794 kServiceName, /*systemNativeClient*/ false, {}, uid, USE_CALLING_PID,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07001795 API_1, /*shimUpdateOnly*/ true, /*oomScoreOffset*/ 0,
Chengfei Taobe683db2023-01-31 18:52:49 +00001796 /*targetSdkVersion*/ __ANDROID_API_FUTURE__, /*overrideToPortrait*/ true,
Austin Borgered99f642023-06-01 16:51:35 -07001797 /*forceSlowJpegMode*/false, cameraIdStr, /*out*/ tmp)
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001798 ).isOk()) {
Tomasz Wasilczyk12b04a52023-08-11 15:52:22 +00001799 ALOGE("%s: Error initializing shim metadata: %s", __FUNCTION__, ret.toString8().c_str());
Ruben Brunkb2119af2014-05-09 19:57:56 -07001800 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001801 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07001802}
1803
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001804Status CameraService::getLegacyParametersLazy(int cameraId,
Igor Murashkin65d14b92014-06-17 12:03:20 -07001805 /*out*/
1806 CameraParameters* parameters) {
1807
1808 ALOGV("%s: for cameraId: %d", __FUNCTION__, cameraId);
1809
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001810 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07001811
1812 if (parameters == NULL) {
1813 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001814 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001815 }
1816
malikakashedb38962023-09-06 00:03:35 +00001817 std::string unresolvedCameraId = std::to_string(cameraId);
1818 std::string cameraIdStr = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08001819 getCallingUid());
Ruben Brunkcc776712015-02-17 20:18:47 -08001820
1821 // Check if we already have parameters
1822 {
1823 // Scope for service lock
Igor Murashkin65d14b92014-06-17 12:03:20 -07001824 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001825 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001826 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001827 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001828 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001829 "Invalid camera ID: %s", cameraIdStr.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08001830 }
1831 CameraParameters p = cameraState->getShimParams();
1832 if (!p.isEmpty()) {
1833 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001834 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001835 }
1836 }
1837
Austin Borger22c5c852024-03-08 13:31:36 -08001838 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08001839 ret = initializeShimMetadata(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08001840 restoreCallingIdentity(token);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001841 if (!ret.isOk()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001842 // Error already logged by callee
1843 return ret;
1844 }
1845
1846 // Check for parameters again
1847 {
1848 // Scope for service lock
1849 Mutex::Autolock lock(mServiceLock);
Austin Borgered99f642023-06-01 16:51:35 -07001850 auto cameraState = getCameraState(cameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08001851 if (cameraState == nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07001852 ALOGE("%s: Invalid camera ID: %s", __FUNCTION__, cameraIdStr.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001853 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
Austin Borgered99f642023-06-01 16:51:35 -07001854 "Invalid camera ID: %s", cameraIdStr.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07001855 }
Ruben Brunkcc776712015-02-17 20:18:47 -08001856 CameraParameters p = cameraState->getShimParams();
1857 if (!p.isEmpty()) {
1858 *parameters = p;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001859 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07001860 }
1861 }
1862
Ruben Brunkcc776712015-02-17 20:18:47 -08001863 ALOGE("%s: Parameters were not initialized, or were empty. Device may not be present.",
1864 __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001865 return STATUS_ERROR(ERROR_INVALID_OPERATION, "Unable to initialize legacy parameters");
Igor Murashkin65d14b92014-06-17 12:03:20 -07001866}
1867
Austin Borgered99f642023-06-01 16:51:35 -07001868Status CameraService::validateConnectLocked(const std::string& cameraId,
1869 const std::string& clientName8, /*inout*/int& clientUid, /*inout*/int& clientPid,
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07001870 /*out*/int& originalClientPid) const {
Tyler Luu5861a9a2011-10-06 00:00:03 -05001871
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001872#ifdef __BRILLO__
1873 UNUSED(clientName8);
1874 UNUSED(clientUid);
1875 UNUSED(clientPid);
1876 UNUSED(originalClientPid);
1877#else
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001878 Status allowed = validateClientPermissionsLocked(cameraId, clientName8, clientUid, clientPid,
1879 originalClientPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001880 if (!allowed.isOk()) {
Christopher Wileyce761d12016-02-16 10:15:00 -08001881 return allowed;
1882 }
Alex Deymo9c2a2c22016-08-25 11:59:14 -07001883#endif // __BRILLO__
Christopher Wileyce761d12016-02-16 10:15:00 -08001884
Austin Borger22c5c852024-03-08 13:31:36 -08001885 int callingPid = getCallingPid();
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001886
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08001887 if (!mInitialized) {
Ruben Brunkcc776712015-02-17 20:18:47 -08001888 ALOGE("CameraService::connect X (PID %d) rejected (camera HAL module not loaded)",
1889 callingPid);
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001890 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001891 "No camera HAL module available to open camera device \"%s\"", cameraId.c_str());
Iliyan Malchev8951a972011-04-14 16:55:59 -07001892 }
1893
Ruben Brunkcc776712015-02-17 20:18:47 -08001894 if (getCameraState(cameraId) == nullptr) {
1895 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07001896 cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001897 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001898 "No camera device with ID \"%s\" available", cameraId.c_str());
Mathias Agopian65ab4712010-07-14 17:59:35 -07001899 }
1900
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001901 status_t err = checkIfDeviceIsUsable(cameraId);
1902 if (err != NO_ERROR) {
1903 switch(err) {
1904 case -ENODEV:
1905 case -EBUSY:
1906 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
Austin Borgered99f642023-06-01 16:51:35 -07001907 "No camera device with ID \"%s\" currently available", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001908 default:
1909 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
Austin Borgered99f642023-06-01 16:51:35 -07001910 "Unknown error connecting to ID \"%s\"", cameraId.c_str());
Eino-Ville Talvala04926862016-03-02 15:42:53 -08001911 }
1912 }
1913 return Status::ok();
Christopher Wiley0039bcf2016-02-05 10:29:50 -08001914}
1915
Austin Borgered99f642023-06-01 16:51:35 -07001916Status CameraService::validateClientPermissionsLocked(const std::string& cameraId,
1917 const std::string& clientName, int& clientUid, int& clientPid,
Chien-Yu Chen7939aee2016-03-21 18:19:33 -07001918 /*out*/int& originalClientPid) const {
Austin Borger22c5c852024-03-08 13:31:36 -08001919 int callingPid = getCallingPid();
1920 int callingUid = getCallingUid();
Mathias Agopian65ab4712010-07-14 17:59:35 -07001921
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001922 // Check if we can trust clientUid
Mathias Agopian65ab4712010-07-14 17:59:35 -07001923 if (clientUid == USE_CALLING_UID) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001924 clientUid = callingUid;
1925 } else if (!isTrustedCallingUid(callingUid)) {
1926 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1927 "(don't trust clientUid %d)", callingPid, callingUid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001928 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1929 "Untrusted caller (calling PID %d, UID %d) trying to "
1930 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001931 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001932 clientName.c_str(), clientPid, clientUid);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001933 }
1934
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001935 // Check if we can trust clientPid
1936 if (clientPid == USE_CALLING_PID) {
1937 clientPid = callingPid;
1938 } else if (!isTrustedCallingUid(callingUid)) {
1939 ALOGE("CameraService::connect X (calling PID %d, calling UID %d) rejected "
1940 "(don't trust clientPid %d)", callingPid, callingUid, clientPid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001941 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1942 "Untrusted caller (calling PID %d, UID %d) trying to "
1943 "forward camera access to camera %s for client %s (PID %d, UID %d)",
Austin Borgered99f642023-06-01 16:51:35 -07001944 callingPid, callingUid, cameraId.c_str(),
Austin Borger249e6592024-03-10 22:28:11 -07001945 clientName.c_str(), clientPid, clientUid);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001946 }
1947
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001948 if (shouldRejectSystemCameraConnection(cameraId)) {
1949 ALOGW("Attempting to connect to system-only camera id %s, connection rejected",
1950 cameraId.c_str());
1951 return STATUS_ERROR_FMT(ERROR_DISCONNECTED, "No camera device with ID \"%s\" is"
Austin Borgered99f642023-06-01 16:51:35 -07001952 "available", cameraId.c_str());
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001953 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001954 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
1955 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07001956 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001957 return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT, "No camera device with ID \"%s\""
Austin Borgered99f642023-06-01 16:51:35 -07001958 "found while trying to query device kind", cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07001959 }
1960
Biswarup Pale506e732024-03-27 13:46:20 +00001961 // Get the device id that owns this camera.
1962 auto [deviceId, _] = mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
1963
Jayant Chowdhary5216b212019-07-17 09:26:23 -07001964 // If it's not calling from cameraserver, check the permission if the
1965 // device isn't a system only camera (shouldRejectSystemCameraConnection already checks for
1966 // android.permission.SYSTEM_CAMERA for system only camera devices).
Austin Borger249e6592024-03-10 22:28:11 -07001967 bool checkPermissionForCamera =
Biswarup Pale506e732024-03-27 13:46:20 +00001968 hasPermissionsForCamera(cameraId, clientPid, clientUid, clientName, deviceId);
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001969 if (callingPid != getpid() &&
Joanne Chung02c13d02023-01-16 12:58:05 +00001970 (deviceKind != SystemCameraKind::SYSTEM_ONLY_CAMERA) && !checkPermissionForCamera) {
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001971 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08001972 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
1973 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" without camera permission",
Austin Borger249e6592024-03-10 22:28:11 -07001974 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08001975 }
1976
Svet Ganova453d0d2018-01-11 15:37:58 -08001977 // Make sure the UID is in an active state to use the camera
Austin Borgered99f642023-06-01 16:51:35 -07001978 if (!mUidPolicy->isUidActive(callingUid, clientName)) {
Varun Shahb42f1eb2019-04-16 14:45:13 -07001979 int32_t procState = mUidPolicy->getProcState(callingUid);
Svet Ganova453d0d2018-01-11 15:37:58 -08001980 ALOGE("Access Denial: can't use the camera from an idle UID pid=%d, uid=%d",
1981 clientPid, clientUid);
1982 return STATUS_ERROR_FMT(ERROR_DISABLED,
Varun Shahb42f1eb2019-04-16 14:45:13 -07001983 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" from background ("
1984 "calling UID %d proc state %" PRId32 ")",
Austin Borger249e6592024-03-10 22:28:11 -07001985 clientName.c_str(), clientPid, clientUid, cameraId.c_str(),
Varun Shahb42f1eb2019-04-16 14:45:13 -07001986 callingUid, procState);
Svet Ganova453d0d2018-01-11 15:37:58 -08001987 }
1988
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07001989 // Automotive privileged client AID_AUTOMOTIVE_EVS using exterior system camera for use cases
1990 // such as rear view and surround view cannot be disabled and are exempt from sensor privacy
1991 // policy. In all other cases,if sensor privacy is enabled then prevent access to the camera.
1992 if ((!isAutomotivePrivilegedClient(callingUid) ||
1993 !isAutomotiveExteriorSystemCamera(cameraId)) &&
1994 mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
Michael Grooverd1d435a2018-12-18 17:39:42 -08001995 ALOGE("Access Denial: cannot use the camera when sensor privacy is enabled");
1996 return STATUS_ERROR_FMT(ERROR_DISABLED,
1997 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" when sensor privacy "
Austin Borger249e6592024-03-10 22:28:11 -07001998 "is enabled", clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Michael Grooverd1d435a2018-12-18 17:39:42 -08001999 }
2000
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002001 // Only use passed in clientPid to check permission. Use calling PID as the client PID that's
2002 // connected to camera service directly.
Chien-Yu Chen18df60e2016-03-18 18:18:09 -07002003 originalClientPid = clientPid;
Chien-Yu Chen4f3d6202016-03-22 10:50:23 -07002004 clientPid = callingPid;
Mathias Agopian65ab4712010-07-14 17:59:35 -07002005
Ruben Brunk6267b532015-04-30 17:44:07 -07002006 userid_t clientUserId = multiuser_get_user_id(clientUid);
Wu-cheng Lia3355432011-05-20 14:54:25 +08002007
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002008 // For non-system clients : Only allow clients who are being used by the current foreground
2009 // device user, unless calling from our own process.
Austin Borger22c5c852024-03-08 13:31:36 -08002010 if (!callerHasSystemUid() && callingPid != getpid() &&
Jayant Chowdhary8ec41c12019-02-21 20:17:22 -08002011 (mAllowedUsers.find(clientUserId) == mAllowedUsers.end())) {
Ruben Brunk6267b532015-04-30 17:44:07 -07002012 ALOGE("CameraService::connect X (PID %d) rejected (cannot connect from "
2013 "device user %d, currently allowed device users: %s)", callingPid, clientUserId,
Austin Borgered99f642023-06-01 16:51:35 -07002014 toString(mAllowedUsers).c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002015 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2016 "Callers from device user %d are not currently allowed to connect to camera \"%s\"",
Austin Borgered99f642023-06-01 16:51:35 -07002017 clientUserId, cameraId.c_str());
Ruben Brunk36597b22015-03-20 22:15:57 -07002018 }
2019
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002020 if (flags::camera_hsum_permission()) {
2021 // If the System User tries to access the camera when the device is running in
2022 // headless system user mode, ensure that client has the required permission
2023 // CAMERA_HEADLESS_SYSTEM_USER.
Austin Borger249e6592024-03-10 22:28:11 -07002024 if (isHeadlessSystemUserMode()
2025 && (clientUserId == USER_SYSTEM)
2026 && !hasPermissionsForCameraHeadlessSystemUser(cameraId, callingPid, callingUid)) {
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002027 ALOGE("Permission Denial: can't use the camera pid=%d, uid=%d", clientPid, clientUid);
2028 return STATUS_ERROR_FMT(ERROR_PERMISSION_DENIED,
2029 "Caller \"%s\" (PID %d, UID %d) cannot open camera \"%s\" as Headless System \
2030 User without camera headless system user permission",
Austin Borger249e6592024-03-10 22:28:11 -07002031 clientName.c_str(), clientPid, clientUid, cameraId.c_str());
Jyoti Bhayanaa16cc4c2023-09-26 15:37:19 -07002032 }
Jyoti Bhayana5bdb5a62023-08-24 14:46:08 -07002033 }
2034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002035 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08002036}
2037
Austin Borgered99f642023-06-01 16:51:35 -07002038status_t CameraService::checkIfDeviceIsUsable(const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08002039 auto cameraState = getCameraState(cameraId);
Austin Borger22c5c852024-03-08 13:31:36 -08002040 int callingPid = getCallingPid();
Ruben Brunkcc776712015-02-17 20:18:47 -08002041 if (cameraState == nullptr) {
2042 ALOGE("CameraService::connect X (PID %d) rejected (invalid camera ID %s)", callingPid,
Austin Borgered99f642023-06-01 16:51:35 -07002043 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002044 return -ENODEV;
2045 }
2046
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002047 StatusInternal currentStatus = cameraState->getStatus();
2048 if (currentStatus == StatusInternal::NOT_PRESENT) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002049 ALOGE("CameraService::connect X (PID %d) rejected (camera %s is not connected)",
Austin Borgered99f642023-06-01 16:51:35 -07002050 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002051 return -ENODEV;
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08002052 } else if (currentStatus == StatusInternal::ENUMERATING) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002053 ALOGE("CameraService::connect X (PID %d) rejected, (camera %s is initializing)",
Austin Borgered99f642023-06-01 16:51:35 -07002054 callingPid, cameraId.c_str());
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002055 return -EBUSY;
Igor Murashkincba2c162013-03-20 15:56:31 -07002056 }
Igor Murashkincba2c162013-03-20 15:56:31 -07002057
Ruben Brunkcc776712015-02-17 20:18:47 -08002058 return NO_ERROR;
Igor Murashkine6800ce2013-03-04 17:25:57 -08002059}
2060
Ruben Brunkcc776712015-02-17 20:18:47 -08002061void CameraService::finishConnectLocked(const sp<BasicClient>& client,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002062 const CameraService::DescriptorPtr& desc, int oomScoreOffset, bool systemNativeClient) {
Igor Murashkine6800ce2013-03-04 17:25:57 -08002063
Ruben Brunkcc776712015-02-17 20:18:47 -08002064 // Make a descriptor for the incoming client
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002065 auto clientDescriptor =
2066 CameraService::CameraClientManager::makeClientDescriptor(client, desc,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002067 oomScoreOffset, systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08002068 auto evicted = mActiveClientManager.addAndEvict(clientDescriptor);
2069
2070 logConnected(desc->getKey(), static_cast<int>(desc->getOwnerId()),
Austin Borgered99f642023-06-01 16:51:35 -07002071 client->getPackageName());
Ruben Brunkcc776712015-02-17 20:18:47 -08002072
2073 if (evicted.size() > 0) {
2074 // This should never happen - clients should already have been removed in disconnect
2075 for (auto& i : evicted) {
2076 ALOGE("%s: Invalid state: Client for camera %s was not removed in disconnect",
Austin Borgered99f642023-06-01 16:51:35 -07002077 __FUNCTION__, i->getKey().c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08002078 }
2079
2080 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, clients not evicted properly",
2081 __FUNCTION__);
2082 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07002083
2084 // And register a death notification for the client callback. Do
2085 // this last to avoid Binder policy where a nested Binder
2086 // transaction might be pre-empted to service the client death
2087 // notification if the client process dies before linkToDeath is
2088 // invoked.
2089 sp<IBinder> remoteCallback = client->getRemote();
2090 if (remoteCallback != nullptr) {
2091 remoteCallback->linkToDeath(this);
2092 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002093}
2094
Austin Borgered99f642023-06-01 16:51:35 -07002095status_t CameraService::handleEvictionsLocked(const std::string& cameraId, int clientPid,
2096 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback,
2097 const std::string& packageName, int oomScoreOffset, bool systemNativeClient,
Ruben Brunkcc776712015-02-17 20:18:47 -08002098 /*out*/
2099 sp<BasicClient>* client,
Austin Borgered99f642023-06-01 16:51:35 -07002100 std::shared_ptr<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>* partial) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002101 ATRACE_CALL();
Ruben Brunkcc776712015-02-17 20:18:47 -08002102 status_t ret = NO_ERROR;
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002103 std::vector<DescriptorPtr> evictedClients;
Ruben Brunkcc776712015-02-17 20:18:47 -08002104 DescriptorPtr clientDescriptor;
2105 {
2106 if (effectiveApiLevel == API_1) {
2107 // If we are using API1, any existing client for this camera ID with the same remote
2108 // should be returned rather than evicted to allow MediaRecorder to work properly.
2109
2110 auto current = mActiveClientManager.get(cameraId);
2111 if (current != nullptr) {
2112 auto clientSp = current->getValue();
2113 if (clientSp.get() != nullptr) { // should never be needed
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002114 if (!clientSp->canCastToApiClient(effectiveApiLevel)) {
Shuzhen Wangb2d43f62021-08-25 14:01:11 -07002115 ALOGW("CameraService connect called with a different"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002116 " API level, evicting prior client...");
2117 } else if (clientSp->getRemote() == remoteCallback) {
Ruben Brunkcc776712015-02-17 20:18:47 -08002118 ALOGI("CameraService::connect X (PID %d) (second call from same"
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07002119 " app binder, returning the same client)", clientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08002120 *client = clientSp;
2121 return NO_ERROR;
2122 }
2123 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002124 }
Wu-cheng Li2fd24402012-02-23 19:01:00 -08002125 }
Wu-cheng Li08ad5ef2012-04-19 12:35:00 +08002126
Ruben Brunkcc776712015-02-17 20:18:47 -08002127 // Get state for the given cameraId
2128 auto state = getCameraState(cameraId);
2129 if (state == nullptr) {
2130 ALOGE("CameraService::connect X (PID %d) rejected (no camera device with ID %s)",
Austin Borgered99f642023-06-01 16:51:35 -07002131 clientPid, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002132 // Should never get here because validateConnectLocked should have errored out
Zhijun Heb10cdad2014-06-16 16:38:35 -07002133 return BAD_VALUE;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002134 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002135
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002136 sp<IServiceManager> sm = defaultServiceManager();
2137 sp<IBinder> binder = sm->checkService(String16(kProcessInfoServiceName));
Austin Borger22c5c852024-03-08 13:31:36 -08002138 if (!binder && isAutomotivePrivilegedClient(getCallingUid())) {
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002139 // If processinfo service is not available and the client is automotive privileged
2140 // client used for safety critical uses cases such as rear-view and surround-view which
2141 // needs to be available before android boot completes, then use the hardcoded values
2142 // for the process state and priority score. As this scenario is before android system
2143 // services are up and client is native client, hence using NATIVE_ADJ as the priority
2144 // score and state as PROCESS_STATE_BOUND_TOP as such automotive apps need to be
2145 // visible on the top.
2146 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2147 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2148 state->getConflicting(), resource_policy::NATIVE_ADJ, clientPid,
2149 ActivityManager::PROCESS_STATE_BOUND_TOP, oomScoreOffset, systemNativeClient);
2150 } else {
2151 // Get current active client PIDs
2152 std::vector<int> ownerPids(mActiveClientManager.getAllOwners());
2153 ownerPids.push_back(clientPid);
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00002154
Jyoti Bhayanada519ab2023-05-15 15:49:15 -07002155 std::vector<int> priorityScores(ownerPids.size());
2156 std::vector<int> states(ownerPids.size());
2157
2158 // Get priority scores of all active PIDs
2159 status_t err = ProcessInfoService::getProcessStatesScoresFromPids(ownerPids.size(),
2160 &ownerPids[0], /*out*/&states[0], /*out*/&priorityScores[0]);
2161 if (err != OK) {
2162 ALOGE("%s: Priority score query failed: %d", __FUNCTION__, err);
2163 return err;
2164 }
2165
2166 // Update all active clients' priorities
2167 std::map<int,resource_policy::ClientPriority> pidToPriorityMap;
2168 for (size_t i = 0; i < ownerPids.size() - 1; i++) {
2169 pidToPriorityMap.emplace(ownerPids[i],
2170 resource_policy::ClientPriority(priorityScores[i], states[i],
2171 /* isVendorClient won't get copied over*/ false,
2172 /* oomScoreOffset won't get copied over*/ 0));
2173 }
2174 mActiveClientManager.updatePriorities(pidToPriorityMap);
2175
2176 int32_t actualScore = priorityScores[priorityScores.size() - 1];
2177 int32_t actualState = states[states.size() - 1];
2178
2179 // Make descriptor for incoming client. We store the oomScoreOffset
2180 // since we might need it later on new handleEvictionsLocked and
2181 // ProcessInfoService would not take that into account.
2182 clientDescriptor = CameraClientManager::makeClientDescriptor(cameraId,
2183 sp<BasicClient>{nullptr}, static_cast<int32_t>(state->getCost()),
2184 state->getConflicting(), actualScore, clientPid, actualState,
2185 oomScoreOffset, systemNativeClient);
2186 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002187
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002188 resource_policy::ClientPriority clientPriority = clientDescriptor->getPriority();
2189
Ruben Brunkcc776712015-02-17 20:18:47 -08002190 // Find clients that would be evicted
2191 auto evicted = mActiveClientManager.wouldEvict(clientDescriptor);
2192
2193 // If the incoming client was 'evicted,' higher priority clients have the camera in the
2194 // background, so we cannot do evictions
2195 if (std::find(evicted.begin(), evicted.end(), clientDescriptor) != evicted.end()) {
2196 ALOGE("CameraService::connect X (PID %d) rejected (existing client(s) with higher"
2197 " priority).", clientPid);
2198
2199 sp<BasicClient> clientSp = clientDescriptor->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07002200 std::string curTime = getFormattedCurrentTime();
Ruben Brunkcc776712015-02-17 20:18:47 -08002201 auto incompatibleClients =
2202 mActiveClientManager.getIncompatibleClients(clientDescriptor);
2203
Austin Borgered99f642023-06-01 16:51:35 -07002204 std::string msg = fmt::sprintf("%s : DENIED connect device %s client for package %s "
2205 "(PID %d, score %d state %d) due to eviction policy", curTime.c_str(),
2206 cameraId.c_str(), packageName.c_str(), clientPid,
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002207 clientPriority.getScore(), clientPriority.getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002208
2209 for (auto& i : incompatibleClients) {
Austin Borgered99f642023-06-01 16:51:35 -07002210 msg += fmt::sprintf("\n - Blocked by existing device %s client for package %s"
Emilian Peev8131a262017-02-01 12:33:43 +00002211 "(PID %" PRId32 ", score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002212 i->getKey().c_str(),
2213 i->getValue()->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002214 i->getOwnerId(), i->getPriority().getScore(),
2215 i->getPriority().getState());
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07002216 ALOGE(" Conflicts with: Device %s, client package %s (PID %"
Austin Borgered99f642023-06-01 16:51:35 -07002217 PRId32 ", score %" PRId32 ", state %" PRId32 ")", i->getKey().c_str(),
2218 i->getValue()->getPackageName().c_str(), i->getOwnerId(),
Emilian Peev8131a262017-02-01 12:33:43 +00002219 i->getPriority().getScore(), i->getPriority().getState());
Ruben Brunkcc776712015-02-17 20:18:47 -08002220 }
2221
2222 // Log the client's attempt
Ruben Brunka8ca9152015-04-07 14:23:40 -07002223 Mutex::Autolock l(mLogLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08002224 mEventLog.add(msg);
2225
Yin-Chia Yeh8dfe4642020-06-01 11:57:45 -07002226 auto current = mActiveClientManager.get(cameraId);
2227 if (current != nullptr) {
2228 return -EBUSY; // CAMERA_IN_USE
2229 } else {
2230 return -EUSERS; // MAX_CAMERAS_IN_USE
2231 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002232 }
2233
2234 for (auto& i : evicted) {
2235 sp<BasicClient> clientSp = i->getValue();
2236 if (clientSp.get() == nullptr) {
2237 ALOGE("%s: Invalid state: Null client in active client list.", __FUNCTION__);
2238
2239 // TODO: Remove this
2240 LOG_ALWAYS_FATAL("%s: Invalid state for CameraService, null client in active list",
2241 __FUNCTION__);
2242 mActiveClientManager.remove(i);
2243 continue;
2244 }
2245
2246 ALOGE("CameraService::connect evicting conflicting client for camera ID %s",
Austin Borgered99f642023-06-01 16:51:35 -07002247 i->getKey().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002248 evictedClients.push_back(i);
Ruben Brunkcc776712015-02-17 20:18:47 -08002249
Ruben Brunkcc776712015-02-17 20:18:47 -08002250 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07002251 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID"
Emilian Peev8131a262017-02-01 12:33:43 +00002252 " %" PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted by device %s client for"
2253 " package %s (PID %d, score %" PRId32 ", state %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002254 i->getKey().c_str(), clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00002255 i->getOwnerId(), i->getPriority().getScore(),
Austin Borgered99f642023-06-01 16:51:35 -07002256 i->getPriority().getState(), cameraId.c_str(),
2257 packageName.c_str(), clientPid, clientPriority.getScore(),
Jayant Chowdhary5bf11bf2019-06-24 19:42:56 -07002258 clientPriority.getState()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002259
2260 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002261 clientSp->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08002262 CaptureResultExtras());
Zhijun Heb10cdad2014-06-16 16:38:35 -07002263 }
Ruben Brunkb2119af2014-05-09 19:57:56 -07002264 }
2265
Ruben Brunkcc776712015-02-17 20:18:47 -08002266 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
2267 // other clients from connecting in mServiceLockWrapper if held
2268 mServiceLock.unlock();
2269
2270 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08002271 int64_t token = clearCallingIdentity();
Ruben Brunkcc776712015-02-17 20:18:47 -08002272
2273 // Destroy evicted clients
2274 for (auto& i : evictedClients) {
2275 // Disconnect is blocking, and should only have returned when HAL has cleaned up
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002276 i->getValue()->disconnect(); // Clients will remove themselves from the active client list
Ruben Brunkcc776712015-02-17 20:18:47 -08002277 }
Ruben Brunkcc776712015-02-17 20:18:47 -08002278
Austin Borger22c5c852024-03-08 13:31:36 -08002279 restoreCallingIdentity(token);
Ruben Brunkcc776712015-02-17 20:18:47 -08002280
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002281 for (const auto& i : evictedClients) {
2282 ALOGV("%s: Waiting for disconnect to complete for client for device %s (PID %" PRId32 ")",
Austin Borgered99f642023-06-01 16:51:35 -07002283 __FUNCTION__, i->getKey().c_str(), i->getOwnerId());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002284 ret = mActiveClientManager.waitUntilRemoved(i, DEFAULT_DISCONNECT_TIMEOUT_NS);
2285 if (ret == TIMED_OUT) {
2286 ALOGE("%s: Timed out waiting for client for device %s to disconnect, "
Austin Borgered99f642023-06-01 16:51:35 -07002287 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(),
2288 mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002289 return -EBUSY;
2290 }
2291 if (ret != NO_ERROR) {
2292 ALOGE("%s: Received error waiting for client for device %s to disconnect: %s (%d), "
Austin Borgered99f642023-06-01 16:51:35 -07002293 "current clients:\n%s", __FUNCTION__, i->getKey().c_str(), strerror(-ret),
2294 ret, mActiveClientManager.toString().c_str());
Ruben Brunk4f9576b2015-04-10 17:26:56 -07002295 return ret;
2296 }
2297 }
2298
2299 evictedClients.clear();
2300
Ruben Brunkcc776712015-02-17 20:18:47 -08002301 // Once clients have been disconnected, relock
2302 mServiceLock.lock();
2303
2304 // Check again if the device was unplugged or something while we weren't holding mServiceLock
2305 if ((ret = checkIfDeviceIsUsable(cameraId)) != NO_ERROR) {
2306 return ret;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002307 }
2308
Ruben Brunkcc776712015-02-17 20:18:47 -08002309 *partial = clientDescriptor;
2310 return NO_ERROR;
Ruben Brunkb2119af2014-05-09 19:57:56 -07002311}
2312
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002313Status CameraService::connect(
Igor Murashkine6800ce2013-03-04 17:25:57 -08002314 const sp<ICameraClient>& cameraClient,
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002315 int api1CameraId,
Austin Borgered99f642023-06-01 16:51:35 -07002316 const std::string& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002317 int clientUid,
Chien-Yu Chen98a668f2015-12-18 14:10:33 -08002318 int clientPid,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002319 int targetSdkVersion,
Austin Borger18b30a72022-10-27 12:20:29 -07002320 bool overrideToPortrait,
Chengfei Taobe683db2023-01-31 18:52:49 +00002321 bool forceSlowJpegMode,
Biswarup Pal37a75182024-01-16 15:53:35 +00002322 int32_t deviceId,
2323 int32_t devicePolicy,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -07002324 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002325 sp<ICamera>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002326 ATRACE_CALL();
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002327 Status ret = Status::ok();
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08002328
Biswarup Pal37a75182024-01-16 15:53:35 +00002329 std::string cameraIdStr = cameraIdIntToStr(api1CameraId, deviceId, devicePolicy);
2330 if (cameraIdStr.empty()) {
2331 std::string msg = fmt::sprintf("Camera %d: Invalid camera id for device id %d",
2332 api1CameraId, deviceId);
2333 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
2334 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
2335 }
malikakashedb38962023-09-06 00:03:35 +00002336
Ruben Brunkcc776712015-02-17 20:18:47 -08002337 sp<Client> client = nullptr;
Austin Borgered99f642023-06-01 16:51:35 -07002338 ret = connectHelper<ICameraClient,Client>(cameraClient, cameraIdStr, api1CameraId,
2339 clientPackageName, /*systemNativeClient*/ false, {}, clientUid, clientPid, API_1,
Austin Borger18b30a72022-10-27 12:20:29 -07002340 /*shimUpdateOnly*/ false, /*oomScoreOffset*/ 0, targetSdkVersion,
Austin Borgered99f642023-06-01 16:51:35 -07002341 overrideToPortrait, forceSlowJpegMode, cameraIdStr, /*out*/client);
Zhijun Heb10cdad2014-06-16 16:38:35 -07002342
Biswarup Pal37a75182024-01-16 15:53:35 +00002343 if (!ret.isOk()) {
2344 logRejected(cameraIdStr, getCallingPid(), clientPackageName, toStdString(ret.toString8()));
Ruben Brunkcc776712015-02-17 20:18:47 -08002345 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002346 }
2347
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002348 *device = client;
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002349
2350 const sp<IServiceManager> sm(defaultServiceManager());
2351 const auto& mActivityManager = getActivityManager();
2352 if (mActivityManager) {
2353 mActivityManager->logFgsApiBegin(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08002354 getCallingUid(),
2355 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00002356 }
2357
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002358 return ret;
Zhijun Heb10cdad2014-06-16 16:38:35 -07002359}
2360
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002361bool CameraService::shouldSkipStatusUpdates(SystemCameraKind systemCameraKind,
2362 bool isVendorListener, int clientPid, int clientUid) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002363 // If the client is not a vendor client, don't add listener if
2364 // a) the camera is a publicly hidden secure camera OR
2365 // b) the camera is a system only camera and the client doesn't
2366 // have android.permission.SYSTEM_CAMERA permissions.
2367 if (!isVendorListener && (systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA ||
2368 (systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Austin Borger1c1bee02023-06-01 16:51:35 -07002369 !hasPermissionsForSystemCamera(std::string(), clientPid, clientUid)))) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08002370 return true;
2371 }
2372 return false;
2373}
2374
Austin Borgered99f642023-06-01 16:51:35 -07002375bool CameraService::shouldRejectSystemCameraConnection(const std::string& cameraId) const {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002376 // Rules for rejection:
2377 // 1) If cameraserver tries to access this camera device, accept the
2378 // connection.
2379 // 2) The camera device is a publicly hidden secure camera device AND some
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002380 // non system component is trying to access it.
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002381 // 3) if the camera device is advertised by the camera HAL as SYSTEM_ONLY
2382 // and the serving thread is a non hwbinder thread, the client must have
2383 // android.permission.SYSTEM_CAMERA permissions to connect.
2384
Austin Borger22c5c852024-03-08 13:31:36 -08002385 int cPid = getCallingPid();
2386 int cUid = getCallingUid();
2387 bool systemClient = callerHasSystemUid();
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002388 SystemCameraKind systemCameraKind = SystemCameraKind::PUBLIC;
2389 if (getSystemCameraKind(cameraId, &systemCameraKind) != OK) {
Eino-Ville Talvalaa976df82019-06-13 18:01:58 -07002390 // This isn't a known camera ID, so it's not a system camera
2391 ALOGV("%s: Unknown camera id %s, ", __FUNCTION__, cameraId.c_str());
2392 return false;
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07002393 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002394
2395 // (1) Cameraserver trying to connect, accept.
Austin Borger249e6592024-03-10 22:28:11 -07002396 if (isCallerCameraServerNotDelegating()) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002397 return false;
2398 }
2399 // (2)
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002400 if (!systemClient && systemCameraKind == SystemCameraKind::HIDDEN_SECURE_CAMERA) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002401 ALOGW("Rejecting access to secure hidden camera %s", cameraId.c_str());
2402 return true;
2403 }
2404 // (3) Here we only check for permissions if it is a system only camera device. This is since
2405 // getCameraCharacteristics() allows for calls to succeed (albeit after hiding some
2406 // characteristics) even if clients don't have android.permission.CAMERA. We do not want the
2407 // same behavior for system camera devices.
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08002408 if (!systemClient && systemCameraKind == SystemCameraKind::SYSTEM_ONLY_CAMERA &&
Jyoti Bhayanafeb73922023-03-16 13:01:38 -07002409 !hasPermissionsForSystemCamera(cameraId, cPid, cUid)) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07002410 ALOGW("Rejecting access to system only camera %s, inadequete permissions",
2411 cameraId.c_str());
2412 return true;
2413 }
2414
2415 return false;
2416}
2417
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002418Status CameraService::connectDevice(
2419 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
Austin Borgered99f642023-06-01 16:51:35 -07002420 const std::string& unresolvedCameraId,
2421 const std::string& clientPackageName,
2422 const std::optional<std::string>& clientFeatureId,
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07002423 int clientUid, int oomScoreOffset, int targetSdkVersion,
Biswarup Pal37a75182024-01-16 15:53:35 +00002424 bool overrideToPortrait, int32_t deviceId, int32_t devicePolicy,
Ruben Brunkcc776712015-02-17 20:18:47 -08002425 /*out*/
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08002426 sp<hardware::camera2::ICameraDeviceUser>* device) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07002427 ATRACE_CALL();
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
3436Status CameraService::getConcurrentCameraIds(
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003437 std::vector<ConcurrentCameraIdCombination>* concurrentCameraIds) {
3438 ATRACE_CALL();
3439 if (!concurrentCameraIds) {
3440 ALOGE("%s: concurrentCameraIds is NULL", __FUNCTION__);
3441 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "concurrentCameraIds is NULL");
3442 }
3443
3444 if (!mInitialized) {
3445 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
Austin Borgered99f642023-06-01 16:51:35 -07003446 logServiceError("Camera subsystem is not available", ERROR_DISCONNECTED);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003447 return STATUS_ERROR(ERROR_DISCONNECTED,
3448 "Camera subsystem is not available");
3449 }
3450 // First call into the provider and get the set of concurrent camera
3451 // combinations
3452 std::vector<std::unordered_set<std::string>> concurrentCameraCombinations =
Jayant Chowdharycad23c22020-03-10 15:04:59 -07003453 mCameraProviderManager->getConcurrentCameraIds();
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003454 for (auto &combination : concurrentCameraCombinations) {
Biswarup Pal7d072862024-04-17 15:24:47 +00003455 std::vector<std::pair<std::string, int32_t>> validCombination;
3456 int32_t firstDeviceId = kInvalidDeviceId;
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003457 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 }
Biswarup Pal7d072862024-04-17 15:24:47 +00003471 auto [cameraOwnerDeviceId, mappedCameraId] =
3472 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
3473 if (firstDeviceId == kInvalidDeviceId) {
3474 firstDeviceId = cameraOwnerDeviceId;
3475 } else if (firstDeviceId != cameraOwnerDeviceId) {
3476 // Found an invalid combination which contains cameras with different device id's,
3477 // hence discard it.
3478 validCombination.clear();
3479 break;
3480 }
3481 validCombination.push_back({mappedCameraId, cameraOwnerDeviceId});
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003482 }
3483 if (validCombination.size() != 0) {
3484 concurrentCameraIds->push_back(std::move(validCombination));
3485 }
3486 }
3487 return Status::ok();
3488}
3489
3490Status CameraService::isConcurrentSessionConfigurationSupported(
3491 const std::vector<CameraIdAndSessionConfiguration>& cameraIdsAndSessionConfigurations,
Biswarup Pal7d072862024-04-17 15:24:47 +00003492 int targetSdkVersion, int32_t deviceId, int32_t devicePolicy,
3493 /*out*/bool* isSupported) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003494 if (!isSupported) {
3495 ALOGE("%s: isSupported is NULL", __FUNCTION__);
3496 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "isSupported is NULL");
3497 }
3498
3499 if (!mInitialized) {
3500 ALOGE("%s: Camera HAL couldn't be initialized", __FUNCTION__);
3501 return STATUS_ERROR(ERROR_DISCONNECTED,
3502 "Camera subsystem is not available");
3503 }
3504
Biswarup Pal7d072862024-04-17 15:24:47 +00003505 for (auto cameraIdAndSessionConfiguration : cameraIdsAndSessionConfigurations) {
3506 std::optional<std::string> cameraIdOptional =
3507 resolveCameraId(cameraIdAndSessionConfiguration.mCameraId, deviceId, devicePolicy,
3508 getCallingUid());
3509 if (!cameraIdOptional.has_value()) {
3510 std::string msg = fmt::sprintf("Camera %s: Invalid camera id for device id %d",
3511 cameraIdAndSessionConfiguration.mCameraId.c_str(), deviceId);
3512 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3513 return STATUS_ERROR(CameraService::ERROR_ILLEGAL_ARGUMENT, msg.c_str());
3514 }
3515 cameraIdAndSessionConfiguration.mCameraId = cameraIdOptional.value();
3516 }
3517
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003518 // Check for camera permissions
Austin Borger22c5c852024-03-08 13:31:36 -08003519 int callingPid = getCallingPid();
3520 int callingUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003521 bool hasCameraPermission = ((callingPid == getpid()) ||
Biswarup Pal7d072862024-04-17 15:24:47 +00003522 hasPermissionsForCamera(callingPid, callingUid,
3523 devicePolicy == IVirtualDeviceManagerNative::DEVICE_POLICY_DEFAULT
3524 ? kDefaultDeviceId : deviceId));
Austin Borger249e6592024-03-10 22:28:11 -07003525 if (!hasCameraPermission) {
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003526 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
3527 "android.permission.CAMERA needed to call"
3528 "isConcurrentSessionConfigurationSupported");
3529 }
3530
3531 status_t res =
3532 mCameraProviderManager->isConcurrentSessionConfigurationSupported(
Shuzhen Wangd4abdf72021-05-28 11:22:50 -07003533 cameraIdsAndSessionConfigurations, mPerfClassPrimaryCameraIds,
3534 targetSdkVersion, isSupported);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003535 if (res != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07003536 logServiceError("Unable to query session configuration support",
Rucha Katakward9ea6452021-05-06 11:57:16 -07003537 ERROR_INVALID_OPERATION);
Jayant Chowdhary2bbdce42020-01-12 14:55:41 -08003538 return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION, "Unable to query session configuration "
3539 "support %s (%d)", strerror(-res), res);
3540 }
3541 return Status::ok();
3542}
3543
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003544Status CameraService::addListener(const sp<ICameraServiceListener>& listener,
3545 /*out*/
3546 std::vector<hardware::CameraStatus> *cameraStatuses) {
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003547 return addListenerHelper(listener, cameraStatuses);
3548}
3549
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003550binder::Status CameraService::addListenerTest(const sp<hardware::ICameraServiceListener>& listener,
3551 std::vector<hardware::CameraStatus>* cameraStatuses) {
3552 return addListenerHelper(listener, cameraStatuses, false, true);
3553}
3554
Jayant Chowdharyf949ddd2019-01-29 14:34:11 -08003555Status CameraService::addListenerHelper(const sp<ICameraServiceListener>& listener,
3556 /*out*/
3557 std::vector<hardware::CameraStatus> *cameraStatuses,
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003558 bool isVendorListener, bool isProcessLocalTest) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003559 ATRACE_CALL();
3560
Igor Murashkinbfc99152013-02-27 12:55:20 -08003561 ALOGV("%s: Add listener %p", __FUNCTION__, listener.get());
Igor Murashkin634a5152013-02-20 17:15:11 -08003562
Ruben Brunk3450ba72015-06-16 11:00:37 -07003563 if (listener == nullptr) {
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003564 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003565 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to addListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003566 }
3567
Austin Borger22c5c852024-03-08 13:31:36 -08003568 auto clientPid = getCallingPid();
3569 auto clientUid = getCallingUid();
Austin Borger249e6592024-03-10 22:28:11 -07003570 bool openCloseCallbackAllowed = hasPermissionsForOpenCloseListener(clientPid, clientUid);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003571
Igor Murashkinbfc99152013-02-27 12:55:20 -08003572 Mutex::Autolock lock(mServiceLock);
3573
Ruben Brunkcc776712015-02-17 20:18:47 -08003574 {
3575 Mutex::Autolock lock(mStatusListenerLock);
Emilian Peev53722fa2019-02-22 17:47:20 -08003576 for (const auto &it : mListenerList) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003577 if (IInterface::asBinder(it->getListener()) == IInterface::asBinder(listener)) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003578 ALOGW("%s: Tried to add listener %p which was already subscribed",
3579 __FUNCTION__, listener.get());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003580 return STATUS_ERROR(ERROR_ALREADY_EXISTS, "Listener already registered");
Ruben Brunkcc776712015-02-17 20:18:47 -08003581 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003582 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003583
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003584 sp<ServiceListener> serviceListener =
Shuzhen Wang695044d2020-03-06 09:02:23 -08003585 new ServiceListener(this, listener, clientUid, clientPid, isVendorListener,
3586 openCloseCallbackAllowed);
Jayant Chowdhary32ced0e2021-04-09 14:00:22 -07003587 auto ret = serviceListener->initialize(isProcessLocalTest);
Emilian Peev53722fa2019-02-22 17:47:20 -08003588 if (ret != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07003589 std::string msg = fmt::sprintf("Failed to initialize service listener: %s (%d)",
Emilian Peev53722fa2019-02-22 17:47:20 -08003590 strerror(-ret), ret);
Austin Borgered99f642023-06-01 16:51:35 -07003591 logServiceError(msg, ERROR_ILLEGAL_ARGUMENT);
3592 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3593 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Emilian Peev53722fa2019-02-22 17:47:20 -08003594 }
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003595 // The listener still needs to be added to the list of listeners, regardless of what
3596 // permissions the listener process has / whether it is a vendor listener. Since it might be
3597 // eligible to listen to other camera ids.
3598 mListenerList.emplace_back(serviceListener);
Austin Borgerdddb7552023-03-30 17:53:01 -07003599 mUidPolicy->registerMonitorUid(clientUid, /*openCamera*/false);
Igor Murashkinbfc99152013-02-27 12:55:20 -08003600 }
3601
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003602 /* Collect current devices and status */
Igor Murashkincba2c162013-03-20 15:56:31 -07003603 {
Ruben Brunkcc776712015-02-17 20:18:47 -08003604 Mutex::Autolock lock(mCameraStatesLock);
3605 for (auto& i : mCameraStates) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003606 // Get the device id and app-visible camera id for the given HAL-visible camera id.
3607 auto [deviceId, mappedCameraId] =
3608 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(i.first);
3609
3610 cameraStatuses->emplace_back(mappedCameraId,
Shuzhen Wange7aa0342021-08-03 11:29:47 -07003611 mapToInterface(i.second->getStatus()), i.second->getUnavailablePhysicalIds(),
Biswarup Pal37a75182024-01-16 15:53:35 +00003612 openCloseCallbackAllowed ? i.second->getClientPackage() : std::string(),
3613 deviceId);
Igor Murashkincba2c162013-03-20 15:56:31 -07003614 }
3615 }
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003616 // Remove the camera statuses that should be hidden from the client, we do
3617 // this after collecting the states in order to avoid holding
3618 // mCameraStatesLock and mInterfaceLock (held in getSystemCameraKind()) at
3619 // the same time.
3620 cameraStatuses->erase(std::remove_if(cameraStatuses->begin(), cameraStatuses->end(),
3621 [this, &isVendorListener, &clientPid, &clientUid](const hardware::CameraStatus& s) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003622 std::string cameraId = s.cameraId;
3623 std::optional<std::string> cameraIdOptional = resolveCameraId(s.cameraId,
3624 s.deviceId, IVirtualDeviceManagerNative::DEVICE_POLICY_CUSTOM,
3625 clientUid);
3626 if (!cameraIdOptional.has_value()) {
3627 std::string msg =
3628 fmt::sprintf(
3629 "Camera %s: Invalid camera id for device id %d",
3630 s.cameraId.c_str(), s.deviceId);
3631 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3632 return true;
3633 }
3634 cameraId = cameraIdOptional.value();
3635 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
3636 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
3637 ALOGE("%s: Invalid camera id %s, skipping status update",
3638 __FUNCTION__, s.cameraId.c_str());
3639 return true;
3640 }
3641 return shouldSkipStatusUpdates(deviceKind, isVendorListener, clientPid,
3642 clientUid);
3643 }), cameraStatuses->end());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07003644
Biswarup Pal37a75182024-01-16 15:53:35 +00003645 // cameraStatuses will have non-eligible camera ids removed.
Austin Borgered99f642023-06-01 16:51:35 -07003646 std::set<std::string> idsChosenForCallback;
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003647 for (const auto &s : *cameraStatuses) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003648 // Add only default device cameras here, as virtual cameras currently don't support torch
3649 // anyway. Note that this is a simplification of the implementation here, and we should
3650 // change this when virtual cameras support torch.
3651 if (s.deviceId == kDefaultDeviceId) {
3652 idsChosenForCallback.insert(s.cameraId);
3653 }
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003654 }
Igor Murashkincba2c162013-03-20 15:56:31 -07003655
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003656 /*
3657 * Immediately signal current torch status to this listener only
3658 * This may be a subset of all the devices, so don't include it in the response directly
3659 */
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003660 {
3661 Mutex::Autolock al(mTorchStatusMutex);
3662 for (size_t i = 0; i < mTorchStatusMap.size(); i++ ) {
Austin Borgered99f642023-06-01 16:51:35 -07003663 const std::string &id = mTorchStatusMap.keyAt(i);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003664 // The camera id is visible to the client. Fine to send torch
3665 // callback.
3666 if (idsChosenForCallback.find(id) != idsChosenForCallback.end()) {
Biswarup Pal37a75182024-01-16 15:53:35 +00003667 listener->onTorchStatusChanged(mapToInterface(mTorchStatusMap.valueAt(i)), id,
3668 kDefaultDeviceId);
Jayant Chowdhary8c62d892021-03-31 02:13:46 -07003669 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003670 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08003671 }
3672
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003673 return Status::ok();
Igor Murashkinbfc99152013-02-27 12:55:20 -08003674}
Ruben Brunkcc776712015-02-17 20:18:47 -08003675
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003676Status CameraService::removeListener(const sp<ICameraServiceListener>& listener) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003677 ATRACE_CALL();
3678
Igor Murashkinbfc99152013-02-27 12:55:20 -08003679 ALOGV("%s: Remove listener %p", __FUNCTION__, listener.get());
3680
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003681 if (listener == 0) {
3682 ALOGE("%s: Listener must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003683 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Null listener given to removeListener");
Igor Murashkinbd3e2e02014-03-17 13:01:41 -07003684 }
3685
Igor Murashkinbfc99152013-02-27 12:55:20 -08003686 Mutex::Autolock lock(mServiceLock);
3687
Ruben Brunkcc776712015-02-17 20:18:47 -08003688 {
3689 Mutex::Autolock lock(mStatusListenerLock);
3690 for (auto it = mListenerList.begin(); it != mListenerList.end(); it++) {
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003691 if (IInterface::asBinder((*it)->getListener()) == IInterface::asBinder(listener)) {
Austin Borgerdddb7552023-03-30 17:53:01 -07003692 mUidPolicy->unregisterMonitorUid((*it)->getListenerUid(), /*closeCamera*/false);
Jayant Chowdhary5216b212019-07-17 09:26:23 -07003693 IInterface::asBinder(listener)->unlinkToDeath(*it);
Ruben Brunkcc776712015-02-17 20:18:47 -08003694 mListenerList.erase(it);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003695 return Status::ok();
Ruben Brunkcc776712015-02-17 20:18:47 -08003696 }
Igor Murashkinbfc99152013-02-27 12:55:20 -08003697 }
3698 }
3699
3700 ALOGW("%s: Tried to remove a listener %p which was not subscribed",
3701 __FUNCTION__, listener.get());
3702
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003703 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Unregistered listener given to removeListener");
Igor Murashkin634a5152013-02-20 17:15:11 -08003704}
3705
Austin Borgered99f642023-06-01 16:51:35 -07003706Status CameraService::getLegacyParameters(int cameraId, /*out*/std::string* parameters) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003707
3708 ATRACE_CALL();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003709 ALOGV("%s: for camera ID = %d", __FUNCTION__, cameraId);
3710
3711 if (parameters == NULL) {
3712 ALOGE("%s: parameters must not be null", __FUNCTION__);
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003713 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, "Parameters must not be null");
Igor Murashkin65d14b92014-06-17 12:03:20 -07003714 }
3715
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003716 Status ret = Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003717
3718 CameraParameters shimParams;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003719 if (!(ret = getLegacyParametersLazy(cameraId, /*out*/&shimParams)).isOk()) {
Igor Murashkin65d14b92014-06-17 12:03:20 -07003720 // Error logged by caller
3721 return ret;
3722 }
3723
3724 String8 shimParamsString8 = shimParams.flatten();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003725
Austin Borgered99f642023-06-01 16:51:35 -07003726 *parameters = toStdString(shimParamsString8);
Igor Murashkin65d14b92014-06-17 12:03:20 -07003727
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003728 return ret;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003729}
3730
Austin Borgered99f642023-06-01 16:51:35 -07003731Status CameraService::supportsCameraApi(const std::string& unresolvedCameraId, int apiVersion,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08003732 /*out*/ bool *isSupported) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07003733 ATRACE_CALL();
3734
malikakashedb38962023-09-06 00:03:35 +00003735 const std::string cameraId = resolveCameraId(
Austin Borger22c5c852024-03-08 13:31:36 -08003736 unresolvedCameraId, getCallingUid());
malikakash82ed4352023-07-21 22:44:34 +00003737
Austin Borgered99f642023-06-01 16:51:35 -07003738 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003739
3740 switch (apiVersion) {
3741 case API_VERSION_1:
3742 case API_VERSION_2:
3743 break;
3744 default:
Austin Borgered99f642023-06-01 16:51:35 -07003745 std::string msg = fmt::sprintf("Unknown API version %d", apiVersion);
3746 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3747 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Igor Murashkin65d14b92014-06-17 12:03:20 -07003748 }
3749
Austin Borger18b30a72022-10-27 12:20:29 -07003750 int portraitRotation;
Austin Borgered99f642023-06-01 16:51:35 -07003751 auto deviceVersionAndTransport = getDeviceVersion(cameraId, false, &portraitRotation);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003752 if (deviceVersionAndTransport.first == -1) {
Austin Borgered99f642023-06-01 16:51:35 -07003753 std::string msg = fmt::sprintf("Unknown camera ID %s", cameraId.c_str());
3754 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3755 return STATUS_ERROR(ERROR_ILLEGAL_ARGUMENT, msg.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003756 }
3757 if (deviceVersionAndTransport.second == IPCTransport::HIDL) {
3758 int deviceVersion = deviceVersionAndTransport.first;
3759 switch (deviceVersion) {
3760 case CAMERA_DEVICE_API_VERSION_1_0:
3761 case CAMERA_DEVICE_API_VERSION_3_0:
3762 case CAMERA_DEVICE_API_VERSION_3_1:
3763 if (apiVersion == API_VERSION_2) {
3764 ALOGV("%s: Camera id %s uses HAL version %d <3.2, doesn't support api2 without "
Austin Borgered99f642023-06-01 16:51:35 -07003765 "shim", __FUNCTION__, cameraId.c_str(), deviceVersion);
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003766 *isSupported = false;
3767 } else { // if (apiVersion == API_VERSION_1) {
3768 ALOGV("%s: Camera id %s uses older HAL before 3.2, but api1 is always "
Austin Borgered99f642023-06-01 16:51:35 -07003769 "supported", __FUNCTION__, cameraId.c_str());
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003770 *isSupported = true;
3771 }
3772 break;
3773 case CAMERA_DEVICE_API_VERSION_3_2:
3774 case CAMERA_DEVICE_API_VERSION_3_3:
3775 case CAMERA_DEVICE_API_VERSION_3_4:
3776 case CAMERA_DEVICE_API_VERSION_3_5:
3777 case CAMERA_DEVICE_API_VERSION_3_6:
3778 case CAMERA_DEVICE_API_VERSION_3_7:
3779 ALOGV("%s: Camera id %s uses HAL3.2 or newer, supports api1/api2 directly",
Austin Borgered99f642023-06-01 16:51:35 -07003780 __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003781 *isSupported = true;
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003782 break;
3783 default: {
Austin Borgered99f642023-06-01 16:51:35 -07003784 std::string msg = fmt::sprintf("Unknown device version %x for device %s",
3785 deviceVersion, cameraId.c_str());
3786 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
3787 return STATUS_ERROR(ERROR_INVALID_OPERATION, msg.c_str());
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003788 }
Igor Murashkin65d14b92014-06-17 12:03:20 -07003789 }
Jayant Chowdharyffc5d682022-05-12 18:34:34 +00003790 } else {
3791 *isSupported = true;
Igor Murashkin65d14b92014-06-17 12:03:20 -07003792 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003793 return Status::ok();
Igor Murashkin65d14b92014-06-17 12:03:20 -07003794}
3795
Austin Borgered99f642023-06-01 16:51:35 -07003796Status CameraService::isHiddenPhysicalCamera(const std::string& unresolvedCameraId,
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003797 /*out*/ bool *isSupported) {
3798 ATRACE_CALL();
3799
malikakashedb38962023-09-06 00:03:35 +00003800 const std::string cameraId = resolveCameraId(unresolvedCameraId,
Austin Borger22c5c852024-03-08 13:31:36 -08003801 getCallingUid());
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003802
Austin Borgered99f642023-06-01 16:51:35 -07003803 ALOGV("%s: for camera ID = %s", __FUNCTION__, cameraId.c_str());
3804 *isSupported = mCameraProviderManager->isHiddenPhysicalCamera(cameraId);
Shuzhen Wangf9d2c022018-08-21 12:07:35 -07003805
3806 return Status::ok();
3807}
3808
Cliff Wud8cae102021-03-11 01:37:42 +08003809Status CameraService::injectCamera(
Austin Borgered99f642023-06-01 16:51:35 -07003810 const std::string& packageName, const std::string& internalCamId,
3811 const std::string& externalCamId,
Cliff Wud8cae102021-03-11 01:37:42 +08003812 const sp<ICameraInjectionCallback>& callback,
3813 /*out*/
Cliff Wud3a05312021-04-26 23:07:31 +08003814 sp<ICameraInjectionSession>* cameraInjectionSession) {
Cliff Wud8cae102021-03-11 01:37:42 +08003815 ATRACE_CALL();
3816
Austin Borgered99f642023-06-01 16:51:35 -07003817 if (!checkCallingPermission(toString16(sCameraInjectExternalCameraPermission))) {
Austin Borger22c5c852024-03-08 13:31:36 -08003818 const int pid = getCallingPid();
3819 const int uid = getCallingUid();
Cliff Wud8cae102021-03-11 01:37:42 +08003820 ALOGE("Permission Denial: can't inject camera pid=%d, uid=%d", pid, uid);
3821 return STATUS_ERROR(ERROR_PERMISSION_DENIED,
Biswarup Pal37a75182024-01-16 15:53:35 +00003822 "Permission Denial: no permission to inject camera");
3823 }
3824
3825 // Do not allow any camera injection that injects or replaces a virtual camera.
3826 auto [deviceIdForInternalCamera, _] =
3827 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(internalCamId);
3828 if (deviceIdForInternalCamera != kDefaultDeviceId) {
3829 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3830 "Cannot replace a virtual camera");
3831 }
3832 [[maybe_unused]] auto [deviceIdForExternalCamera, unusedMappedCameraId] =
3833 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(externalCamId);
3834 if (deviceIdForExternalCamera != kDefaultDeviceId) {
3835 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED,
3836 "Cannot inject a virtual camera to replace an internal camera");
Cliff Wud8cae102021-03-11 01:37:42 +08003837 }
3838
3839 ALOGV(
3840 "%s: Package name = %s, Internal camera ID = %s, External camera ID = "
3841 "%s",
Austin Borgered99f642023-06-01 16:51:35 -07003842 __FUNCTION__, packageName.c_str(),
3843 internalCamId.c_str(), externalCamId.c_str());
Cliff Wud8cae102021-03-11 01:37:42 +08003844
Cliff Wud3a05312021-04-26 23:07:31 +08003845 {
3846 Mutex::Autolock lock(mInjectionParametersLock);
Austin Borgered99f642023-06-01 16:51:35 -07003847 mInjectionInternalCamId = internalCamId;
3848 mInjectionExternalCamId = externalCamId;
Cliff Wu646bd612021-11-23 23:21:29 +08003849 mInjectionStatusListener->addListener(callback);
3850 *cameraInjectionSession = new CameraInjectionSession(this);
Cliff Wud3a05312021-04-26 23:07:31 +08003851 status_t res = NO_ERROR;
3852 auto clientDescriptor = mActiveClientManager.get(mInjectionInternalCamId);
3853 // If the client already exists, we can directly connect to the camera device through the
3854 // client's injectCamera(), otherwise we need to wait until the client is established
3855 // (execute connectHelper()) before injecting the camera to the camera device.
3856 if (clientDescriptor != nullptr) {
3857 mInjectionInitPending = false;
Cliff Wu646bd612021-11-23 23:21:29 +08003858 sp<BasicClient> clientSp = clientDescriptor->getValue();
3859 res = checkIfInjectionCameraIsPresent(mInjectionExternalCamId, clientSp);
3860 if(res != OK) {
3861 return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
3862 "No camera device with ID \"%s\" currently available",
Austin Borgered99f642023-06-01 16:51:35 -07003863 mInjectionExternalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08003864 }
3865 res = clientSp->injectCamera(mInjectionExternalCamId, mCameraProviderManager);
Biswarup Pal37a75182024-01-16 15:53:35 +00003866 if (res != OK) {
Cliff Wud3a05312021-04-26 23:07:31 +08003867 mInjectionStatusListener->notifyInjectionError(mInjectionExternalCamId, res);
3868 }
3869 } else {
3870 mInjectionInitPending = true;
3871 }
3872 }
Cliff Wud8cae102021-03-11 01:37:42 +08003873
Cliff Wud3a05312021-04-26 23:07:31 +08003874 return binder::Status::ok();
Cliff Wud8cae102021-03-11 01:37:42 +08003875}
3876
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003877Status CameraService::reportExtensionSessionStats(
Austin Borgered99f642023-06-01 16:51:35 -07003878 const hardware::CameraExtensionSessionStats& stats, std::string* sessionKey /*out*/) {
Avichal Rakesh6e57a2b2023-05-01 17:53:37 -07003879 ALOGV("%s: reported %s", __FUNCTION__, stats.toString().c_str());
3880 *sessionKey = mCameraServiceProxyWrapper->updateExtensionStats(stats);
3881 return Status::ok();
3882}
3883
Ruben Brunkcc776712015-02-17 20:18:47 -08003884void CameraService::removeByClient(const BasicClient* client) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07003885 Mutex::Autolock lock(mServiceLock);
Ruben Brunkcc776712015-02-17 20:18:47 -08003886 for (auto& i : mActiveClientManager.getAll()) {
3887 auto clientSp = i->getValue();
3888 if (clientSp.get() == client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003889 cacheClientTagDumpIfNeeded(client->mCameraIdStr, clientSp.get());
Ruben Brunkcc776712015-02-17 20:18:47 -08003890 mActiveClientManager.remove(i);
Igor Murashkin634a5152013-02-20 17:15:11 -08003891 }
Igor Murashkinecf17e82012-10-02 16:05:11 -07003892 }
Yin-Chia Yehdba03232019-08-19 15:54:28 -07003893 updateAudioRestrictionLocked();
Igor Murashkin634a5152013-02-20 17:15:11 -08003894}
3895
Ruben Brunkcc776712015-02-17 20:18:47 -08003896bool CameraService::evictClientIdByRemote(const wp<IBinder>& remote) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003897 bool ret = false;
3898 {
3899 // Acquire mServiceLock and prevent other clients from connecting
3900 std::unique_ptr<AutoConditionLock> lock =
3901 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
Igor Murashkin634a5152013-02-20 17:15:11 -08003902
Ruben Brunkcc776712015-02-17 20:18:47 -08003903 std::vector<sp<BasicClient>> evicted;
3904 for (auto& i : mActiveClientManager.getAll()) {
3905 auto clientSp = i->getValue();
3906 if (clientSp.get() == nullptr) {
3907 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
3908 mActiveClientManager.remove(i);
3909 continue;
3910 }
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08003911 if (remote == clientSp->getRemote()) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003912 mActiveClientManager.remove(i);
3913 evicted.push_back(clientSp);
Igor Murashkin634a5152013-02-20 17:15:11 -08003914
Ruben Brunkcc776712015-02-17 20:18:47 -08003915 // Notify the client of disconnection
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003916 clientSp->notifyError(
3917 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
Ruben Brunkcc776712015-02-17 20:18:47 -08003918 CaptureResultExtras());
Igor Murashkin634a5152013-02-20 17:15:11 -08003919 }
3920 }
3921
Ruben Brunkcc776712015-02-17 20:18:47 -08003922 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
3923 // other clients from connecting in mServiceLockWrapper if held
3924 mServiceLock.unlock();
3925
Ruben Brunk36597b22015-03-20 22:15:57 -07003926 // Do not clear caller identity, remote caller should be client proccess
3927
Ruben Brunkcc776712015-02-17 20:18:47 -08003928 for (auto& i : evicted) {
3929 if (i.get() != nullptr) {
3930 i->disconnect();
3931 ret = true;
3932 }
Igor Murashkin634a5152013-02-20 17:15:11 -08003933 }
3934
Ruben Brunkcc776712015-02-17 20:18:47 -08003935 // Reacquire mServiceLock
3936 mServiceLock.lock();
Igor Murashkin634a5152013-02-20 17:15:11 -08003937
Ruben Brunkcc776712015-02-17 20:18:47 -08003938 } // lock is destroyed, allow further connect calls
3939
3940 return ret;
Igor Murashkinecf17e82012-10-02 16:05:11 -07003941}
3942
Ruben Brunkcc776712015-02-17 20:18:47 -08003943std::shared_ptr<CameraService::CameraState> CameraService::getCameraState(
Austin Borgered99f642023-06-01 16:51:35 -07003944 const std::string& cameraId) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08003945 std::shared_ptr<CameraState> state;
3946 {
3947 Mutex::Autolock lock(mCameraStatesLock);
3948 auto iter = mCameraStates.find(cameraId);
3949 if (iter != mCameraStates.end()) {
3950 state = iter->second;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003951 }
3952 }
Ruben Brunkcc776712015-02-17 20:18:47 -08003953 return state;
Mathias Agopian65ab4712010-07-14 17:59:35 -07003954}
3955
Austin Borgered99f642023-06-01 16:51:35 -07003956sp<CameraService::BasicClient> CameraService::removeClientLocked(const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08003957 // Remove from active clients list
3958 auto clientDescriptorPtr = mActiveClientManager.remove(cameraId);
3959 if (clientDescriptorPtr == nullptr) {
3960 ALOGW("%s: Could not evict client, no client for camera ID %s", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07003961 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08003962 return sp<BasicClient>{nullptr};
3963 }
3964
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07003965 sp<BasicClient> client = clientDescriptorPtr->getValue();
3966 if (client.get() != nullptr) {
3967 cacheClientTagDumpIfNeeded(clientDescriptorPtr->getKey(), client.get());
3968 }
3969 return client;
Keun young Parkd8973a72012-03-28 14:13:09 -07003970}
3971
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003972void CameraService::doUserSwitch(const std::vector<int32_t>& newUserIds) {
Ruben Brunk36597b22015-03-20 22:15:57 -07003973 // Acquire mServiceLock and prevent other clients from connecting
3974 std::unique_ptr<AutoConditionLock> lock =
3975 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
3976
Ruben Brunk6267b532015-04-30 17:44:07 -07003977 std::set<userid_t> newAllowedUsers;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003978 for (size_t i = 0; i < newUserIds.size(); i++) {
3979 if (newUserIds[i] < 0) {
Ruben Brunk6267b532015-04-30 17:44:07 -07003980 ALOGE("%s: Bad user ID %d given during user switch, ignoring.",
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003981 __FUNCTION__, newUserIds[i]);
Ruben Brunk6267b532015-04-30 17:44:07 -07003982 return;
3983 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003984 newAllowedUsers.insert(static_cast<userid_t>(newUserIds[i]));
Ruben Brunk36597b22015-03-20 22:15:57 -07003985 }
3986
Ruben Brunka8ca9152015-04-07 14:23:40 -07003987
Ruben Brunk6267b532015-04-30 17:44:07 -07003988 if (newAllowedUsers == mAllowedUsers) {
3989 ALOGW("%s: Received notification of user switch with no updated user IDs.", __FUNCTION__);
3990 return;
3991 }
3992
3993 logUserSwitch(mAllowedUsers, newAllowedUsers);
3994
3995 mAllowedUsers = std::move(newAllowedUsers);
Ruben Brunk36597b22015-03-20 22:15:57 -07003996
3997 // Current user has switched, evict all current clients.
3998 std::vector<sp<BasicClient>> evicted;
3999 for (auto& i : mActiveClientManager.getAll()) {
4000 auto clientSp = i->getValue();
4001
4002 if (clientSp.get() == nullptr) {
4003 ALOGE("%s: Dead client still in mActiveClientManager.", __FUNCTION__);
4004 continue;
4005 }
4006
Ruben Brunk6267b532015-04-30 17:44:07 -07004007 // Don't evict clients that are still allowed.
4008 uid_t clientUid = clientSp->getClientUid();
4009 userid_t clientUserId = multiuser_get_user_id(clientUid);
4010 if (mAllowedUsers.find(clientUserId) != mAllowedUsers.end()) {
4011 continue;
4012 }
4013
Ruben Brunk36597b22015-03-20 22:15:57 -07004014 evicted.push_back(clientSp);
4015
Ruben Brunk36597b22015-03-20 22:15:57 -07004016 ALOGE("Evicting conflicting client for camera ID %s due to user change",
Austin Borgered99f642023-06-01 16:51:35 -07004017 i->getKey().c_str());
Ruben Brunka8ca9152015-04-07 14:23:40 -07004018
Ruben Brunk36597b22015-03-20 22:15:57 -07004019 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004020 logEvent(fmt::sprintf("EVICT device %s client held by package %s (PID %"
Emilian Peev8131a262017-02-01 12:33:43 +00004021 PRId32 ", score %" PRId32 ", state %" PRId32 ")\n - Evicted due"
Austin Borgered99f642023-06-01 16:51:35 -07004022 " to user switch.", i->getKey().c_str(),
4023 clientSp->getPackageName().c_str(),
Emilian Peev8131a262017-02-01 12:33:43 +00004024 i->getOwnerId(), i->getPriority().getScore(),
4025 i->getPriority().getState()));
Ruben Brunk36597b22015-03-20 22:15:57 -07004026
4027 }
4028
4029 // Do not hold mServiceLock while disconnecting clients, but retain the condition
4030 // blocking other clients from connecting in mServiceLockWrapper if held.
4031 mServiceLock.unlock();
4032
4033 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08004034 int64_t token = clearCallingIdentity();
Ruben Brunk36597b22015-03-20 22:15:57 -07004035
4036 for (auto& i : evicted) {
4037 i->disconnect();
4038 }
4039
Austin Borger22c5c852024-03-08 13:31:36 -08004040 restoreCallingIdentity(token);
Ruben Brunk36597b22015-03-20 22:15:57 -07004041
4042 // Reacquire mServiceLock
4043 mServiceLock.lock();
4044}
Ruben Brunkcc776712015-02-17 20:18:47 -08004045
Austin Borgered99f642023-06-01 16:51:35 -07004046void CameraService::logEvent(const std::string &event) {
4047 std::string curTime = getFormattedCurrentTime();
Ruben Brunka8ca9152015-04-07 14:23:40 -07004048 Mutex::Autolock l(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07004049 std::string msg = curTime + " : " + event;
Rucha Katakward9ea6452021-05-06 11:57:16 -07004050 // For service error events, print the msg only once.
Austin Borgered99f642023-06-01 16:51:35 -07004051 if (msg.find("SERVICE ERROR") != std::string::npos) {
Rucha Katakward9ea6452021-05-06 11:57:16 -07004052 mEventLog.add(msg);
4053 } else if(sServiceErrorEventSet.find(msg) == sServiceErrorEventSet.end()) {
4054 // Error event not added to the dumpsys log before
4055 mEventLog.add(msg);
4056 sServiceErrorEventSet.insert(msg);
4057 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004058}
4059
Austin Borgered99f642023-06-01 16:51:35 -07004060void CameraService::logDisconnected(const std::string &cameraId, int clientPid,
4061 const std::string &clientPackage) {
Ruben Brunkcc776712015-02-17 20:18:47 -08004062 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004063 logEvent(fmt::sprintf("DISCONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4064 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004065}
4066
Austin Borgered99f642023-06-01 16:51:35 -07004067void CameraService::logDisconnectedOffline(const std::string &cameraId, int clientPid,
4068 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004069 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004070 logEvent(fmt::sprintf("DISCONNECT offline device %s client for package %s (PID %d)",
4071 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004072}
4073
Austin Borgered99f642023-06-01 16:51:35 -07004074void CameraService::logConnected(const std::string &cameraId, int clientPid,
4075 const std::string &clientPackage) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004076 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004077 logEvent(fmt::sprintf("CONNECT device %s client for package %s (PID %d)", cameraId.c_str(),
4078 clientPackage.c_str(), clientPid));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004079}
4080
Austin Borgered99f642023-06-01 16:51:35 -07004081void CameraService::logConnectedOffline(const std::string &cameraId, int clientPid,
4082 const std::string &clientPackage) {
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004083 // Log the clients evicted
Austin Borgered99f642023-06-01 16:51:35 -07004084 logEvent(fmt::sprintf("CONNECT offline device %s client for package %s (PID %d)",
4085 cameraId.c_str(), clientPackage.c_str(), clientPid));
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004086}
4087
Austin Borgered99f642023-06-01 16:51:35 -07004088void CameraService::logRejected(const std::string &cameraId, int clientPid,
4089 const std::string &clientPackage, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004090 // Log the client rejected
Austin Borgered99f642023-06-01 16:51:35 -07004091 logEvent(fmt::sprintf("REJECT device %s client for package %s (PID %d), reason: (%s)",
4092 cameraId.c_str(), clientPackage.c_str(), clientPid, reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004093}
4094
Austin Borgered99f642023-06-01 16:51:35 -07004095void CameraService::logTorchEvent(const std::string &cameraId, const std::string &torchState,
4096 int clientPid) {
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004097 // Log torch event
Austin Borgered99f642023-06-01 16:51:35 -07004098 logEvent(fmt::sprintf("Torch for camera id %s turned %s for client PID %d", cameraId.c_str(),
4099 torchState.c_str(), clientPid));
Jayant Chowdhary0e2eefd2019-04-18 14:05:43 -07004100}
4101
Ruben Brunk6267b532015-04-30 17:44:07 -07004102void CameraService::logUserSwitch(const std::set<userid_t>& oldUserIds,
4103 const std::set<userid_t>& newUserIds) {
Austin Borgered99f642023-06-01 16:51:35 -07004104 std::string newUsers = toString(newUserIds);
4105 std::string oldUsers = toString(oldUserIds);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08004106 if (oldUsers.size() == 0) {
4107 oldUsers = "<None>";
4108 }
Ruben Brunka8ca9152015-04-07 14:23:40 -07004109 // Log the new and old users
Austin Borgered99f642023-06-01 16:51:35 -07004110 logEvent(fmt::sprintf("USER_SWITCH previous allowed user IDs: %s, current allowed user IDs: %s",
4111 oldUsers.c_str(), newUsers.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004112}
4113
Austin Borgered99f642023-06-01 16:51:35 -07004114void CameraService::logDeviceRemoved(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004115 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004116 logEvent(fmt::sprintf("REMOVE device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004117}
4118
Austin Borgered99f642023-06-01 16:51:35 -07004119void CameraService::logDeviceAdded(const std::string &cameraId, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004120 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004121 logEvent(fmt::sprintf("ADD device %s, reason: (%s)", cameraId.c_str(), reason.c_str()));
Ruben Brunka8ca9152015-04-07 14:23:40 -07004122}
4123
Austin Borgered99f642023-06-01 16:51:35 -07004124void CameraService::logClientDied(int clientPid, const std::string &reason) {
Ruben Brunka8ca9152015-04-07 14:23:40 -07004125 // Log the device removal
Austin Borgered99f642023-06-01 16:51:35 -07004126 logEvent(fmt::sprintf("DIED client(s) with PID %d, reason: (%s)", clientPid, reason.c_str()));
Igor Murashkinecf17e82012-10-02 16:05:11 -07004127}
4128
Austin Borgered99f642023-06-01 16:51:35 -07004129void CameraService::logServiceError(const std::string &msg, int errorCode) {
4130 logEvent(fmt::sprintf("SERVICE ERROR: %s : %d (%s)", msg.c_str(), errorCode,
4131 strerror(-errorCode)));
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07004132}
4133
Ruben Brunk36597b22015-03-20 22:15:57 -07004134status_t CameraService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4135 uint32_t flags) {
4136
Mathias Agopian65ab4712010-07-14 17:59:35 -07004137 // Permission checks
4138 switch (code) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004139 case SHELL_COMMAND_TRANSACTION: {
4140 int in = data.readFileDescriptor();
4141 int out = data.readFileDescriptor();
4142 int err = data.readFileDescriptor();
4143 int argc = data.readInt32();
4144 Vector<String16> args;
4145 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
4146 args.add(data.readString16());
4147 }
4148 sp<IBinder> unusedCallback;
4149 sp<IResultReceiver> resultReceiver;
4150 status_t status;
4151 if ((status = data.readNullableStrongBinder(&unusedCallback)) != NO_ERROR) {
4152 return status;
4153 }
4154 if ((status = data.readNullableStrongBinder(&resultReceiver)) != NO_ERROR) {
4155 return status;
4156 }
4157 status = shellCommand(in, out, err, args);
4158 if (resultReceiver != nullptr) {
4159 resultReceiver->send(status);
4160 }
4161 return NO_ERROR;
4162 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004163 }
4164
4165 return BnCameraService::onTransact(code, data, reply, flags);
4166}
4167
Mathias Agopian65ab4712010-07-14 17:59:35 -07004168// We share the media players for shutter and recording sound for all clients.
4169// A reference count is kept to determine when we will actually release the
4170// media players.
Jaekyun Seokef498052018-03-23 13:09:44 +09004171sp<MediaPlayer> CameraService::newMediaPlayer(const char *file) {
4172 sp<MediaPlayer> mp = new MediaPlayer();
4173 status_t error;
4174 if ((error = mp->setDataSource(NULL /* httpService */, file, NULL)) == NO_ERROR) {
Eino-Ville Talvala60a78ac2012-01-05 15:34:53 -08004175 mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
Jaekyun Seokef498052018-03-23 13:09:44 +09004176 error = mp->prepare();
4177 }
4178 if (error != NO_ERROR) {
Steve Block29357bc2012-01-06 19:20:56 +00004179 ALOGE("Failed to load CameraService sounds: %s", file);
Jaekyun Seokef498052018-03-23 13:09:44 +09004180 mp->disconnect();
4181 mp.clear();
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004182 return nullptr;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004183 }
4184 return mp;
4185}
4186
username5755fea2018-12-27 09:48:08 +08004187void CameraService::increaseSoundRef() {
4188 Mutex::Autolock lock(mSoundLock);
4189 mSoundRef++;
4190}
4191
4192void CameraService::loadSoundLocked(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004193 ATRACE_CALL();
4194
username5755fea2018-12-27 09:48:08 +08004195 LOG1("CameraService::loadSoundLocked ref=%d", mSoundRef);
4196 if (SOUND_SHUTTER == kind && mSoundPlayer[SOUND_SHUTTER] == NULL) {
4197 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/product/media/audio/ui/camera_click.ogg");
4198 if (mSoundPlayer[SOUND_SHUTTER] == nullptr) {
4199 mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
4200 }
4201 } else if (SOUND_RECORDING_START == kind && mSoundPlayer[SOUND_RECORDING_START] == NULL) {
4202 mSoundPlayer[SOUND_RECORDING_START] = newMediaPlayer("/product/media/audio/ui/VideoRecord.ogg");
4203 if (mSoundPlayer[SOUND_RECORDING_START] == nullptr) {
4204 mSoundPlayer[SOUND_RECORDING_START] =
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004205 newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
username5755fea2018-12-27 09:48:08 +08004206 }
4207 } else if (SOUND_RECORDING_STOP == kind && mSoundPlayer[SOUND_RECORDING_STOP] == NULL) {
4208 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/product/media/audio/ui/VideoStop.ogg");
4209 if (mSoundPlayer[SOUND_RECORDING_STOP] == nullptr) {
4210 mSoundPlayer[SOUND_RECORDING_STOP] = newMediaPlayer("/system/media/audio/ui/VideoStop.ogg");
4211 }
Jaekyun Seok59a8ef02018-01-15 14:49:05 +09004212 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07004213}
4214
username5755fea2018-12-27 09:48:08 +08004215void CameraService::decreaseSoundRef() {
Mathias Agopian65ab4712010-07-14 17:59:35 -07004216 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004217 LOG1("CameraService::decreaseSoundRef ref=%d", mSoundRef);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004218 if (--mSoundRef) return;
4219
4220 for (int i = 0; i < NUM_SOUNDS; i++) {
4221 if (mSoundPlayer[i] != 0) {
4222 mSoundPlayer[i]->disconnect();
4223 mSoundPlayer[i].clear();
4224 }
4225 }
4226}
4227
4228void CameraService::playSound(sound_kind kind) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004229 ATRACE_CALL();
4230
Mathias Agopian65ab4712010-07-14 17:59:35 -07004231 LOG1("playSound(%d)", kind);
Eino-Ville Talvala139ca752021-04-23 15:40:34 -07004232 if (kind < 0 || kind >= NUM_SOUNDS) {
4233 ALOGE("%s: Invalid sound id requested: %d", __FUNCTION__, kind);
4234 return;
4235 }
4236
Mathias Agopian65ab4712010-07-14 17:59:35 -07004237 Mutex::Autolock lock(mSoundLock);
username5755fea2018-12-27 09:48:08 +08004238 loadSoundLocked(kind);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004239 sp<MediaPlayer> player = mSoundPlayer[kind];
4240 if (player != 0) {
Chih-Chung Chang8888a752011-10-20 10:47:26 +08004241 player->seekTo(0);
4242 player->start();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004243 }
4244}
4245
4246// ----------------------------------------------------------------------------
4247
4248CameraService::Client::Client(const sp<CameraService>& cameraService,
Wu-cheng Lib7a67942010-08-17 15:45:37 -07004249 const sp<ICameraClient>& cameraClient,
Austin Borger249e6592024-03-10 22:28:11 -07004250 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004251 const std::string& clientPackageName, bool systemNativeClient,
4252 const std::optional<std::string>& clientFeatureId,
4253 const std::string& cameraIdStr,
Emilian Peev8b64f282021-03-25 16:49:57 -07004254 int api1CameraId, int cameraFacing, int sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004255 int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004256 int servicePid, bool overrideToPortrait) :
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004257 CameraService::BasicClient(cameraService,
Marco Nelissenf8880202014-11-14 07:58:25 -08004258 IInterface::asBinder(cameraClient),
Austin Borger249e6592024-03-10 22:28:11 -07004259 attributionAndPermissionUtils,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004260 clientPackageName, systemNativeClient, clientFeatureId,
Emilian Peev8b64f282021-03-25 16:49:57 -07004261 cameraIdStr, cameraFacing, sensorOrientation,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004262 clientPid, clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004263 servicePid, overrideToPortrait),
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08004264 mCameraId(api1CameraId)
Igor Murashkin634a5152013-02-20 17:15:11 -08004265{
Austin Borger22c5c852024-03-08 13:31:36 -08004266 int callingPid = getCallingPid();
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004267 LOG1("Client::Client E (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004268
Igor Murashkin44cfcf02013-03-01 16:22:28 -08004269 mRemoteCallback = cameraClient;
Mathias Agopian65ab4712010-07-14 17:59:35 -07004270
username5755fea2018-12-27 09:48:08 +08004271 cameraService->increaseSoundRef();
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004272
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004273 LOG1("Client::Client X (pid %d, id %d)", callingPid, mCameraId);
Mathias Agopian65ab4712010-07-14 17:59:35 -07004274}
4275
Mathias Agopian65ab4712010-07-14 17:59:35 -07004276// tear down the client
4277CameraService::Client::~Client() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004278 ALOGV("~Client");
Igor Murashkin634a5152013-02-20 17:15:11 -08004279 mDestructionStarted = true;
4280
username5755fea2018-12-27 09:48:08 +08004281 sCameraService->decreaseSoundRef();
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004282 // unconditionally disconnect. function is idempotent
4283 Client::disconnect();
Mathias Agopian65ab4712010-07-14 17:59:35 -07004284}
4285
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004286sp<CameraService> CameraService::BasicClient::BasicClient::sCameraService;
4287
Igor Murashkin634a5152013-02-20 17:15:11 -08004288CameraService::BasicClient::BasicClient(const sp<CameraService>& cameraService,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004289 const sp<IBinder>& remoteCallback,
Austin Borger249e6592024-03-10 22:28:11 -07004290 std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
Austin Borgered99f642023-06-01 16:51:35 -07004291 const std::string& clientPackageName, bool nativeClient,
4292 const std::optional<std::string>& clientFeatureId, const std::string& cameraIdStr,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004293 int cameraFacing, int sensorOrientation, int clientPid, uid_t clientUid,
Austin Borger18b30a72022-10-27 12:20:29 -07004294 int servicePid, bool overrideToPortrait):
Austin Borger249e6592024-03-10 22:28:11 -07004295 AttributionAndPermissionUtilsEncapsulator(attributionAndPermissionUtils),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004296 mDestructionStarted(false),
Emilian Peev8b64f282021-03-25 16:49:57 -07004297 mCameraIdStr(cameraIdStr), mCameraFacing(cameraFacing), mOrientation(sensorOrientation),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004298 mClientPackageName(clientPackageName), mSystemNativeClient(nativeClient),
4299 mClientFeatureId(clientFeatureId),
Philip P. Moltmann9e648f62019-11-04 12:52:45 -08004300 mClientPid(clientPid), mClientUid(clientUid),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004301 mServicePid(servicePid),
Shuzhen Wang2c656792020-04-13 17:36:49 -07004302 mDisconnected(false), mUidIsTrusted(false),
Austin Borger18b30a72022-10-27 12:20:29 -07004303 mOverrideToPortrait(overrideToPortrait),
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004304 mAudioRestriction(hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE),
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004305 mRemoteBinder(remoteCallback),
4306 mOpsActive(false),
4307 mOpsStreaming(false)
Igor Murashkin634a5152013-02-20 17:15:11 -08004308{
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004309 if (sCameraService == nullptr) {
4310 sCameraService = cameraService;
4311 }
Yin-Chia Yeh0dea57f2015-12-09 16:46:07 -08004312
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08004313 // There are 2 scenarios in which a client won't have AppOps operations
4314 // (both scenarios : native clients)
4315 // 1) It's an system native client*, the package name will be empty
4316 // and it will return from this function in the previous if condition
4317 // (This is the same as the previously existing behavior).
4318 // 2) It is a system native client, but its package name has been
4319 // modified for debugging, however it still must not use AppOps since
4320 // the package name is not a real one.
4321 //
4322 // * system native client - native client with UID < AID_APP_START. It
4323 // doesn't exclude clients not on the system partition.
4324 if (!mSystemNativeClient) {
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004325 mAppOpsManager = std::make_unique<AppOpsManager>();
4326 }
Shuzhen Wang2c656792020-04-13 17:36:49 -07004327
Charles Chenf075f082024-03-04 23:32:55 +00004328 mUidIsTrusted = isTrustedCallingUid(mClientUid);
Igor Murashkin634a5152013-02-20 17:15:11 -08004329}
4330
4331CameraService::BasicClient::~BasicClient() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004332 ALOGV("~BasicClient");
Igor Murashkin634a5152013-02-20 17:15:11 -08004333 mDestructionStarted = true;
4334}
4335
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004336binder::Status CameraService::BasicClient::disconnect() {
4337 binder::Status res = Status::ok();
Ruben Brunk36597b22015-03-20 22:15:57 -07004338 if (mDisconnected) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004339 return res;
Ruben Brunk36597b22015-03-20 22:15:57 -07004340 }
Eino-Ville Talvala24901c82015-09-04 14:15:58 -07004341 mDisconnected = true;
Ruben Brunkcc776712015-02-17 20:18:47 -08004342
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004343 sCameraService->removeByClient(this);
Austin Borgered99f642023-06-01 16:51:35 -07004344 sCameraService->logDisconnected(mCameraIdStr, mClientPid, mClientPackageName);
Peter Kalauskasa29c1352018-10-10 12:05:42 -07004345 sCameraService->mCameraProviderManager->removeRef(CameraProviderManager::DeviceMode::CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004346 mCameraIdStr);
Ruben Brunkcc776712015-02-17 20:18:47 -08004347
4348 sp<IBinder> remote = getRemote();
4349 if (remote != nullptr) {
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004350 remote->unlinkToDeath(sCameraService);
Ruben Brunkcc776712015-02-17 20:18:47 -08004351 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004352
4353 finishCameraOps();
Chien-Yu Chene4fe21b2016-08-04 12:42:40 -07004354 // Notify flashlight that a camera device is closed.
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004355 sCameraService->mFlashlight->deviceClosed(mCameraIdStr);
Austin Borgered99f642023-06-01 16:51:35 -07004356 ALOGI("%s: Disconnected client for camera %s for PID %d", __FUNCTION__, mCameraIdStr.c_str(),
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004357 mClientPid);
Ruben Brunkcc776712015-02-17 20:18:47 -08004358
Igor Murashkincba2c162013-03-20 15:56:31 -07004359 // client shouldn't be able to call into us anymore
4360 mClientPid = 0;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004361
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004362 const auto& mActivityManager = getActivityManager();
4363 if (mActivityManager) {
4364 mActivityManager->logFgsApiEnd(LOG_FGS_CAMERA_API,
Austin Borger22c5c852024-03-08 13:31:36 -08004365 getCallingUid(),
4366 getCallingPid());
Kunal Malhotrabfc96052023-02-28 23:25:34 +00004367 }
4368
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004369 return res;
Igor Murashkin634a5152013-02-20 17:15:11 -08004370}
4371
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004372status_t CameraService::BasicClient::dump(int, const Vector<String16>&) {
4373 // No dumping of clients directly over Binder,
4374 // must go through CameraService::dump
4375 android_errorWriteWithInfoLog(SN_EVENT_LOG_ID, "26265403",
Austin Borger22c5c852024-03-08 13:31:36 -08004376 getCallingUid(), NULL, 0);
Eino-Ville Talvalac4003962016-01-13 10:07:04 -08004377 return OK;
4378}
4379
Austin Borgered99f642023-06-01 16:51:35 -07004380status_t CameraService::BasicClient::startWatchingTags(const std::string&, int) {
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07004381 // Can't watch tags directly, must go through CameraService::startWatchingTags
4382 return OK;
4383}
4384
4385status_t CameraService::BasicClient::stopWatchingTags(int) {
4386 // Can't watch tags directly, must go through CameraService::stopWatchingTags
4387 return OK;
4388}
4389
4390status_t CameraService::BasicClient::dumpWatchedEventsToVector(std::vector<std::string> &) {
4391 // Can't watch tags directly, must go through CameraService::dumpWatchedEventsToVector
4392 return OK;
4393}
4394
Austin Borgered99f642023-06-01 16:51:35 -07004395std::string CameraService::BasicClient::getPackageName() const {
Svetoslav Ganov280405a2015-05-12 02:19:27 +00004396 return mClientPackageName;
Ruben Brunkcc776712015-02-17 20:18:47 -08004397}
4398
Emilian Peev8b64f282021-03-25 16:49:57 -07004399int CameraService::BasicClient::getCameraFacing() const {
4400 return mCameraFacing;
4401}
4402
4403int CameraService::BasicClient::getCameraOrientation() const {
4404 return mOrientation;
4405}
Ruben Brunkcc776712015-02-17 20:18:47 -08004406
4407int CameraService::BasicClient::getClientPid() const {
4408 return mClientPid;
4409}
4410
Ruben Brunk6267b532015-04-30 17:44:07 -07004411uid_t CameraService::BasicClient::getClientUid() const {
4412 return mClientUid;
4413}
4414
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004415bool CameraService::BasicClient::canCastToApiClient(apiLevel level) const {
4416 // Defaults to API2.
4417 return level == API_2;
4418}
4419
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004420status_t CameraService::BasicClient::setAudioRestriction(int32_t mode) {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004421 {
4422 Mutex::Autolock l(mAudioRestrictionLock);
4423 mAudioRestriction = mode;
4424 }
Yin-Chia Yehcfab4e12019-09-09 13:08:28 -07004425 sCameraService->updateAudioRestriction();
4426 return OK;
4427}
4428
4429int32_t CameraService::BasicClient::getServiceAudioRestriction() const {
Yin-Chia Yehdba03232019-08-19 15:54:28 -07004430 return sCameraService->updateAudioRestriction();
4431}
4432
4433int32_t CameraService::BasicClient::getAudioRestriction() const {
4434 Mutex::Autolock l(mAudioRestrictionLock);
4435 return mAudioRestriction;
4436}
4437
4438bool CameraService::BasicClient::isValidAudioRestriction(int32_t mode) {
4439 switch (mode) {
4440 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_NONE:
4441 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION:
4442 case hardware::camera2::ICameraDeviceUser::AUDIO_RESTRICTION_VIBRATION_SOUND:
4443 return true;
4444 default:
4445 return false;
4446 }
4447}
4448
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004449status_t CameraService::BasicClient::handleAppOpMode(int32_t mode) {
4450 if (mode == AppOpsManager::MODE_ERRORED) {
4451 ALOGI("Camera %s: Access for \"%s\" has been revoked",
Austin Borgered99f642023-06-01 16:51:35 -07004452 mCameraIdStr.c_str(), mClientPackageName.c_str());
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004453 return PERMISSION_DENIED;
4454 } else if (!mUidIsTrusted && mode == AppOpsManager::MODE_IGNORED) {
4455 // If the calling Uid is trusted (a native service), the AppOpsManager could
4456 // return MODE_IGNORED. Do not treat such case as error.
4457 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid,
4458 mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004459
4460 bool isCameraPrivacyEnabled;
4461 if (flags::camera_privacy_allowlist()) {
4462 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4463 toString16(mClientPackageName), std::string(), mClientPid, mClientUid);
4464 } else {
4465 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004466 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004467 }
Jyoti Bhayana8143e572023-01-09 08:46:49 -08004468 // We don't want to return EACCESS if the CameraPrivacy is enabled.
4469 // We prefer to successfully open the camera and perform camera muting
4470 // or blocking in connectHelper as handleAppOpMode can be called before the
4471 // connection has been fully established and at that time camera muting
4472 // capabilities are unknown.
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004473 if (!isUidActive || !isCameraPrivacyEnabled) {
Austin Borgerfd05d982024-04-22 15:54:50 -07004474 ALOGI("Camera %s: Access for \"%s\" has been restricted."
4475 "uid active: %s, privacy enabled: %s", mCameraIdStr.c_str(),
4476 mClientPackageName.c_str(), isUidActive ? "true" : "false",
4477 isCameraPrivacyEnabled ? "true" : "false");
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004478 // Return the same error as for device policy manager rejection
4479 return -EACCES;
4480 }
4481 }
4482 return OK;
4483}
4484
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004485status_t CameraService::BasicClient::startCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004486 ATRACE_CALL();
4487
Igor Murashkine6800ce2013-03-04 17:25:57 -08004488 {
4489 ALOGV("%s: Start camera ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004490 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Igor Murashkine6800ce2013-03-04 17:25:57 -08004491 }
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004492 if (mAppOpsManager != nullptr) {
4493 // Notify app ops that the camera is not available
4494 mOpsCallback = new OpsCallback(this);
Austin Borgerca1e0062023-06-28 11:32:55 -07004495
4496 if (flags::watch_foreground_changes()) {
4497 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
4498 toString16(mClientPackageName),
4499 AppOpsManager::WATCH_FOREGROUND_CHANGES, mOpsCallback);
4500 } else {
4501 mAppOpsManager->startWatchingMode(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004502 toString16(mClientPackageName), mOpsCallback);
Austin Borgerca1e0062023-06-28 11:32:55 -07004503 }
Igor Murashkine6800ce2013-03-04 17:25:57 -08004504
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004505 // Just check for camera acccess here on open - delay startOp until
4506 // camera frames start streaming in startCameraStreamingOps
4507 int32_t mode = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004508 toString16(mClientPackageName));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004509 status_t res = handleAppOpMode(mode);
4510 if (res != OK) {
4511 return res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004512 }
Svetoslav28e8ef72015-05-11 19:21:31 -07004513 }
4514
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004515 mOpsActive = true;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004516
4517 // Transition device availability listeners from PRESENT -> NOT_AVAILABLE
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004518 sCameraService->updateStatus(StatusInternal::NOT_AVAILABLE, mCameraIdStr);
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004519
Austin Borgerdddb7552023-03-30 17:53:01 -07004520 sCameraService->mUidPolicy->registerMonitorUid(mClientUid, /*openCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004521
Shuzhen Wang695044d2020-03-06 09:02:23 -08004522 // Notify listeners of camera open/close status
4523 sCameraService->updateOpenCloseStatus(mCameraIdStr, true/*open*/, mClientPackageName);
4524
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004525 return OK;
4526}
4527
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004528status_t CameraService::BasicClient::startCameraStreamingOps() {
4529 ATRACE_CALL();
4530
4531 if (!mOpsActive) {
4532 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4533 return INVALID_OPERATION;
4534 }
4535 if (mOpsStreaming) {
4536 ALOGV("%s: Streaming already active!", __FUNCTION__);
4537 return OK;
4538 }
4539
4540 ALOGV("%s: Start camera streaming ops, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004541 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004542
4543 if (mAppOpsManager != nullptr) {
4544 int32_t mode = mAppOpsManager->startOpNoThrow(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004545 toString16(mClientPackageName), /*startIfModeDefault*/ false,
4546 toString16(mClientFeatureId),
4547 toString16("start camera ") + toString16(mCameraIdStr));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004548 status_t res = handleAppOpMode(mode);
4549 if (res != OK) {
4550 return res;
4551 }
4552 }
4553
4554 mOpsStreaming = true;
4555
4556 return OK;
4557}
4558
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004559status_t CameraService::BasicClient::noteAppOp() {
4560 ATRACE_CALL();
4561
4562 ALOGV("%s: Start camera noteAppOp, package name = %s, client UID = %d",
Austin Borgered99f642023-06-01 16:51:35 -07004563 __FUNCTION__, mClientPackageName.c_str(), mClientUid);
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004564
4565 // noteAppOp is only used for when camera mute is not supported, in order
4566 // to trigger the sensor privacy "Unblock" dialog
4567 if (mAppOpsManager != nullptr) {
4568 int32_t mode = mAppOpsManager->noteOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004569 toString16(mClientPackageName), toString16(mClientFeatureId),
4570 toString16("start camera ") + toString16(mCameraIdStr));
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004571 status_t res = handleAppOpMode(mode);
4572 if (res != OK) {
4573 return res;
4574 }
4575 }
4576
4577 return OK;
4578}
4579
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004580status_t CameraService::BasicClient::finishCameraStreamingOps() {
4581 ATRACE_CALL();
4582
4583 if (!mOpsActive) {
4584 ALOGE("%s: Calling streaming start when not yet active", __FUNCTION__);
4585 return INVALID_OPERATION;
4586 }
4587 if (!mOpsStreaming) {
4588 ALOGV("%s: Streaming not active!", __FUNCTION__);
4589 return OK;
4590 }
4591
4592 if (mAppOpsManager != nullptr) {
4593 mAppOpsManager->finishOp(AppOpsManager::OP_CAMERA, mClientUid,
Austin Borgered99f642023-06-01 16:51:35 -07004594 toString16(mClientPackageName), toString16(mClientFeatureId));
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004595 mOpsStreaming = false;
4596 }
4597
4598 return OK;
4599}
4600
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004601status_t CameraService::BasicClient::finishCameraOps() {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004602 ATRACE_CALL();
4603
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004604 if (mOpsStreaming) {
4605 // Make sure we've notified everyone about camera stopping
4606 finishCameraStreamingOps();
4607 }
4608
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004609 // Check if startCameraOps succeeded, and if so, finish the camera op
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004610 if (mOpsActive) {
Eino-Ville Talvala178e8232021-04-16 18:41:39 -07004611 mOpsActive = false;
4612
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004613 // This function is called when a client disconnects. This should
4614 // release the camera, but actually only if it was in a proper
4615 // functional state, i.e. with status NOT_AVAILABLE
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08004616 std::initializer_list<StatusInternal> rejected = {StatusInternal::PRESENT,
Guennadi Liakhovetski151e3be2017-11-28 16:34:18 +01004617 StatusInternal::ENUMERATING, StatusInternal::NOT_PRESENT};
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004618
Ruben Brunkcc776712015-02-17 20:18:47 -08004619 // Transition to PRESENT if the camera is not in either of the rejected states
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -08004620 sCameraService->updateStatus(StatusInternal::PRESENT,
4621 mCameraIdStr, rejected);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004622 }
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -07004623 // Always stop watching, even if no camera op is active
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004624 if (mOpsCallback != nullptr && mAppOpsManager != nullptr) {
4625 mAppOpsManager->stopWatchingMode(mOpsCallback);
Eino-Ville Talvalae992e752014-11-07 16:17:48 -08004626 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004627 mOpsCallback.clear();
4628
Austin Borgerdddb7552023-03-30 17:53:01 -07004629 sCameraService->mUidPolicy->unregisterMonitorUid(mClientUid, /*closeCamera*/true);
Emilian Peev53722fa2019-02-22 17:47:20 -08004630
Shuzhen Wang695044d2020-03-06 09:02:23 -08004631 // Notify listeners of camera open/close status
4632 sCameraService->updateOpenCloseStatus(mCameraIdStr, false/*open*/, mClientPackageName);
4633
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004634 return OK;
4635}
4636
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004637void CameraService::BasicClient::opChanged(int32_t op, const String16&) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07004638 ATRACE_CALL();
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004639 if (mAppOpsManager == nullptr) {
4640 return;
4641 }
Emilian Peevb2bc5a42019-11-20 16:02:14 -08004642 // TODO : add offline camera session case
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004643 if (op != AppOpsManager::OP_CAMERA) {
4644 ALOGW("Unexpected app ops notification received: %d", op);
4645 return;
4646 }
4647
4648 int32_t res;
Jayant Chowdharyb61526c2019-05-13 19:37:42 -07004649 res = mAppOpsManager->checkOp(AppOpsManager::OP_CAMERA,
Austin Borgered99f642023-06-01 16:51:35 -07004650 mClientUid, toString16(mClientPackageName));
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004651 ALOGV("checkOp returns: %d, %s ", res,
4652 res == AppOpsManager::MODE_ALLOWED ? "ALLOWED" :
4653 res == AppOpsManager::MODE_IGNORED ? "IGNORED" :
4654 res == AppOpsManager::MODE_ERRORED ? "ERRORED" :
4655 "UNKNOWN");
4656
Shuzhen Wang64900852021-02-05 09:03:29 -08004657 if (res == AppOpsManager::MODE_ERRORED) {
Austin Borgered99f642023-06-01 16:51:35 -07004658 ALOGI("Camera %s: Access for \"%s\" revoked", mCameraIdStr.c_str(),
4659 mClientPackageName.c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08004660 block();
Shuzhen Wang64900852021-02-05 09:03:29 -08004661 } else if (res == AppOpsManager::MODE_IGNORED) {
4662 bool isUidActive = sCameraService->mUidPolicy->isUidActive(mClientUid, mClientPackageName);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004663
Austin Borgerca1e0062023-06-28 11:32:55 -07004664 // Uid may be active, but not visible to the user (e.g. PROCESS_STATE_FOREGROUND_SERVICE).
4665 // If not visible, but still active, then we want to block instead of muting the camera.
4666 int32_t procState = sCameraService->mUidPolicy->getProcState(mClientUid);
4667 bool isUidVisible = (procState <= ActivityManager::PROCESS_STATE_BOUND_TOP);
4668
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004669 bool isCameraPrivacyEnabled;
4670 if (flags::camera_privacy_allowlist()) {
4671 isCameraPrivacyEnabled = sCameraService->isCameraPrivacyEnabled(
4672 toString16(mClientPackageName),std::string(),mClientPid,mClientUid);
4673 } else {
4674 isCameraPrivacyEnabled =
Evan Seversond0b69922022-01-27 10:47:34 -08004675 sCameraService->mSensorPrivacyPolicy->isCameraPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00004676 }
4677
4678 ALOGI("Camera %s: Access for \"%s\" has been restricted, isUidTrusted %d, isUidActive %d"
Austin Borgerca1e0062023-06-28 11:32:55 -07004679 " isUidVisible %d, isCameraPrivacyEnabled %d", mCameraIdStr.c_str(),
4680 mClientPackageName.c_str(), mUidIsTrusted, isUidActive, isUidVisible,
4681 isCameraPrivacyEnabled);
4682 // If the calling Uid is trusted (a native service), or the client Uid is active / visible
4683 // (WAR for b/175320666)the AppOpsManager could return MODE_IGNORED. Do not treat such
4684 // cases as error.
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004685 if (!mUidIsTrusted) {
Austin Borgerca1e0062023-06-28 11:32:55 -07004686 if (flags::watch_foreground_changes()) {
4687 if (isUidVisible && isCameraPrivacyEnabled && supportsCameraMute()) {
4688 setCameraMute(true);
4689 } else {
4690 block();
4691 }
4692 } else {
4693 if (isUidActive && isCameraPrivacyEnabled && supportsCameraMute()) {
4694 setCameraMute(true);
4695 } else if (!isUidActive
4696 || (isCameraPrivacyEnabled && !supportsCameraMute())) {
4697 block();
4698 }
Valentin Iftimec0b8d472021-07-23 20:21:06 +02004699 }
Shuzhen Wang64900852021-02-05 09:03:29 -08004700 }
Evan Severson09ab4002021-02-10 14:15:19 -08004701 } else if (res == AppOpsManager::MODE_ALLOWED) {
4702 setCameraMute(sCameraService->mOverrideCameraMuteMode);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004703 }
4704}
4705
Svet Ganova453d0d2018-01-11 15:37:58 -08004706void CameraService::BasicClient::block() {
4707 ATRACE_CALL();
4708
4709 // Reset the client PID to allow server-initiated disconnect,
4710 // and to prevent further calls by client.
Austin Borger22c5c852024-03-08 13:31:36 -08004711 mClientPid = getCallingPid();
Svet Ganova453d0d2018-01-11 15:37:58 -08004712 CaptureResultExtras resultExtras; // a dummy result (invalid)
4713 notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED, resultExtras);
4714 disconnect();
4715}
4716
Mathias Agopian65ab4712010-07-14 17:59:35 -07004717// ----------------------------------------------------------------------------
4718
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004719void CameraService::Client::notifyError(int32_t errorCode,
Jing Mikec7f9b132023-03-12 11:12:04 +08004720 [[maybe_unused]] const CaptureResultExtras& resultExtras) {
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004721 if (mRemoteCallback != NULL) {
Yin-Chia Yehf13bda52018-05-31 12:12:59 -07004722 int32_t api1ErrorCode = CAMERA_ERROR_RELEASED;
4723 if (errorCode == hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISABLED) {
4724 api1ErrorCode = CAMERA_ERROR_DISABLED;
4725 }
4726 mRemoteCallback->notifyCallback(CAMERA_MSG_ERROR, api1ErrorCode, 0);
Ranjith Kagathi Ananda3e600892015-10-08 16:00:33 -07004727 } else {
4728 ALOGE("mRemoteCallback is NULL!!");
4729 }
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004730}
4731
Igor Murashkin036bc3e2012-10-08 15:09:46 -07004732// NOTE: function is idempotent
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004733binder::Status CameraService::Client::disconnect() {
Eino-Ville Talvalad09801b2013-04-23 15:16:57 -07004734 ALOGV("Client::disconnect");
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004735 return BasicClient::disconnect();
Wu-cheng Lie09591e2010-10-14 20:17:44 +08004736}
4737
Ruben Brunk0bbf8b22015-04-30 14:35:42 -07004738bool CameraService::Client::canCastToApiClient(apiLevel level) const {
4739 return level == API_1;
4740}
4741
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -08004742CameraService::Client::OpsCallback::OpsCallback(wp<BasicClient> client):
4743 mClient(client) {
4744}
4745
4746void CameraService::Client::OpsCallback::opChanged(int32_t op,
4747 const String16& packageName) {
4748 sp<BasicClient> client = mClient.promote();
4749 if (client != NULL) {
4750 client->opChanged(op, packageName);
4751 }
4752}
4753
Mathias Agopian65ab4712010-07-14 17:59:35 -07004754// ----------------------------------------------------------------------------
Svet Ganova453d0d2018-01-11 15:37:58 -08004755// UidPolicy
4756// ----------------------------------------------------------------------------
4757
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004758void CameraService::UidPolicy::registerWithActivityManager() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004759 Mutex::Autolock _l(mUidLock);
Austin Borgerd0309d42023-04-21 20:07:18 -07004760 int32_t emptyUidArray[] = { };
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004761
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004762 if (mRegistered) return;
Steven Moreland2f348142019-07-02 15:59:07 -07004763 status_t res = mAm.linkToDeath(this);
Austin Borgerd0309d42023-04-21 20:07:18 -07004764 mAm.registerUidObserverForUids(this, ActivityManager::UID_OBSERVER_GONE
Svet Ganova453d0d2018-01-11 15:37:58 -08004765 | ActivityManager::UID_OBSERVER_IDLE
Austin Borger65577682022-02-17 00:25:43 +00004766 | ActivityManager::UID_OBSERVER_ACTIVE | ActivityManager::UID_OBSERVER_PROCSTATE
4767 | ActivityManager::UID_OBSERVER_PROC_OOM_ADJ,
Svet Ganova453d0d2018-01-11 15:37:58 -08004768 ActivityManager::PROCESS_STATE_UNKNOWN,
Austin Borgered99f642023-06-01 16:51:35 -07004769 toString16(kServiceName), emptyUidArray, 0, mObserverToken);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004770 if (res == OK) {
4771 mRegistered = true;
4772 ALOGV("UidPolicy: Registered with ActivityManager");
Austin Borgerd0309d42023-04-21 20:07:18 -07004773 } else {
4774 ALOGE("UidPolicy: Failed to register with ActivityManager: 0x%08x", res);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004775 }
Svet Ganova453d0d2018-01-11 15:37:58 -08004776}
4777
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004778void CameraService::UidPolicy::onServiceRegistration(const String16& name, const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07004779 if (name != toString16(kActivityServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004780 return;
4781 }
4782
4783 registerWithActivityManager();
4784}
4785
4786void CameraService::UidPolicy::registerSelf() {
4787 // Use check service to see if the activity service is available
4788 // If not available then register for notifications, instead of blocking
4789 // till the service is ready
4790 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07004791 sp<IBinder> binder = sm->checkService(toString16(kActivityServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004792 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07004793 sm->registerForNotifications(toString16(kActivityServiceName), this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08004794 } else {
4795 registerWithActivityManager();
4796 }
4797}
4798
Svet Ganova453d0d2018-01-11 15:37:58 -08004799void CameraService::UidPolicy::unregisterSelf() {
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004800 Mutex::Autolock _l(mUidLock);
4801
Steven Moreland2f348142019-07-02 15:59:07 -07004802 mAm.unregisterUidObserver(this);
4803 mAm.unlinkToDeath(this);
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004804 mRegistered = false;
4805 mActiveUids.clear();
4806 ALOGV("UidPolicy: Unregistered with ActivityManager");
Svet Ganova453d0d2018-01-11 15:37:58 -08004807}
4808
4809void CameraService::UidPolicy::onUidGone(uid_t uid, bool disabled) {
4810 onUidIdle(uid, disabled);
4811}
4812
4813void CameraService::UidPolicy::onUidActive(uid_t uid) {
4814 Mutex::Autolock _l(mUidLock);
4815 mActiveUids.insert(uid);
4816}
4817
4818void CameraService::UidPolicy::onUidIdle(uid_t uid, bool /* disabled */) {
4819 bool deleted = false;
4820 {
4821 Mutex::Autolock _l(mUidLock);
4822 if (mActiveUids.erase(uid) > 0) {
4823 deleted = true;
4824 }
4825 }
4826 if (deleted) {
4827 sp<CameraService> service = mService.promote();
4828 if (service != nullptr) {
4829 service->blockClientsForUid(uid);
4830 }
4831 }
4832}
4833
Emilian Peev53722fa2019-02-22 17:47:20 -08004834void CameraService::UidPolicy::onUidStateChanged(uid_t uid, int32_t procState,
Hui Yu13ad0eb2019-09-09 10:27:07 -07004835 int64_t procStateSeq __unused, int32_t capability __unused) {
Austin Borgerc5585dc2022-05-12 00:48:17 +00004836 bool procStateChange = false;
4837 {
4838 Mutex::Autolock _l(mUidLock);
4839 if (mMonitoredUids.find(uid) != mMonitoredUids.end() &&
4840 mMonitoredUids[uid].procState != procState) {
4841 mMonitoredUids[uid].procState = procState;
4842 procStateChange = true;
4843 }
4844 }
4845
4846 if (procStateChange) {
4847 sp<CameraService> service = mService.promote();
4848 if (service != nullptr) {
4849 service->notifyMonitoredUids();
4850 }
Emilian Peev53722fa2019-02-22 17:47:20 -08004851 }
4852}
4853
Austin Borgerdddb7552023-03-30 17:53:01 -07004854/**
4855 * When the OOM adj of the uid owning the camera changes, a different uid waiting on camera
4856 * privileges may take precedence if the owner's new OOM adj is greater than the waiting package.
4857 * Here, we track which monitoredUid has the camera, and track its adj relative to other
4858 * monitoredUids. If it is revised above some other monitoredUid, signal
4859 * onCameraAccessPrioritiesChanged. This only needs to capture the case where there are two
4860 * foreground apps in split screen - state changes will capture all other cases.
4861 */
4862void CameraService::UidPolicy::onUidProcAdjChanged(uid_t uid, int32_t adj) {
4863 std::unordered_set<uid_t> notifyUidSet;
Austin Borger65577682022-02-17 00:25:43 +00004864 {
4865 Mutex::Autolock _l(mUidLock);
Austin Borgerdddb7552023-03-30 17:53:01 -07004866 auto it = mMonitoredUids.find(uid);
4867
4868 if (it != mMonitoredUids.end()) {
4869 if (it->second.hasCamera) {
4870 for (auto &monitoredUid : mMonitoredUids) {
4871 if (monitoredUid.first != uid && adj > monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004872 ALOGV("%s: notify uid %d", __FUNCTION__, monitoredUid.first);
Austin Borgerdddb7552023-03-30 17:53:01 -07004873 notifyUidSet.emplace(monitoredUid.first);
4874 }
4875 }
Austin Borgerd0309d42023-04-21 20:07:18 -07004876 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004877 notifyUidSet.emplace(uid);
4878 } else {
4879 for (auto &monitoredUid : mMonitoredUids) {
4880 if (monitoredUid.second.hasCamera && adj < monitoredUid.second.procAdj) {
Austin Borgerd0309d42023-04-21 20:07:18 -07004881 ALOGV("%s: notify uid %d", __FUNCTION__, uid);
Austin Borgerdddb7552023-03-30 17:53:01 -07004882 notifyUidSet.emplace(uid);
4883 }
4884 }
4885 }
4886 it->second.procAdj = adj;
Austin Borger65577682022-02-17 00:25:43 +00004887 }
4888 }
4889
Austin Borgerdddb7552023-03-30 17:53:01 -07004890 if (notifyUidSet.size() > 0) {
Austin Borger65577682022-02-17 00:25:43 +00004891 sp<CameraService> service = mService.promote();
4892 if (service != nullptr) {
Austin Borgerdddb7552023-03-30 17:53:01 -07004893 service->notifyMonitoredUids(notifyUidSet);
Austin Borger65577682022-02-17 00:25:43 +00004894 }
4895 }
4896}
4897
Austin Borgerdddb7552023-03-30 17:53:01 -07004898/**
4899 * Register a uid for monitoring, and note whether it owns a camera.
4900 */
4901void CameraService::UidPolicy::registerMonitorUid(uid_t uid, bool openCamera) {
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++;
Emilian Peev53722fa2019-02-22 17:47:20 -08004906 } else {
Austin Borger65577682022-02-17 00:25:43 +00004907 MonitoredUid monitoredUid;
4908 monitoredUid.procState = ActivityManager::PROCESS_STATE_NONEXISTENT;
Austin Borgerdddb7552023-03-30 17:53:01 -07004909 monitoredUid.procAdj = resource_policy::UNKNOWN_ADJ;
Austin Borger65577682022-02-17 00:25:43 +00004910 monitoredUid.refCount = 1;
Austin Borgerdddb7552023-03-30 17:53:01 -07004911 it = mMonitoredUids.emplace(std::pair<uid_t, MonitoredUid>(uid, monitoredUid)).first;
Austin Borgered99f642023-06-01 16:51:35 -07004912 status_t res = mAm.addUidToObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004913 if (res != OK) {
4914 ALOGE("UidPolicy: Failed to add uid to observer: 0x%08x", res);
4915 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004916 }
4917
4918 if (openCamera) {
4919 it->second.hasCamera = true;
Emilian Peev53722fa2019-02-22 17:47:20 -08004920 }
4921}
4922
Austin Borgerdddb7552023-03-30 17:53:01 -07004923/**
4924 * Unregister a uid for monitoring, and note whether it lost ownership of a camera.
4925 */
4926void CameraService::UidPolicy::unregisterMonitorUid(uid_t uid, bool closeCamera) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004927 Mutex::Autolock _l(mUidLock);
4928 auto it = mMonitoredUids.find(uid);
4929 if (it != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00004930 it->second.refCount--;
4931 if (it->second.refCount == 0) {
Emilian Peev53722fa2019-02-22 17:47:20 -08004932 mMonitoredUids.erase(it);
Austin Borgered99f642023-06-01 16:51:35 -07004933 status_t res = mAm.removeUidFromObserver(mObserverToken, toString16(kServiceName), uid);
Austin Borgerd0309d42023-04-21 20:07:18 -07004934 if (res != OK) {
4935 ALOGE("UidPolicy: Failed to remove uid from observer: 0x%08x", res);
4936 }
Austin Borgerdddb7552023-03-30 17:53:01 -07004937 } else if (closeCamera) {
4938 it->second.hasCamera = false;
Emilian Peev53722fa2019-02-22 17:47:20 -08004939 }
4940 } else {
4941 ALOGE("%s: Trying to unregister uid: %d which is not monitored!", __FUNCTION__, uid);
4942 }
4943}
4944
Austin Borgered99f642023-06-01 16:51:35 -07004945bool CameraService::UidPolicy::isUidActive(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004946 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07004947 return isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08004948}
4949
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004950static const int64_t kPollUidActiveTimeoutTotalMillis = 300;
4951static const int64_t kPollUidActiveTimeoutMillis = 50;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004952
Austin Borgered99f642023-06-01 16:51:35 -07004953bool CameraService::UidPolicy::isUidActiveLocked(uid_t uid, const std::string &callingPackage) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004954 // Non-app UIDs are considered always active
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07004955 // If activity manager is unreachable, assume everything is active
4956 if (uid < FIRST_APPLICATION_UID || !mRegistered) {
Svet Ganova453d0d2018-01-11 15:37:58 -08004957 return true;
4958 }
4959 auto it = mOverrideUids.find(uid);
4960 if (it != mOverrideUids.end()) {
4961 return it->second;
4962 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07004963 bool active = mActiveUids.find(uid) != mActiveUids.end();
4964 if (!active) {
4965 // We want active UIDs to always access camera with their first attempt since
4966 // there is no guarantee the app is robustly written and would retry getting
4967 // the camera on failure. The inverse case is not a problem as we would take
4968 // camera away soon once we get the callback that the uid is no longer active.
4969 ActivityManager am;
4970 // Okay to access with a lock held as UID changes are dispatched without
4971 // a lock and we are a higher level component.
Svet Ganov94ec46f2018-06-08 15:03:46 -07004972 int64_t startTimeMillis = 0;
4973 do {
4974 // TODO: Fix this b/109950150!
4975 // Okay this is a hack. There is a race between the UID turning active and
4976 // activity being resumed. The proper fix is very risky, so we temporary add
4977 // some polling which should happen pretty rarely anyway as the race is hard
4978 // to hit.
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004979 active = mActiveUids.find(uid) != mActiveUids.end();
Austin Borgered99f642023-06-01 16:51:35 -07004980 if (!active) active = am.isUidActive(uid, toString16(callingPackage));
Svet Ganov94ec46f2018-06-08 15:03:46 -07004981 if (active) {
4982 break;
4983 }
4984 if (startTimeMillis <= 0) {
4985 startTimeMillis = uptimeMillis();
4986 }
4987 int64_t ellapsedTimeMillis = uptimeMillis() - startTimeMillis;
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004988 int64_t remainingTimeMillis = kPollUidActiveTimeoutTotalMillis - ellapsedTimeMillis;
Svet Ganov94ec46f2018-06-08 15:03:46 -07004989 if (remainingTimeMillis <= 0) {
4990 break;
4991 }
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004992 remainingTimeMillis = std::min(kPollUidActiveTimeoutMillis, remainingTimeMillis);
4993
4994 mUidLock.unlock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004995 usleep(remainingTimeMillis * 1000);
Eino-Ville Talvala32b8c202018-08-20 10:27:58 -07004996 mUidLock.lock();
Svet Ganov94ec46f2018-06-08 15:03:46 -07004997 } while (true);
4998
Svet Ganov7b4ab782018-03-25 12:48:10 -07004999 if (active) {
5000 // Now that we found out the UID is actually active, cache that
5001 mActiveUids.insert(uid);
5002 }
5003 }
5004 return active;
Svet Ganova453d0d2018-01-11 15:37:58 -08005005}
5006
Varun Shahb42f1eb2019-04-16 14:45:13 -07005007int32_t CameraService::UidPolicy::getProcState(uid_t uid) {
5008 Mutex::Autolock _l(mUidLock);
5009 return getProcStateLocked(uid);
5010}
5011
5012int32_t CameraService::UidPolicy::getProcStateLocked(uid_t uid) {
5013 int32_t procState = ActivityManager::PROCESS_STATE_UNKNOWN;
5014 if (mMonitoredUids.find(uid) != mMonitoredUids.end()) {
Austin Borger65577682022-02-17 00:25:43 +00005015 procState = mMonitoredUids[uid].procState;
Varun Shahb42f1eb2019-04-16 14:45:13 -07005016 }
5017 return procState;
5018}
5019
Austin Borgered99f642023-06-01 16:51:35 -07005020void CameraService::UidPolicy::addOverrideUid(uid_t uid,
5021 const std::string &callingPackage, bool active) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005022 updateOverrideUid(uid, callingPackage, active, true);
Svet Ganova453d0d2018-01-11 15:37:58 -08005023}
5024
Austin Borgered99f642023-06-01 16:51:35 -07005025void CameraService::UidPolicy::removeOverrideUid(uid_t uid, const std::string &callingPackage) {
Svet Ganov7b4ab782018-03-25 12:48:10 -07005026 updateOverrideUid(uid, callingPackage, false, false);
Svet Ganova453d0d2018-01-11 15:37:58 -08005027}
5028
Eino-Ville Talvala8abec3f2018-03-20 11:07:00 -07005029void CameraService::UidPolicy::binderDied(const wp<IBinder>& /*who*/) {
5030 Mutex::Autolock _l(mUidLock);
5031 ALOGV("UidPolicy: ActivityManager has died");
5032 mRegistered = false;
5033 mActiveUids.clear();
5034}
5035
Austin Borgered99f642023-06-01 16:51:35 -07005036void CameraService::UidPolicy::updateOverrideUid(uid_t uid, const std::string &callingPackage,
Svet Ganov7b4ab782018-03-25 12:48:10 -07005037 bool active, bool insert) {
Svet Ganova453d0d2018-01-11 15:37:58 -08005038 bool wasActive = false;
5039 bool isActive = false;
5040 {
5041 Mutex::Autolock _l(mUidLock);
Svet Ganov7b4ab782018-03-25 12:48:10 -07005042 wasActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005043 mOverrideUids.erase(uid);
5044 if (insert) {
5045 mOverrideUids.insert(std::pair<uid_t, bool>(uid, active));
5046 }
Svet Ganov7b4ab782018-03-25 12:48:10 -07005047 isActive = isUidActiveLocked(uid, callingPackage);
Svet Ganova453d0d2018-01-11 15:37:58 -08005048 }
5049 if (wasActive != isActive && !isActive) {
5050 sp<CameraService> service = mService.promote();
5051 if (service != nullptr) {
5052 service->blockClientsForUid(uid);
5053 }
5054 }
5055}
5056
5057// ----------------------------------------------------------------------------
Michael Grooverd1d435a2018-12-18 17:39:42 -08005058// SensorPrivacyPolicy
5059// ----------------------------------------------------------------------------
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005060
5061void CameraService::SensorPrivacyPolicy::registerWithSensorPrivacyManager()
5062{
Michael Grooverd1d435a2018-12-18 17:39:42 -08005063 Mutex::Autolock _l(mSensorPrivacyLock);
5064 if (mRegistered) {
5065 return;
5066 }
Evan Severson09ab4002021-02-10 14:15:19 -08005067 hasCameraPrivacyFeature(); // Called so the result is cached
Steven Moreland3cf67172020-01-29 11:44:22 -08005068 mSpm.addSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005069 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005070 mSpm.addToggleSensorPrivacyListener(this);
5071 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005072 mSensorPrivacyEnabled = mSpm.isSensorPrivacyEnabled();
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005073 if (flags::camera_privacy_allowlist()) {
5074 mCameraPrivacyState = mSpm.getToggleSensorPrivacyState(
5075 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE,
5076 SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5077 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005078 status_t res = mSpm.linkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005079 if (res == OK) {
5080 mRegistered = true;
5081 ALOGV("SensorPrivacyPolicy: Registered with SensorPrivacyManager");
5082 }
5083}
5084
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005085void CameraService::SensorPrivacyPolicy::onServiceRegistration(const String16& name,
5086 const sp<IBinder>&) {
Austin Borgered99f642023-06-01 16:51:35 -07005087 if (name != toString16(kSensorPrivacyServiceName)) {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005088 return;
5089 }
5090
5091 registerWithSensorPrivacyManager();
5092}
5093
5094void CameraService::SensorPrivacyPolicy::registerSelf() {
5095 // Use checkservice to see if the sensor_privacy service is available
5096 // If service is not available then register for notification
5097 sp<IServiceManager> sm = defaultServiceManager();
Austin Borgered99f642023-06-01 16:51:35 -07005098 sp<IBinder> binder = sm->checkService(toString16(kSensorPrivacyServiceName));
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005099 if (!binder) {
Austin Borgered99f642023-06-01 16:51:35 -07005100 sm->registerForNotifications(toString16(kSensorPrivacyServiceName),this);
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005101 } else {
5102 registerWithSensorPrivacyManager();
5103 }
5104}
5105
Michael Grooverd1d435a2018-12-18 17:39:42 -08005106void CameraService::SensorPrivacyPolicy::unregisterSelf() {
5107 Mutex::Autolock _l(mSensorPrivacyLock);
Steven Moreland3cf67172020-01-29 11:44:22 -08005108 mSpm.removeSensorPrivacyListener(this);
Charles Chenf075f082024-03-04 23:32:55 +00005109 if (isAutomotiveDevice()) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005110 mSpm.removeToggleSensorPrivacyListener(this);
5111 }
Steven Moreland3cf67172020-01-29 11:44:22 -08005112 mSpm.unlinkToDeath(this);
Michael Grooverd1d435a2018-12-18 17:39:42 -08005113 mRegistered = false;
5114 ALOGV("SensorPrivacyPolicy: Unregistered with SensorPrivacyManager");
5115}
5116
5117bool CameraService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
Jyoti Bhayanacde601c2022-12-07 10:03:42 -08005118 if (!mRegistered) {
5119 registerWithSensorPrivacyManager();
5120 }
5121
Michael Grooverd1d435a2018-12-18 17:39:42 -08005122 Mutex::Autolock _l(mSensorPrivacyLock);
5123 return mSensorPrivacyEnabled;
5124}
5125
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005126int CameraService::SensorPrivacyPolicy::getCameraPrivacyState() {
5127 if (!mRegistered) {
5128 registerWithSensorPrivacyManager();
5129 }
5130
5131 Mutex::Autolock _l(mSensorPrivacyLock);
5132 return mCameraPrivacyState;
5133}
5134
Evan Seversond0b69922022-01-27 10:47:34 -08005135bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled() {
Evan Severson09ab4002021-02-10 14:15:19 -08005136 if (!hasCameraPrivacyFeature()) {
5137 return false;
5138 }
Evan Seversond0b69922022-01-27 10:47:34 -08005139 return mSpm.isToggleSensorPrivacyEnabled(SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
Evan Severson09ab4002021-02-10 14:15:19 -08005140}
5141
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005142bool CameraService::SensorPrivacyPolicy::isCameraPrivacyEnabled(const String16& packageName) {
5143 if (!hasCameraPrivacyFeature()) {
5144 return SensorPrivacyManager::DISABLED;
5145 }
5146 return mSpm.isCameraPrivacyEnabled(packageName);
5147}
5148
Evan Seversond0b69922022-01-27 10:47:34 -08005149binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyChanged(
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005150 int toggleType, int sensor, bool enabled) {
5151 if ((toggleType == SensorPrivacyManager::TOGGLE_TYPE_UNKNOWN)
5152 && (sensor == SensorPrivacyManager::TOGGLE_SENSOR_UNKNOWN)) {
5153 {
5154 Mutex::Autolock _l(mSensorPrivacyLock);
5155 mSensorPrivacyEnabled = enabled;
5156 }
5157 // if sensor privacy is enabled then block all clients from accessing the camera
5158 if (enabled) {
5159 sp<CameraService> service = mService.promote();
5160 if (service != nullptr) {
5161 service->blockAllClients();
5162 }
5163 }
5164 }
5165 return binder::Status::ok();
5166}
5167
5168binder::Status CameraService::SensorPrivacyPolicy::onSensorPrivacyStateChanged(
5169 int, int sensor, int state) {
5170 if (!flags::camera_privacy_allowlist()
5171 || (sensor != SensorPrivacyManager::TOGGLE_SENSOR_CAMERA)) {
5172 return binder::Status::ok();
5173 }
Michael Grooverd1d435a2018-12-18 17:39:42 -08005174 {
5175 Mutex::Autolock _l(mSensorPrivacyLock);
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005176 mCameraPrivacyState = state;
5177 }
5178 sp<CameraService> service = mService.promote();
5179 if (!service) {
5180 return binder::Status::ok();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005181 }
5182 // if sensor privacy is enabled then block all clients from accessing the camera
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005183 if (state == SensorPrivacyManager::ENABLED) {
5184 service->blockAllClients();
Jyoti Bhayana54a4b002024-02-27 15:36:09 -08005185 } else if (state == SensorPrivacyManager::ENABLED_EXCEPT_ALLOWLISTED_APPS) {
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00005186 service->blockPrivacyEnabledClients();
Michael Grooverd1d435a2018-12-18 17:39:42 -08005187 }
5188 return binder::Status::ok();
5189}
5190
5191void CameraService::SensorPrivacyPolicy::binderDied(const wp<IBinder>& /*who*/) {
5192 Mutex::Autolock _l(mSensorPrivacyLock);
5193 ALOGV("SensorPrivacyPolicy: SensorPrivacyManager has died");
5194 mRegistered = false;
5195}
5196
Evan Severson09ab4002021-02-10 14:15:19 -08005197bool CameraService::SensorPrivacyPolicy::hasCameraPrivacyFeature() {
Evan Seversond0b69922022-01-27 10:47:34 -08005198 bool supportsSoftwareToggle = mSpm.supportsSensorToggle(
5199 SensorPrivacyManager::TOGGLE_TYPE_SOFTWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5200 bool supportsHardwareToggle = mSpm.supportsSensorToggle(
5201 SensorPrivacyManager::TOGGLE_TYPE_HARDWARE, SensorPrivacyManager::TOGGLE_SENSOR_CAMERA);
5202 return supportsSoftwareToggle || supportsHardwareToggle;
Evan Severson09ab4002021-02-10 14:15:19 -08005203}
5204
Michael Grooverd1d435a2018-12-18 17:39:42 -08005205// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005206// CameraState
5207// ----------------------------------------------------------------------------
5208
Austin Borgered99f642023-06-01 16:51:35 -07005209CameraService::CameraState::CameraState(const std::string& id, int cost,
5210 const std::set<std::string>& conflicting, SystemCameraKind systemCameraKind,
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005211 const std::vector<std::string>& physicalCameras) : mId(id),
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005212 mStatus(StatusInternal::NOT_PRESENT), mCost(cost), mConflicting(conflicting),
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005213 mSystemCameraKind(systemCameraKind), mPhysicalCameras(physicalCameras) {}
Ruben Brunkcc776712015-02-17 20:18:47 -08005214
5215CameraService::CameraState::~CameraState() {}
5216
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005217CameraService::StatusInternal CameraService::CameraState::getStatus() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005218 Mutex::Autolock lock(mStatusLock);
5219 return mStatus;
5220}
5221
Austin Borgered99f642023-06-01 16:51:35 -07005222std::vector<std::string> CameraService::CameraState::getUnavailablePhysicalIds() const {
Shuzhen Wang43858162020-01-10 13:42:15 -08005223 Mutex::Autolock lock(mStatusLock);
Austin Borgered99f642023-06-01 16:51:35 -07005224 std::vector<std::string> res(mUnavailablePhysicalIds.begin(), mUnavailablePhysicalIds.end());
Shuzhen Wang43858162020-01-10 13:42:15 -08005225 return res;
5226}
5227
Ruben Brunkcc776712015-02-17 20:18:47 -08005228CameraParameters CameraService::CameraState::getShimParams() const {
5229 return mShimParams;
5230}
5231
5232void CameraService::CameraState::setShimParams(const CameraParameters& params) {
5233 mShimParams = params;
5234}
5235
5236int CameraService::CameraState::getCost() const {
5237 return mCost;
5238}
5239
Austin Borgered99f642023-06-01 16:51:35 -07005240std::set<std::string> CameraService::CameraState::getConflicting() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005241 return mConflicting;
5242}
5243
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005244SystemCameraKind CameraService::CameraState::getSystemCameraKind() const {
5245 return mSystemCameraKind;
5246}
5247
Shuzhen Wang403af6d2021-12-21 00:08:43 +00005248bool CameraService::CameraState::containsPhysicalCamera(const std::string& physicalCameraId) const {
5249 return std::find(mPhysicalCameras.begin(), mPhysicalCameras.end(), physicalCameraId)
5250 != mPhysicalCameras.end();
5251}
5252
Austin Borgered99f642023-06-01 16:51:35 -07005253bool CameraService::CameraState::addUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005254 Mutex::Autolock lock(mStatusLock);
5255 auto result = mUnavailablePhysicalIds.insert(physicalId);
5256 return result.second;
5257}
5258
Austin Borgered99f642023-06-01 16:51:35 -07005259bool CameraService::CameraState::removeUnavailablePhysicalId(const std::string& physicalId) {
Shuzhen Wang43858162020-01-10 13:42:15 -08005260 Mutex::Autolock lock(mStatusLock);
5261 auto count = mUnavailablePhysicalIds.erase(physicalId);
5262 return count > 0;
5263}
5264
Austin Borgered99f642023-06-01 16:51:35 -07005265void CameraService::CameraState::setClientPackage(const std::string& clientPackage) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005266 Mutex::Autolock lock(mStatusLock);
5267 mClientPackage = clientPackage;
5268}
5269
Austin Borgered99f642023-06-01 16:51:35 -07005270std::string CameraService::CameraState::getClientPackage() const {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005271 Mutex::Autolock lock(mStatusLock);
5272 return mClientPackage;
5273}
5274
Ruben Brunkcc776712015-02-17 20:18:47 -08005275// ----------------------------------------------------------------------------
Ruben Brunk99e69712015-05-26 17:25:07 -07005276// ClientEventListener
5277// ----------------------------------------------------------------------------
5278
5279void CameraService::ClientEventListener::onClientAdded(
Austin Borgered99f642023-06-01 16:51:35 -07005280 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005281 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005282 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005283 if (basicClient.get() != nullptr) {
5284 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005285 notifier.noteStartCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005286 static_cast<int>(basicClient->getClientUid()));
5287 }
5288}
5289
5290void CameraService::ClientEventListener::onClientRemoved(
Austin Borgered99f642023-06-01 16:51:35 -07005291 const resource_policy::ClientDescriptor<std::string,
Ruben Brunk99e69712015-05-26 17:25:07 -07005292 sp<CameraService::BasicClient>>& descriptor) {
Chih-Hung Hsieh5404ee12016-08-09 14:25:53 -07005293 const auto& basicClient = descriptor.getValue();
Ruben Brunk99e69712015-05-26 17:25:07 -07005294 if (basicClient.get() != nullptr) {
5295 BatteryNotifier& notifier(BatteryNotifier::getInstance());
Austin Borgered99f642023-06-01 16:51:35 -07005296 notifier.noteStopCamera(toString8(descriptor.getKey()),
Ruben Brunk99e69712015-05-26 17:25:07 -07005297 static_cast<int>(basicClient->getClientUid()));
5298 }
5299}
5300
Ruben Brunk99e69712015-05-26 17:25:07 -07005301// ----------------------------------------------------------------------------
Ruben Brunkcc776712015-02-17 20:18:47 -08005302// CameraClientManager
5303// ----------------------------------------------------------------------------
5304
Ruben Brunk99e69712015-05-26 17:25:07 -07005305CameraService::CameraClientManager::CameraClientManager() {
5306 setListener(std::make_shared<ClientEventListener>());
5307}
5308
Ruben Brunkcc776712015-02-17 20:18:47 -08005309CameraService::CameraClientManager::~CameraClientManager() {}
5310
5311sp<CameraService::BasicClient> CameraService::CameraClientManager::getCameraClient(
Austin Borgered99f642023-06-01 16:51:35 -07005312 const std::string& id) const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005313 auto descriptor = get(id);
5314 if (descriptor == nullptr) {
5315 return sp<BasicClient>{nullptr};
5316 }
5317 return descriptor->getValue();
5318}
5319
Austin Borgered99f642023-06-01 16:51:35 -07005320std::string CameraService::CameraClientManager::toString() const {
Ruben Brunkcc776712015-02-17 20:18:47 -08005321 auto all = getAll();
Austin Borgered99f642023-06-01 16:51:35 -07005322 std::ostringstream ret;
5323 ret << "[";
Ruben Brunkcc776712015-02-17 20:18:47 -08005324 bool hasAny = false;
5325 for (auto& i : all) {
5326 hasAny = true;
Austin Borgered99f642023-06-01 16:51:35 -07005327 std::string key = i->getKey();
Ruben Brunkcc776712015-02-17 20:18:47 -08005328 int32_t cost = i->getCost();
5329 int32_t pid = i->getOwnerId();
Emilian Peev8131a262017-02-01 12:33:43 +00005330 int32_t score = i->getPriority().getScore();
5331 int32_t state = i->getPriority().getState();
Ruben Brunkcc776712015-02-17 20:18:47 -08005332 auto conflicting = i->getConflicting();
5333 auto clientSp = i->getValue();
Austin Borgered99f642023-06-01 16:51:35 -07005334 std::string packageName;
Eino-Ville Talvala022f0cb2015-05-19 16:31:16 -07005335 userid_t clientUserId = 0;
Ruben Brunkcc776712015-02-17 20:18:47 -08005336 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005337 packageName = clientSp->getPackageName();
Ruben Brunk6267b532015-04-30 17:44:07 -07005338 uid_t clientUid = clientSp->getClientUid();
5339 clientUserId = multiuser_get_user_id(clientUid);
Ruben Brunkcc776712015-02-17 20:18:47 -08005340 }
Austin Borgered99f642023-06-01 16:51:35 -07005341 ret << fmt::sprintf("\n(Camera ID: %s, Cost: %" PRId32 ", PID: %" PRId32 ", Score: %"
5342 PRId32 ", State: %" PRId32, key.c_str(), cost, pid, score, state);
Ruben Brunkcc776712015-02-17 20:18:47 -08005343
Ruben Brunk6267b532015-04-30 17:44:07 -07005344 if (clientSp.get() != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005345 ret << fmt::sprintf("User Id: %d, ", clientUserId);
Ruben Brunk6267b532015-04-30 17:44:07 -07005346 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005347 if (packageName.size() != 0) {
Austin Borgered99f642023-06-01 16:51:35 -07005348 ret << fmt::sprintf("Client Package Name: %s", packageName.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005349 }
5350
Austin Borgered99f642023-06-01 16:51:35 -07005351 ret << ", Conflicting Client Devices: {";
Ruben Brunkcc776712015-02-17 20:18:47 -08005352 for (auto& j : conflicting) {
Austin Borgered99f642023-06-01 16:51:35 -07005353 ret << fmt::sprintf("%s, ", j.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005354 }
Austin Borgered99f642023-06-01 16:51:35 -07005355 ret << "})";
Ruben Brunkcc776712015-02-17 20:18:47 -08005356 }
Austin Borgered99f642023-06-01 16:51:35 -07005357 if (hasAny) ret << "\n";
5358 ret << "]\n";
5359 return std::move(ret.str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005360}
5361
5362CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Austin Borgered99f642023-06-01 16:51:35 -07005363 const std::string& key, const sp<BasicClient>& value, int32_t cost,
5364 const std::set<std::string>& conflictingKeys, int32_t score, int32_t ownerId,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005365 int32_t state, int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005366
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005367 int32_t score_adj = systemNativeClient ? kSystemNativeClientScore : score;
Austin Borgered99f642023-06-01 16:51:35 -07005368 int32_t state_adj = systemNativeClient ? kSystemNativeClientState : state;
Jayant Chowdharyc578a502019-05-08 10:57:54 -07005369
Austin Borgered99f642023-06-01 16:51:35 -07005370 return std::make_shared<resource_policy::ClientDescriptor<std::string, sp<BasicClient>>>(
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005371 key, value, cost, conflictingKeys, score_adj, ownerId, state_adj,
5372 systemNativeClient, oomScoreOffset);
Ruben Brunkcc776712015-02-17 20:18:47 -08005373}
5374
5375CameraService::DescriptorPtr CameraService::CameraClientManager::makeClientDescriptor(
Jayant Chowdhary8eb8d912021-05-18 17:41:56 +00005376 const sp<BasicClient>& value, const CameraService::DescriptorPtr& partial,
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005377 int32_t oomScoreOffset, bool systemNativeClient) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005378 return makeClientDescriptor(partial->getKey(), value, partial->getCost(),
Emilian Peev8131a262017-02-01 12:33:43 +00005379 partial->getConflicting(), partial->getPriority().getScore(),
Jayant Chowdharyeb0169f2022-01-31 00:00:02 -08005380 partial->getOwnerId(), partial->getPriority().getState(), oomScoreOffset,
5381 systemNativeClient);
Ruben Brunkcc776712015-02-17 20:18:47 -08005382}
5383
5384// ----------------------------------------------------------------------------
Cliff Wud8cae102021-03-11 01:37:42 +08005385// InjectionStatusListener
5386// ----------------------------------------------------------------------------
5387
5388void CameraService::InjectionStatusListener::addListener(
5389 const sp<ICameraInjectionCallback>& callback) {
5390 Mutex::Autolock lock(mListenerLock);
5391 if (mCameraInjectionCallback) return;
5392 status_t res = IInterface::asBinder(callback)->linkToDeath(this);
5393 if (res == OK) {
5394 mCameraInjectionCallback = callback;
5395 }
5396}
5397
5398void CameraService::InjectionStatusListener::removeListener() {
5399 Mutex::Autolock lock(mListenerLock);
5400 if (mCameraInjectionCallback == nullptr) {
5401 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5402 return;
5403 }
5404 IInterface::asBinder(mCameraInjectionCallback)->unlinkToDeath(this);
5405 mCameraInjectionCallback = nullptr;
5406}
5407
5408void CameraService::InjectionStatusListener::notifyInjectionError(
Austin Borgered99f642023-06-01 16:51:35 -07005409 const std::string &injectedCamId, status_t err) {
Cliff Wud8cae102021-03-11 01:37:42 +08005410 if (mCameraInjectionCallback == nullptr) {
5411 ALOGW("InjectionStatusListener: mCameraInjectionCallback == nullptr");
5412 return;
5413 }
Cliff Wud3a05312021-04-26 23:07:31 +08005414
5415 switch (err) {
5416 case -ENODEV:
5417 mCameraInjectionCallback->onInjectionError(
5418 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5419 ALOGE("No camera device with ID \"%s\" currently available!",
Austin Borgered99f642023-06-01 16:51:35 -07005420 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005421 break;
5422 case -EBUSY:
5423 mCameraInjectionCallback->onInjectionError(
5424 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5425 ALOGE("Higher-priority client using camera, ID \"%s\" currently unavailable!",
Austin Borgered99f642023-06-01 16:51:35 -07005426 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005427 break;
5428 case DEAD_OBJECT:
5429 mCameraInjectionCallback->onInjectionError(
5430 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5431 ALOGE("Camera ID \"%s\" object is dead!",
Austin Borgered99f642023-06-01 16:51:35 -07005432 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005433 break;
5434 case INVALID_OPERATION:
5435 mCameraInjectionCallback->onInjectionError(
5436 ICameraInjectionCallback::ERROR_INJECTION_SESSION);
5437 ALOGE("Camera ID \"%s\" encountered an operating or internal error!",
Austin Borgered99f642023-06-01 16:51:35 -07005438 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005439 break;
5440 case UNKNOWN_TRANSACTION:
5441 mCameraInjectionCallback->onInjectionError(
5442 ICameraInjectionCallback::ERROR_INJECTION_UNSUPPORTED);
5443 ALOGE("Camera ID \"%s\" method doesn't support!",
Austin Borgered99f642023-06-01 16:51:35 -07005444 injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005445 break;
5446 default:
5447 mCameraInjectionCallback->onInjectionError(
5448 ICameraInjectionCallback::ERROR_INJECTION_INVALID_ERROR);
5449 ALOGE("Unexpected error %s (%d) opening camera \"%s\"!",
Austin Borgered99f642023-06-01 16:51:35 -07005450 strerror(-err), err, injectedCamId.c_str());
Cliff Wud3a05312021-04-26 23:07:31 +08005451 }
Cliff Wud8cae102021-03-11 01:37:42 +08005452}
5453
5454void CameraService::InjectionStatusListener::binderDied(
5455 const wp<IBinder>& /*who*/) {
Cliff Wud8cae102021-03-11 01:37:42 +08005456 ALOGV("InjectionStatusListener: ICameraInjectionCallback has died");
5457 auto parent = mParent.promote();
5458 if (parent != nullptr) {
Cliff Wud3a05312021-04-26 23:07:31 +08005459 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5460 if (clientDescriptor != nullptr) {
5461 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5462 baseClientPtr->stopInjection();
5463 }
Cliff Wu3b268182021-07-06 15:44:43 +08005464 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005465 }
5466}
5467
5468// ----------------------------------------------------------------------------
5469// CameraInjectionSession
5470// ----------------------------------------------------------------------------
5471
5472binder::Status CameraService::CameraInjectionSession::stopInjection() {
5473 Mutex::Autolock lock(mInjectionSessionLock);
5474 auto parent = mParent.promote();
5475 if (parent == nullptr) {
5476 ALOGE("CameraInjectionSession: Parent is gone");
5477 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SERVICE,
5478 "Camera service encountered error");
5479 }
Cliff Wud3a05312021-04-26 23:07:31 +08005480
5481 status_t res = NO_ERROR;
Cliff Wud3a05312021-04-26 23:07:31 +08005482 auto clientDescriptor = parent->mActiveClientManager.get(parent->mInjectionInternalCamId);
5483 if (clientDescriptor != nullptr) {
5484 BasicClient* baseClientPtr = clientDescriptor->getValue().get();
5485 res = baseClientPtr->stopInjection();
5486 if (res != OK) {
5487 ALOGE("CameraInjectionSession: Failed to stop the injection camera!"
5488 " ret != NO_ERROR: %d", res);
5489 return STATUS_ERROR(ICameraInjectionCallback::ERROR_INJECTION_SESSION,
5490 "Camera session encountered error");
5491 }
5492 }
Cliff Wu3b268182021-07-06 15:44:43 +08005493 parent->clearInjectionParameters();
Cliff Wud8cae102021-03-11 01:37:42 +08005494 return binder::Status::ok();
5495}
5496
5497// ----------------------------------------------------------------------------
Mathias Agopian65ab4712010-07-14 17:59:35 -07005498
5499static const int kDumpLockRetries = 50;
5500static const int kDumpLockSleep = 60000;
5501
5502static bool tryLock(Mutex& mutex)
5503{
5504 bool locked = false;
5505 for (int i = 0; i < kDumpLockRetries; ++i) {
5506 if (mutex.tryLock() == NO_ERROR) {
5507 locked = true;
5508 break;
5509 }
5510 usleep(kDumpLockSleep);
5511 }
5512 return locked;
5513}
5514
Rucha Katakwardf223072021-06-15 10:21:00 -07005515void CameraService::cacheDump() {
5516 if (mMemFd != -1) {
5517 const Vector<String16> args;
5518 ATRACE_CALL();
5519 // Acquiring service lock here will avoid the deadlock since
5520 // cacheDump will not be called during the second disconnect.
5521 Mutex::Autolock lock(mServiceLock);
5522
5523 Mutex::Autolock l(mCameraStatesLock);
5524 // Start collecting the info for open sessions and store it in temp file.
5525 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005526 std::string cameraId = state.first;
Rucha Katakwardf223072021-06-15 10:21:00 -07005527 auto clientDescriptor = mActiveClientManager.get(cameraId);
5528 if (clientDescriptor != nullptr) {
Austin Borgered99f642023-06-01 16:51:35 -07005529 dprintf(mMemFd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005530 // Log the current open session info before device is disconnected.
5531 dumpOpenSessionClientLogs(mMemFd, args, cameraId);
5532 }
5533 }
5534 }
5535}
5536
Mathias Agopian65ab4712010-07-14 17:59:35 -07005537status_t CameraService::dump(int fd, const Vector<String16>& args) {
Eino-Ville Talvalaa84bbe62015-09-08 17:59:17 -07005538 ATRACE_CALL();
5539
Austin Borgered99f642023-06-01 16:51:35 -07005540 if (checkCallingPermission(toString16(sDumpPermission)) == false) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005541 dprintf(fd, "Permission Denial: can't dump CameraService from pid=%d, uid=%d\n",
Austin Borger22c5c852024-03-08 13:31:36 -08005542 getCallingPid(),
5543 getCallingUid());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005544 return NO_ERROR;
5545 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005546 bool locked = tryLock(mServiceLock);
5547 // failed to lock - CameraService is probably deadlocked
5548 if (!locked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005549 dprintf(fd, "!! CameraService may be deadlocked !!\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005550 }
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005551
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005552 if (!mInitialized) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005553 dprintf(fd, "!! No camera HAL available !!\n");
Ruben Brunkf81648e2014-04-17 16:14:57 -07005554
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005555 // Dump event log for error information
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005556 dumpEventLog(fd);
Ruben Brunkcc776712015-02-17 20:18:47 -08005557
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005558 if (locked) mServiceLock.unlock();
5559 return NO_ERROR;
5560 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005561 dprintf(fd, "\n== Service global info: ==\n\n");
5562 dprintf(fd, "Number of camera devices: %d\n", mNumberOfCameras);
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005563 dprintf(fd, "Number of normal camera devices: %zu\n", mNormalDeviceIds.size());
Jayant Chowdhary847947d2019-08-30 18:02:59 -07005564 dprintf(fd, "Number of public camera devices visible to API1: %zu\n",
5565 mNormalDeviceIdsWithoutSystemCamera.size());
Yin-Chia Yehc3e9d6f2018-02-06 10:56:32 -08005566 for (size_t i = 0; i < mNormalDeviceIds.size(); i++) {
5567 dprintf(fd, " Device %zu maps to \"%s\"\n", i, mNormalDeviceIds[i].c_str());
5568 }
Austin Borgered99f642023-06-01 16:51:35 -07005569 std::string activeClientString = mActiveClientManager.toString();
5570 dprintf(fd, "Active Camera Clients:\n%s", activeClientString.c_str());
5571 dprintf(fd, "Allowed user IDs: %s\n", toString(mAllowedUsers).c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08005572 if (mStreamUseCaseOverrides.size() > 0) {
5573 dprintf(fd, "Active stream use case overrides:");
5574 for (int64_t useCaseOverride : mStreamUseCaseOverrides) {
5575 dprintf(fd, " %" PRId64, useCaseOverride);
5576 }
5577 dprintf(fd, "\n");
5578 }
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005579
5580 dumpEventLog(fd);
5581
5582 bool stateLocked = tryLock(mCameraStatesLock);
5583 if (!stateLocked) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005584 dprintf(fd, "CameraStates in use, may be deadlocked\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005585 }
5586
Emilian Peevbd8c5032018-02-14 23:05:40 +00005587 int argSize = args.size();
5588 for (int i = 0; i < argSize; i++) {
Austin Borgered99f642023-06-01 16:51:35 -07005589 if (args[i] == toString16(TagMonitor::kMonitorOption)) {
Emilian Peevbd8c5032018-02-14 23:05:40 +00005590 if (i + 1 < argSize) {
Austin Borgered99f642023-06-01 16:51:35 -07005591 mMonitorTags = toStdString(args[i + 1]);
Emilian Peevbd8c5032018-02-14 23:05:40 +00005592 }
5593 break;
5594 }
5595 }
5596
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005597 for (auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07005598 const std::string &cameraId = state.first;
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005599
Austin Borgered99f642023-06-01 16:51:35 -07005600 dprintf(fd, "== Camera device %s dynamic info: ==\n", cameraId.c_str());
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005601
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005602 CameraParameters p = state.second->getShimParams();
5603 if (!p.isEmpty()) {
5604 dprintf(fd, " Camera1 API shim is using parameters:\n ");
5605 p.dump(fd, args);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005606 }
5607
5608 auto clientDescriptor = mActiveClientManager.get(cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005609 if (clientDescriptor != nullptr) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005610 // log the current open session info
5611 dumpOpenSessionClientLogs(fd, args, cameraId);
Zhijun He2f140ed2017-02-08 09:57:23 -08005612 } else {
Rucha Katakwardf223072021-06-15 10:21:00 -07005613 dumpClosedSessionClientLogs(fd, cameraId);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005614 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005615
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005616 }
5617
5618 if (stateLocked) mCameraStatesLock.unlock();
5619
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005620 if (locked) mServiceLock.unlock();
5621
Emilian Peevf53f66e2017-04-11 14:29:43 +01005622 mCameraProviderManager->dump(fd, args);
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005623
5624 dprintf(fd, "\n== Vendor tags: ==\n\n");
5625
5626 sp<VendorTagDescriptor> desc = VendorTagDescriptor::getGlobalVendorTagDescriptor();
5627 if (desc == NULL) {
Emilian Peev71c73a22017-03-21 16:35:51 +00005628 sp<VendorTagDescriptorCache> cache =
5629 VendorTagDescriptorCache::getGlobalVendorTagCache();
5630 if (cache == NULL) {
5631 dprintf(fd, "No vendor tags.\n");
5632 } else {
5633 cache->dump(fd, /*verbosity*/2, /*indentation*/2);
5634 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005635 } else {
5636 desc->dump(fd, /*verbosity*/2, /*indentation*/2);
5637 }
5638
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005639 // Dump camera traces if there were any
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005640 dprintf(fd, "\n");
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07005641 camera3::CameraTraces::dump(fd);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005642
5643 // Process dump arguments, if any
5644 int n = args.size();
5645 String16 verboseOption("-v");
5646 String16 unreachableOption("--unreachable");
5647 for (int i = 0; i < n; i++) {
5648 if (args[i] == verboseOption) {
5649 // change logging level
5650 if (i + 1 >= n) continue;
Austin Borgered99f642023-06-01 16:51:35 -07005651 std::string levelStr = toStdString(args[i+1]);
5652 int level = atoi(levelStr.c_str());
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005653 dprintf(fd, "\nSetting log level to %d.\n", level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005654 setLogLevel(level);
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005655 } else if (args[i] == unreachableOption) {
5656 // Dump memory analysis
5657 // TODO - should limit be an argument parameter?
5658 UnreachableMemoryInfo info;
5659 bool success = GetUnreachableMemory(info, /*limit*/ 10000);
5660 if (!success) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005661 dprintf(fd, "\n== Unable to dump unreachable memory. "
5662 "Try disabling SELinux enforcement. ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005663 } else {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005664 dprintf(fd, "\n== Dumping unreachable memory: ==\n");
Eino-Ville Talvala81314182017-01-30 16:13:45 -08005665 std::string s = info.ToString(/*log_contents*/ true);
5666 write(fd, s.c_str(), s.size());
Mathias Agopian65ab4712010-07-14 17:59:35 -07005667 }
5668 }
5669 }
Rucha Katakwardf223072021-06-15 10:21:00 -07005670
5671 bool serviceLocked = tryLock(mServiceLock);
5672
5673 // Dump info from previous open sessions.
5674 // Reposition the offset to beginning of the file before reading
5675
5676 if ((mMemFd >= 0) && (lseek(mMemFd, 0, SEEK_SET) != -1)) {
5677 dprintf(fd, "\n**********Dumpsys from previous open session**********\n");
5678 ssize_t size_read;
5679 char buf[4096];
5680 while ((size_read = read(mMemFd, buf, (sizeof(buf) - 1))) > 0) {
5681 // Read data from file to a small buffer and write it to fd.
5682 write(fd, buf, size_read);
5683 if (size_read == -1) {
5684 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5685 break;
5686 }
5687 }
5688 dprintf(fd, "\n**********End of Dumpsys from previous open session**********\n");
5689 } else {
5690 ALOGE("%s: Error during reading the file: %s", __FUNCTION__, sFileName);
5691 }
5692
5693 if (serviceLocked) mServiceLock.unlock();
Mathias Agopian65ab4712010-07-14 17:59:35 -07005694 return NO_ERROR;
5695}
5696
Rucha Katakwardf223072021-06-15 10:21:00 -07005697void CameraService::dumpOpenSessionClientLogs(int fd,
Austin Borgered99f642023-06-01 16:51:35 -07005698 const Vector<String16>& args, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005699 auto clientDescriptor = mActiveClientManager.get(cameraId);
Rucha Katakwar71a0e052022-04-07 15:44:18 -07005700 dprintf(fd, " %s : Device %s is open. Client instance dump:\n",
Austin Borgered99f642023-06-01 16:51:35 -07005701 getFormattedCurrentTime().c_str(),
5702 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005703 dprintf(fd, " Client priority score: %d state: %d\n",
5704 clientDescriptor->getPriority().getScore(),
5705 clientDescriptor->getPriority().getState());
5706 dprintf(fd, " Client PID: %d\n", clientDescriptor->getOwnerId());
5707
5708 auto client = clientDescriptor->getValue();
5709 dprintf(fd, " Client package: %s\n",
Austin Borgered99f642023-06-01 16:51:35 -07005710 client->getPackageName().c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005711
5712 client->dumpClient(fd, args);
5713}
5714
Austin Borgered99f642023-06-01 16:51:35 -07005715void CameraService::dumpClosedSessionClientLogs(int fd, const std::string& cameraId) {
Rucha Katakwardf223072021-06-15 10:21:00 -07005716 dprintf(fd, " Device %s is closed, no client instance\n",
Austin Borgered99f642023-06-01 16:51:35 -07005717 cameraId.c_str());
Rucha Katakwardf223072021-06-15 10:21:00 -07005718}
5719
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005720void CameraService::dumpEventLog(int fd) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005721 dprintf(fd, "\n== Camera service events log (most recent at top): ==\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005722
5723 Mutex::Autolock l(mLogLock);
5724 for (const auto& msg : mEventLog) {
Austin Borgered99f642023-06-01 16:51:35 -07005725 dprintf(fd, " %s\n", msg.c_str());
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005726 }
5727
5728 if (mEventLog.size() == DEFAULT_EVENT_LOG_LENGTH) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005729 dprintf(fd, " ...\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005730 } else if (mEventLog.size() == 0) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005731 dprintf(fd, " [no events yet]\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005732 }
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -08005733 dprintf(fd, "\n");
Eino-Ville Talvala1527f072015-04-07 15:55:31 -07005734}
5735
Austin Borgered99f642023-06-01 16:51:35 -07005736void CameraService::cacheClientTagDumpIfNeeded(const std::string &cameraId, BasicClient* client) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005737 Mutex::Autolock lock(mLogLock);
5738 if (!isClientWatchedLocked(client)) { return; }
5739
5740 std::vector<std::string> dumpVector;
5741 client->dumpWatchedEventsToVector(dumpVector);
5742
5743 if (dumpVector.empty()) { return; }
5744
Austin Borgered99f642023-06-01 16:51:35 -07005745 std::ostringstream dumpString;
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005746
Austin Borgered99f642023-06-01 16:51:35 -07005747 std::string currentTime = getFormattedCurrentTime();
5748 dumpString << "Cached @ ";
5749 dumpString << currentTime;
5750 dumpString << "\n"; // First line is the timestamp of when client is cached.
Avichal Rakesh882c08b2021-12-09 17:47:07 -08005751
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005752 size_t i = dumpVector.size();
5753
5754 // Store the string in reverse order (latest last)
5755 while (i > 0) {
5756 i--;
Austin Borgered99f642023-06-01 16:51:35 -07005757 dumpString << cameraId;
5758 dumpString << ":";
5759 dumpString << client->getPackageName();
5760 dumpString << " ";
5761 dumpString << dumpVector[i]; // implicitly ends with '\n'
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005762 }
5763
Austin Borgered99f642023-06-01 16:51:35 -07005764 mWatchedClientsDumpCache[client->getPackageName()] = dumpString.str();
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07005765}
5766
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005767void CameraService::handleTorchClientBinderDied(const wp<IBinder> &who) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005768 Mutex::Autolock al(mTorchClientMapMutex);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005769 for (size_t i = 0; i < mTorchClientMap.size(); i++) {
5770 if (mTorchClientMap[i] == who) {
5771 // turn off the torch mode that was turned on by dead client
Austin Borgered99f642023-06-01 16:51:35 -07005772 std::string cameraId = mTorchClientMap.keyAt(i);
Chien-Yu Chen88da5262015-02-17 13:56:46 -08005773 status_t res = mFlashlight->setTorchMode(cameraId, false);
5774 if (res) {
5775 ALOGE("%s: torch client died but couldn't turn off torch: "
5776 "%s (%d)", __FUNCTION__, strerror(-res), res);
5777 return;
5778 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005779 mTorchClientMap.removeItemsAt(i);
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005780 break;
5781 }
5782 }
5783}
5784
Ruben Brunkcc776712015-02-17 20:18:47 -08005785/*virtual*/void CameraService::binderDied(const wp<IBinder> &who) {
Igor Murashkinecf17e82012-10-02 16:05:11 -07005786
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005787 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -07005788 * While tempting to promote the wp<IBinder> into a sp, it's actually not supported by the
5789 * binder driver
Igor Murashkin294d0ec2012-10-05 10:44:57 -07005790 */
Yin-Chia Yehdbfcb382018-02-16 11:17:36 -08005791 // PID here is approximate and can be wrong.
Austin Borger22c5c852024-03-08 13:31:36 -08005792 logClientDied(getCallingPid(), "Binder died unexpectedly");
Ruben Brunka8ca9152015-04-07 14:23:40 -07005793
Chien-Yu Chen3068d732015-02-09 13:29:57 -08005794 // check torch client
5795 handleTorchClientBinderDied(who);
5796
5797 // check camera device client
Ruben Brunkcc776712015-02-17 20:18:47 -08005798 if(!evictClientIdByRemote(who)) {
5799 ALOGV("%s: Java client's binder death already cleaned up (normal case)", __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005800 return;
5801 }
5802
Ruben Brunkcc776712015-02-17 20:18:47 -08005803 ALOGE("%s: Java client's binder died, removing it from the list of active clients",
5804 __FUNCTION__);
Igor Murashkinecf17e82012-10-02 16:05:11 -07005805}
5806
Austin Borgered99f642023-06-01 16:51:35 -07005807void CameraService::updateStatus(StatusInternal status, const std::string& cameraId) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005808 updateStatus(status, cameraId, {});
Igor Murashkinbfc99152013-02-27 12:55:20 -08005809}
5810
Austin Borgered99f642023-06-01 16:51:35 -07005811void CameraService::updateStatus(StatusInternal status, const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005812 std::initializer_list<StatusInternal> rejectSourceStates) {
Ruben Brunkcc776712015-02-17 20:18:47 -08005813 // Do not lock mServiceLock here or can get into a deadlock from
5814 // connect() -> disconnect -> updateStatus
5815
5816 auto state = getCameraState(cameraId);
5817
5818 if (state == nullptr) {
5819 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005820 cameraId.c_str());
Ruben Brunkcc776712015-02-17 20:18:47 -08005821 return;
Igor Murashkincba2c162013-03-20 15:56:31 -07005822 }
5823
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005824 // Avoid calling getSystemCameraKind() with mStatusListenerLock held (b/141756275)
5825 SystemCameraKind deviceKind = SystemCameraKind::PUBLIC;
5826 if (getSystemCameraKind(cameraId, &deviceKind) != OK) {
Austin Borgered99f642023-06-01 16:51:35 -07005827 ALOGE("%s: Invalid camera id %s, skipping", __FUNCTION__, cameraId.c_str());
Jayant Chowdhary33e8ef82019-09-27 09:20:42 -07005828 return;
5829 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005830
Biswarup Pal37a75182024-01-16 15:53:35 +00005831 if (vd_flags::camera_device_awareness() && status == StatusInternal::PRESENT) {
5832 CameraMetadata cameraInfo;
5833 status_t res = mCameraProviderManager->getCameraCharacteristics(
5834 cameraId, false, &cameraInfo, false);
5835 if (res != OK) {
5836 ALOGW("%s: Not able to get camera characteristics for camera id %s",
5837 __FUNCTION__, cameraId.c_str());
5838 } else {
5839 int32_t deviceId = getDeviceId(cameraInfo);
5840 if (deviceId != kDefaultDeviceId) {
5841 const auto &lensFacingEntry = cameraInfo.find(ANDROID_LENS_FACING);
5842 camera_metadata_enum_android_lens_facing_t androidLensFacing =
5843 static_cast<camera_metadata_enum_android_lens_facing_t>(
5844 lensFacingEntry.data.u8[0]);
5845 std::string mappedCameraId;
5846 if (androidLensFacing == ANDROID_LENS_FACING_BACK) {
5847 mappedCameraId = kVirtualDeviceBackCameraId;
5848 } else if (androidLensFacing == ANDROID_LENS_FACING_FRONT) {
5849 mappedCameraId = kVirtualDeviceFrontCameraId;
5850 } else {
5851 ALOGD("%s: Not adding entry for an external camera of a virtual device",
5852 __func__);
5853 }
5854 if (!mappedCameraId.empty()) {
5855 mVirtualDeviceCameraIdMapper.addCamera(cameraId, deviceId, mappedCameraId);
5856 }
5857 }
5858 }
5859 }
5860
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005861 // Collect the logical cameras without holding mStatusLock in updateStatus
5862 // as that can lead to a deadlock(b/162192331).
5863 auto logicalCameraIds = getLogicalCameras(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005864 // Update the status for this camera state, then send the onStatusChangedCallbacks to each
Shuzhen Wang43858162020-01-10 13:42:15 -08005865 // of the listeners with both the mStatusLock and mStatusListenerLock held
Shuzhen Wangb8259792021-05-27 09:27:06 -07005866 state->updateStatus(status, cameraId, rejectSourceStates, [this, &deviceKind,
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00005867 &logicalCameraIds]
Austin Borgered99f642023-06-01 16:51:35 -07005868 (const std::string& cameraId, StatusInternal status) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005869 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5870 auto [deviceId, mappedCameraId] =
5871 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
Ruben Brunkcc776712015-02-17 20:18:47 -08005872
Biswarup Pal37a75182024-01-16 15:53:35 +00005873 if (status != StatusInternal::ENUMERATING) {
5874 // Update torch status if it has a flash unit.
5875 Mutex::Autolock al(mTorchStatusMutex);
5876 TorchModeStatus torchStatus;
5877 if (getTorchStatusLocked(cameraId, &torchStatus) !=
5878 NAME_NOT_FOUND) {
5879 TorchModeStatus newTorchStatus =
5880 status == StatusInternal::PRESENT ?
5881 TorchModeStatus::AVAILABLE_OFF :
5882 TorchModeStatus::NOT_AVAILABLE;
5883 if (torchStatus != newTorchStatus) {
5884 onTorchStatusChangedLocked(cameraId, newTorchStatus, deviceKind);
5885 }
Chien-Yu Chenf6463fc2015-04-07 15:11:31 -07005886 }
5887 }
Ruben Brunkcc776712015-02-17 20:18:47 -08005888
Biswarup Pal37a75182024-01-16 15:53:35 +00005889 Mutex::Autolock lock(mStatusListenerLock);
5890 notifyPhysicalCameraStatusLocked(mapToInterface(status), mappedCameraId,
5891 logicalCameraIds, deviceKind, deviceId);
Shuzhen Wang43858162020-01-10 13:42:15 -08005892
Biswarup Pal37a75182024-01-16 15:53:35 +00005893 for (auto& listener : mListenerList) {
5894 bool isVendorListener = listener->isVendorListener();
5895 if (shouldSkipStatusUpdates(deviceKind, isVendorListener,
5896 listener->getListenerPid(), listener->getListenerUid())) {
5897 ALOGV("Skipping discovery callback for system-only camera device %s",
5898 cameraId.c_str());
5899 continue;
5900 }
5901
5902 auto ret = listener->getListener()->onStatusChanged(mapToInterface(status),
5903 mappedCameraId, deviceId);
malikakash82ed4352023-07-21 22:44:34 +00005904 listener->handleBinderStatus(ret,
Biswarup Pal37a75182024-01-16 15:53:35 +00005905 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
malikakash82ed4352023-07-21 22:44:34 +00005906 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
5907 ret.exceptionCode());
Biswarup Pal37a75182024-01-16 15:53:35 +00005908
5909 // Only cameras of the default device can be remapped to a different camera
5910 // (using remapCameraIds method), so do the following only if the camera is
5911 // associated with the default device.
5912 if (deviceId == kDefaultDeviceId) {
5913 // For the default device, also trigger the callbacks for cameras that were
5914 // remapped to the current cameraId for the specific package that this
5915 // listener belongs to.
5916 std::vector<std::string> remappedCameraIds =
5917 findOriginalIdsForRemappedCameraId(cameraId,
5918 listener->getListenerUid());
5919 for (auto &remappedCameraId: remappedCameraIds) {
5920 ret = listener->getListener()->onStatusChanged(
5921 mapToInterface(status), remappedCameraId, kDefaultDeviceId);
5922 listener->handleBinderStatus(ret,
5923 "%s: Failed to trigger onStatusChanged callback for %d:%d: %d",
5924 __FUNCTION__, listener->getListenerUid(),
5925 listener->getListenerPid(), ret.exceptionCode());
5926 }
5927 }
malikakash82ed4352023-07-21 22:44:34 +00005928 }
Biswarup Pal37a75182024-01-16 15:53:35 +00005929 });
Igor Murashkincba2c162013-03-20 15:56:31 -07005930}
5931
Austin Borgered99f642023-06-01 16:51:35 -07005932void CameraService::updateOpenCloseStatus(const std::string& cameraId, bool open,
5933 const std::string& clientPackageName) {
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005934 auto state = getCameraState(cameraId);
5935 if (state == nullptr) {
5936 ALOGW("%s: Could not update the status for %s, no such device exists", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005937 cameraId.c_str());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005938 return;
5939 }
5940 if (open) {
Austin Borgered99f642023-06-01 16:51:35 -07005941 state->setClientPackage(clientPackageName);
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005942 } else {
Austin Borgered99f642023-06-01 16:51:35 -07005943 state->setClientPackage(std::string());
Shuzhen Wange7aa0342021-08-03 11:29:47 -07005944 }
5945
Biswarup Pal37a75182024-01-16 15:53:35 +00005946 // Get the device id and app-visible camera id for the given HAL-visible camera id.
5947 auto [deviceId, mappedCameraId] =
5948 mVirtualDeviceCameraIdMapper.getDeviceIdAndMappedCameraIdPair(cameraId);
5949
Shuzhen Wang695044d2020-03-06 09:02:23 -08005950 Mutex::Autolock lock(mStatusListenerLock);
5951
5952 for (const auto& it : mListenerList) {
5953 if (!it->isOpenCloseCallbackAllowed()) {
5954 continue;
5955 }
5956
5957 binder::Status ret;
Shuzhen Wang695044d2020-03-06 09:02:23 -08005958 if (open) {
Biswarup Pal37a75182024-01-16 15:53:35 +00005959 ret = it->getListener()->onCameraOpened(mappedCameraId, clientPackageName,
5960 deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005961 } else {
Biswarup Pal37a75182024-01-16 15:53:35 +00005962 ret = it->getListener()->onCameraClosed(mappedCameraId, deviceId);
Shuzhen Wang695044d2020-03-06 09:02:23 -08005963 }
Austin Borgere8e2c422022-05-12 13:45:24 -07005964
5965 it->handleBinderStatus(ret,
5966 "%s: Failed to trigger onCameraOpened/onCameraClosed callback for %d:%d: %d",
5967 __FUNCTION__, it->getListenerUid(), it->getListenerPid(), ret.exceptionCode());
Shuzhen Wang695044d2020-03-06 09:02:23 -08005968 }
5969}
5970
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005971template<class Func>
5972void CameraService::CameraState::updateStatus(StatusInternal status,
Austin Borgered99f642023-06-01 16:51:35 -07005973 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005974 std::initializer_list<StatusInternal> rejectSourceStates,
5975 Func onStatusUpdatedLocked) {
5976 Mutex::Autolock lock(mStatusLock);
5977 StatusInternal oldStatus = mStatus;
5978 mStatus = status;
5979
5980 if (oldStatus == status) {
5981 return;
5982 }
5983
5984 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
Austin Borgered99f642023-06-01 16:51:35 -07005985 cameraId.c_str(), oldStatus, status);
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08005986
5987 if (oldStatus == StatusInternal::NOT_PRESENT &&
5988 (status != StatusInternal::PRESENT &&
5989 status != StatusInternal::ENUMERATING)) {
5990
5991 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
5992 __FUNCTION__);
5993 mStatus = oldStatus;
5994 return;
5995 }
5996
5997 /**
5998 * Sometimes we want to conditionally do a transition.
5999 * For example if a client disconnects, we want to go to PRESENT
6000 * only if we weren't already in NOT_PRESENT or ENUMERATING.
6001 */
6002 for (auto& rejectStatus : rejectSourceStates) {
6003 if (oldStatus == rejectStatus) {
6004 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
Austin Borgered99f642023-06-01 16:51:35 -07006005 "state was was in one of the bad states.", __FUNCTION__, cameraId.c_str());
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006006 mStatus = oldStatus;
6007 return;
6008 }
6009 }
6010
6011 onStatusUpdatedLocked(cameraId, status);
6012}
6013
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006014status_t CameraService::getTorchStatusLocked(
Austin Borgered99f642023-06-01 16:51:35 -07006015 const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006016 TorchModeStatus *status) const {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006017 if (!status) {
6018 return BAD_VALUE;
6019 }
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006020 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6021 if (index == NAME_NOT_FOUND) {
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006022 // invalid camera ID or the camera doesn't have a flash unit
6023 return NAME_NOT_FOUND;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006024 }
6025
Chien-Yu Chen88da5262015-02-17 13:56:46 -08006026 *status = mTorchStatusMap.valueAt(index);
6027 return OK;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006028}
6029
Austin Borgered99f642023-06-01 16:51:35 -07006030status_t CameraService::setTorchStatusLocked(const std::string& cameraId,
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006031 TorchModeStatus status) {
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006032 ssize_t index = mTorchStatusMap.indexOfKey(cameraId);
6033 if (index == NAME_NOT_FOUND) {
6034 return BAD_VALUE;
6035 }
Eino-Ville Talvalaf51fca22016-12-13 11:25:55 -08006036 mTorchStatusMap.editValueAt(index) = status;
Chien-Yu Chen3068d732015-02-09 13:29:57 -08006037
6038 return OK;
6039}
6040
Austin Borgered99f642023-06-01 16:51:35 -07006041std::list<std::string> CameraService::getLogicalCameras(
6042 const std::string& physicalCameraId) {
6043 std::list<std::string> retList;
Shuzhen Wang43858162020-01-10 13:42:15 -08006044 Mutex::Autolock lock(mCameraStatesLock);
6045 for (const auto& state : mCameraStates) {
Austin Borgered99f642023-06-01 16:51:35 -07006046 if (state.second->containsPhysicalCamera(physicalCameraId)) {
6047 retList.emplace_back(state.first);
Shuzhen Wang43858162020-01-10 13:42:15 -08006048 }
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006049 }
6050 return retList;
6051}
6052
6053void CameraService::notifyPhysicalCameraStatusLocked(int32_t status,
Austin Borgered99f642023-06-01 16:51:35 -07006054 const std::string& physicalCameraId, const std::list<std::string>& logicalCameraIds,
Biswarup Pal37a75182024-01-16 15:53:35 +00006055 SystemCameraKind deviceKind, int32_t deviceId) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006056 // mStatusListenerLock is expected to be locked
6057 for (const auto& logicalCameraId : logicalCameraIds) {
Shuzhen Wang43858162020-01-10 13:42:15 -08006058 for (auto& listener : mListenerList) {
Jayant Chowdhary5e2cd302020-08-14 02:48:34 +00006059 // Note: we check only the deviceKind of the physical camera id
6060 // since, logical camera ids and their physical camera ids are
6061 // guaranteed to have the same system camera kind.
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006062 if (shouldSkipStatusUpdates(deviceKind, listener->isVendorListener(),
6063 listener->getListenerPid(), listener->getListenerUid())) {
6064 ALOGV("Skipping discovery callback for system-only camera device %s",
Austin Borgered99f642023-06-01 16:51:35 -07006065 physicalCameraId.c_str());
Jayant Chowdharyd1478ce2020-05-07 17:35:23 -07006066 continue;
6067 }
Austin Borgere8e2c422022-05-12 13:45:24 -07006068 auto ret = listener->getListener()->onPhysicalCameraStatusChanged(status,
Biswarup Pal37a75182024-01-16 15:53:35 +00006069 logicalCameraId, physicalCameraId, deviceId);
Austin Borgere8e2c422022-05-12 13:45:24 -07006070 listener->handleBinderStatus(ret,
6071 "%s: Failed to trigger onPhysicalCameraStatusChanged for %d:%d: %d",
6072 __FUNCTION__, listener->getListenerUid(), listener->getListenerPid(),
6073 ret.exceptionCode());
Shuzhen Wang43858162020-01-10 13:42:15 -08006074 }
6075 }
6076}
6077
Svet Ganova453d0d2018-01-11 15:37:58 -08006078void CameraService::blockClientsForUid(uid_t uid) {
6079 const auto clients = mActiveClientManager.getAll();
6080 for (auto& current : clients) {
6081 if (current != nullptr) {
6082 const auto basicClient = current->getValue();
6083 if (basicClient.get() != nullptr && basicClient->getClientUid() == uid) {
6084 basicClient->block();
6085 }
6086 }
6087 }
6088}
6089
Michael Grooverd1d435a2018-12-18 17:39:42 -08006090void CameraService::blockAllClients() {
6091 const auto clients = mActiveClientManager.getAll();
6092 for (auto& current : clients) {
6093 if (current != nullptr) {
6094 const auto basicClient = current->getValue();
6095 if (basicClient.get() != nullptr) {
6096 basicClient->block();
6097 }
6098 }
6099 }
6100}
6101
Jyoti Bhayanac05a1192024-02-11 13:19:29 +00006102void CameraService::blockPrivacyEnabledClients() {
6103 const auto clients = mActiveClientManager.getAll();
6104 for (auto& current : clients) {
6105 if (current != nullptr) {
6106 const auto basicClient = current->getValue();
6107 if (basicClient.get() != nullptr) {
6108 std::string pkgName = basicClient->getPackageName();
6109 bool cameraPrivacyEnabled =
6110 mSensorPrivacyPolicy->isCameraPrivacyEnabled(toString16(pkgName));
6111 if (cameraPrivacyEnabled) {
6112 basicClient->block();
6113 }
6114 }
6115 }
6116 }
6117}
6118
Svet Ganova453d0d2018-01-11 15:37:58 -08006119// NOTE: This is a remote API - make sure all args are validated
6120status_t CameraService::shellCommand(int in, int out, int err, const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006121 if (!checkCallingPermission(toString16(sManageCameraPermission), nullptr, nullptr)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006122 return PERMISSION_DENIED;
6123 }
6124 if (in == BAD_TYPE || out == BAD_TYPE || err == BAD_TYPE) {
6125 return BAD_VALUE;
6126 }
Austin Borgered99f642023-06-01 16:51:35 -07006127 if (args.size() >= 3 && args[0] == toString16("set-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006128 return handleSetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006129 } else if (args.size() >= 2 && args[0] == toString16("reset-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006130 return handleResetUidState(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006131 } else if (args.size() >= 2 && args[0] == toString16("get-uid-state")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006132 return handleGetUidState(args, out, err);
Austin Borgered99f642023-06-01 16:51:35 -07006133 } else if (args.size() >= 2 && args[0] == toString16("set-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006134 return handleSetRotateAndCrop(args);
Austin Borgered99f642023-06-01 16:51:35 -07006135 } else if (args.size() >= 1 && args[0] == toString16("get-rotate-and-crop")) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006136 return handleGetRotateAndCrop(out);
Austin Borgered99f642023-06-01 16:51:35 -07006137 } else if (args.size() >= 2 && args[0] == toString16("set-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006138 return handleSetAutoframing(args);
Austin Borgered99f642023-06-01 16:51:35 -07006139 } else if (args.size() >= 1 && args[0] == toString16("get-autoframing")) {
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006140 return handleGetAutoframing(out);
Austin Borgered99f642023-06-01 16:51:35 -07006141 } else if (args.size() >= 2 && args[0] == toString16("set-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006142 return handleSetImageDumpMask(args);
Austin Borgered99f642023-06-01 16:51:35 -07006143 } else if (args.size() >= 1 && args[0] == toString16("get-image-dump-mask")) {
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006144 return handleGetImageDumpMask(out);
Austin Borgered99f642023-06-01 16:51:35 -07006145 } else if (args.size() >= 2 && args[0] == toString16("set-camera-mute")) {
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006146 return handleSetCameraMute(args);
Austin Borgered99f642023-06-01 16:51:35 -07006147 } else if (args.size() >= 2 && args[0] == toString16("set-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006148 return handleSetStreamUseCaseOverrides(args);
Austin Borgered99f642023-06-01 16:51:35 -07006149 } else if (args.size() >= 1 && args[0] == toString16("clear-stream-use-case-override")) {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006150 handleClearStreamUseCaseOverrides();
6151 return OK;
Austin Borgered99f642023-06-01 16:51:35 -07006152 } else if (args.size() >= 1 && args[0] == toString16("set-zoom-override")) {
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006153 return handleSetZoomOverride(args);
Austin Borgered99f642023-06-01 16:51:35 -07006154 } else if (args.size() >= 2 && args[0] == toString16("watch")) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006155 return handleWatchCommand(args, in, out);
Austin Borgered99f642023-06-01 16:51:35 -07006156 } else if (args.size() >= 2 && args[0] == toString16("set-watchdog")) {
Ravneetaeb20dc2022-03-30 05:33:03 +00006157 return handleSetCameraServiceWatchdog(args);
Austin Borgered99f642023-06-01 16:51:35 -07006158 } else if (args.size() >= 4 && args[0] == toString16("remap-camera-id")) {
malikakash82ed4352023-07-21 22:44:34 +00006159 return handleCameraIdRemapping(args, err);
Austin Borgered99f642023-06-01 16:51:35 -07006160 } else if (args.size() == 1 && args[0] == toString16("help")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006161 printHelp(out);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006162 return OK;
Svet Ganova453d0d2018-01-11 15:37:58 -08006163 }
6164 printHelp(err);
6165 return BAD_VALUE;
6166}
6167
malikakash82ed4352023-07-21 22:44:34 +00006168status_t CameraService::handleCameraIdRemapping(const Vector<String16>& args, int err) {
6169 uid_t uid = IPCThreadState::self()->getCallingUid();
6170 if (uid != AID_ROOT) {
6171 dprintf(err, "Must be adb root\n");
6172 return PERMISSION_DENIED;
6173 }
6174 if (args.size() != 4) {
6175 dprintf(err, "Expected format: remap-camera-id <PACKAGE> <Id0> <Id1>\n");
6176 return BAD_VALUE;
6177 }
Austin Borgered99f642023-06-01 16:51:35 -07006178 std::string packageName = toStdString(args[1]);
6179 std::string cameraIdToReplace = toStdString(args[2]);
6180 std::string cameraIdNew = toStdString(args[3]);
malikakash82ed4352023-07-21 22:44:34 +00006181 remapCameraIds({{packageName, {{cameraIdToReplace, cameraIdNew}}}});
6182 return OK;
6183}
6184
Svet Ganova453d0d2018-01-11 15:37:58 -08006185status_t CameraService::handleSetUidState(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
Svet Ganova453d0d2018-01-11 15:37:58 -08006188 bool active = false;
Austin Borgered99f642023-06-01 16:51:35 -07006189 if (args[2] == toString16("active")) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006190 active = true;
Austin Borgered99f642023-06-01 16:51:35 -07006191 } else if ((args[2] != toString16("idle"))) {
6192 ALOGE("Expected active or idle but got: '%s'", toStdString(args[2]).c_str());
Svet Ganova453d0d2018-01-11 15:37:58 -08006193 return BAD_VALUE;
6194 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006195
6196 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006197 if (args.size() >= 5 && args[3] == toString16("--user")) {
6198 userId = atoi(toStdString(args[4]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006199 }
6200
6201 uid_t uid;
6202 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
6203 return BAD_VALUE;
6204 }
6205
6206 mUidPolicy->addOverrideUid(uid, packageName, active);
Svet Ganova453d0d2018-01-11 15:37:58 -08006207 return NO_ERROR;
6208}
6209
6210status_t CameraService::handleResetUidState(const Vector<String16>& args, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006211 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006212
6213 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006214 if (args.size() >= 4 && args[2] == toString16("--user")) {
6215 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006216 }
6217
6218 uid_t uid;
6219 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006220 return BAD_VALUE;
6221 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006222
6223 mUidPolicy->removeOverrideUid(uid, packageName);
Svet Ganova453d0d2018-01-11 15:37:58 -08006224 return NO_ERROR;
6225}
6226
6227status_t CameraService::handleGetUidState(const Vector<String16>& args, int out, int err) {
Austin Borgered99f642023-06-01 16:51:35 -07006228 std::string packageName = toStdString(args[1]);
Nicholas Sauera3620332019-04-03 14:05:17 -07006229
6230 int userId = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006231 if (args.size() >= 4 && args[2] == toString16("--user")) {
6232 userId = atoi(toStdString(args[3]).c_str());
Nicholas Sauera3620332019-04-03 14:05:17 -07006233 }
6234
6235 uid_t uid;
6236 if (getUidForPackage(packageName, userId, uid, err) == BAD_VALUE) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006237 return BAD_VALUE;
6238 }
Nicholas Sauera3620332019-04-03 14:05:17 -07006239
6240 if (mUidPolicy->isUidActive(uid, packageName)) {
Svet Ganova453d0d2018-01-11 15:37:58 -08006241 return dprintf(out, "active\n");
6242 } else {
6243 return dprintf(out, "idle\n");
6244 }
6245}
6246
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006247status_t CameraService::handleSetRotateAndCrop(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006248 int rotateValue = atoi(toStdString(args[1]).c_str());
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006249 if (rotateValue < ANDROID_SCALER_ROTATE_AND_CROP_NONE ||
6250 rotateValue > ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return BAD_VALUE;
6251 Mutex::Autolock lock(mServiceLock);
6252
6253 mOverrideRotateAndCropMode = rotateValue;
6254
6255 if (rotateValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) return OK;
6256
6257 const auto clients = mActiveClientManager.getAll();
6258 for (auto& current : clients) {
6259 if (current != nullptr) {
6260 const auto basicClient = current->getValue();
6261 if (basicClient.get() != nullptr) {
6262 basicClient->setRotateAndCropOverride(rotateValue);
6263 }
6264 }
6265 }
6266
6267 return OK;
6268}
6269
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006270status_t CameraService::handleSetAutoframing(const Vector<String16>& args) {
6271 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006272 int autoframingValue = (int) strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006273 if ((*end != '\0') ||
6274 (autoframingValue != ANDROID_CONTROL_AUTOFRAMING_OFF &&
6275 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_ON &&
6276 autoframingValue != ANDROID_CONTROL_AUTOFRAMING_AUTO)) {
6277 return BAD_VALUE;
6278 }
6279
6280 Mutex::Autolock lock(mServiceLock);
6281 mOverrideAutoframingMode = autoframingValue;
6282
6283 if (autoframingValue == ANDROID_CONTROL_AUTOFRAMING_AUTO) return OK;
6284
6285 const auto clients = mActiveClientManager.getAll();
6286 for (auto& current : clients) {
6287 if (current != nullptr) {
6288 const auto basicClient = current->getValue();
6289 if (basicClient.get() != nullptr) {
6290 basicClient->setAutoframingOverride(autoframingValue);
6291 }
6292 }
6293 }
6294
6295 return OK;
6296}
6297
Ravneetaeb20dc2022-03-30 05:33:03 +00006298status_t CameraService::handleSetCameraServiceWatchdog(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006299 int enableWatchdog = atoi(toStdString(args[1]).c_str());
Ravneetaeb20dc2022-03-30 05:33:03 +00006300
6301 if (enableWatchdog < 0 || enableWatchdog > 1) return BAD_VALUE;
6302
6303 Mutex::Autolock lock(mServiceLock);
6304
6305 mCameraServiceWatchdogEnabled = enableWatchdog;
6306
6307 const auto clients = mActiveClientManager.getAll();
6308 for (auto& current : clients) {
6309 if (current != nullptr) {
6310 const auto basicClient = current->getValue();
6311 if (basicClient.get() != nullptr) {
6312 basicClient->setCameraServiceWatchdog(enableWatchdog);
6313 }
6314 }
6315 }
6316
6317 return OK;
6318}
6319
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006320status_t CameraService::handleGetRotateAndCrop(int out) {
6321 Mutex::Autolock lock(mServiceLock);
6322
6323 return dprintf(out, "rotateAndCrop override: %d\n", mOverrideRotateAndCropMode);
6324}
6325
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006326status_t CameraService::handleGetAutoframing(int out) {
6327 Mutex::Autolock lock(mServiceLock);
6328
6329 return dprintf(out, "autoframing override: %d\n", mOverrideAutoframingMode);
6330}
6331
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006332status_t CameraService::handleSetImageDumpMask(const Vector<String16>& args) {
6333 char *endPtr;
6334 errno = 0;
Austin Borgered99f642023-06-01 16:51:35 -07006335 std::string maskString = toStdString(args[1]);
6336 long maskValue = strtol(maskString.c_str(), &endPtr, 10);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006337
6338 if (errno != 0) return BAD_VALUE;
Austin Borgered99f642023-06-01 16:51:35 -07006339 if (endPtr != maskString.c_str() + maskString.size()) return BAD_VALUE;
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006340 if (maskValue < 0 || maskValue > 1) return BAD_VALUE;
6341
6342 Mutex::Autolock lock(mServiceLock);
6343
6344 mImageDumpMask = maskValue;
6345
6346 return OK;
6347}
6348
6349status_t CameraService::handleGetImageDumpMask(int out) {
6350 Mutex::Autolock lock(mServiceLock);
6351
6352 return dprintf(out, "Image dump mask: %d\n", mImageDumpMask);
6353}
6354
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006355status_t CameraService::handleSetCameraMute(const Vector<String16>& args) {
Austin Borgered99f642023-06-01 16:51:35 -07006356 int muteValue = strtol(toStdString(args[1]).c_str(), nullptr, 10);
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006357 if (errno != 0) return BAD_VALUE;
6358
6359 if (muteValue < 0 || muteValue > 1) return BAD_VALUE;
6360 Mutex::Autolock lock(mServiceLock);
6361
6362 mOverrideCameraMuteMode = (muteValue == 1);
6363
6364 const auto clients = mActiveClientManager.getAll();
6365 for (auto& current : clients) {
6366 if (current != nullptr) {
6367 const auto basicClient = current->getValue();
6368 if (basicClient.get() != nullptr) {
6369 if (basicClient->supportsCameraMute()) {
6370 basicClient->setCameraMute(mOverrideCameraMuteMode);
6371 }
6372 }
6373 }
6374 }
6375
6376 return OK;
6377}
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006378
Shuzhen Wang16610a62022-12-15 22:38:07 -08006379status_t CameraService::handleSetStreamUseCaseOverrides(const Vector<String16>& args) {
6380 std::vector<int64_t> useCasesOverride;
6381 for (size_t i = 1; i < args.size(); i++) {
6382 int64_t useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006383 std::string arg = toStdString(args[i]);
6384 if (arg == "DEFAULT") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006385 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT;
Austin Borgered99f642023-06-01 16:51:35 -07006386 } else if (arg == "PREVIEW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006387 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW;
Austin Borgered99f642023-06-01 16:51:35 -07006388 } else if (arg == "STILL_CAPTURE") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006389 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_STILL_CAPTURE;
Austin Borgered99f642023-06-01 16:51:35 -07006390 } else if (arg == "VIDEO_RECORD") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006391 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_RECORD;
Austin Borgered99f642023-06-01 16:51:35 -07006392 } else if (arg == "PREVIEW_VIDEO_STILL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006393 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_PREVIEW_VIDEO_STILL;
Austin Borgered99f642023-06-01 16:51:35 -07006394 } else if (arg == "VIDEO_CALL") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006395 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_VIDEO_CALL;
Austin Borgered99f642023-06-01 16:51:35 -07006396 } else if (arg == "CROPPED_RAW") {
Shuzhen Wang16610a62022-12-15 22:38:07 -08006397 useCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_CROPPED_RAW;
6398 } else {
Austin Borgered99f642023-06-01 16:51:35 -07006399 ALOGE("%s: Invalid stream use case %s", __FUNCTION__, arg.c_str());
Shuzhen Wang16610a62022-12-15 22:38:07 -08006400 return BAD_VALUE;
6401 }
6402 useCasesOverride.push_back(useCase);
6403 }
6404
6405 Mutex::Autolock lock(mServiceLock);
6406 mStreamUseCaseOverrides = std::move(useCasesOverride);
6407
6408 return OK;
6409}
6410
6411void CameraService::handleClearStreamUseCaseOverrides() {
6412 Mutex::Autolock lock(mServiceLock);
6413 mStreamUseCaseOverrides.clear();
6414}
6415
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006416status_t CameraService::handleSetZoomOverride(const Vector<String16>& args) {
6417 char* end;
Austin Borgered99f642023-06-01 16:51:35 -07006418 int zoomOverrideValue = strtol(toStdString(args[1]).c_str(), &end, /*base=*/10);
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006419 if ((*end != '\0') ||
6420 (zoomOverrideValue != -1 &&
6421 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF &&
6422 zoomOverrideValue != ANDROID_CONTROL_SETTINGS_OVERRIDE_ZOOM)) {
6423 return BAD_VALUE;
6424 }
6425
6426 Mutex::Autolock lock(mServiceLock);
6427 mZoomOverrideValue = zoomOverrideValue;
6428
6429 const auto clients = mActiveClientManager.getAll();
6430 for (auto& current : clients) {
6431 if (current != nullptr) {
6432 const auto basicClient = current->getValue();
6433 if (basicClient.get() != nullptr) {
6434 if (basicClient->supportsZoomOverride()) {
6435 basicClient->setZoomOverride(mZoomOverrideValue);
6436 }
6437 }
6438 }
6439 }
6440
6441 return OK;
6442}
6443
Avichal Rakesh84147132021-11-11 17:47:11 -08006444status_t CameraService::handleWatchCommand(const Vector<String16>& args, int inFd, int outFd) {
Austin Borgered99f642023-06-01 16:51:35 -07006445 if (args.size() >= 3 && args[1] == toString16("start")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006446 return startWatchingTags(args, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006447 } else if (args.size() == 2 && args[1] == toString16("stop")) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006448 return stopWatchingTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006449 } else if (args.size() == 2 && args[1] == toString16("dump")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006450 return printWatchedTags(outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006451 } else if (args.size() >= 2 && args[1] == toString16("live")) {
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006452 return printWatchedTagsUntilInterrupt(args, inFd, outFd);
Austin Borgered99f642023-06-01 16:51:35 -07006453 } else if (args.size() == 2 && args[1] == toString16("clear")) {
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006454 return clearCachedMonitoredTagDumps(outFd);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006455 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006456 dprintf(outFd, "Camera service watch commands:\n"
6457 " start -m <comma_separated_tag_list> [-c <comma_separated_client_list>]\n"
6458 " starts watching the provided tags for clients with provided package\n"
6459 " recognizes tag shorthands like '3a'\n"
6460 " watches all clients if no client is passed, or if 'all' is listed\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006461 " dump dumps the monitoring information and exits\n"
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006462 " stop stops watching all tags\n"
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006463 " live [-n <refresh_interval_ms>]\n"
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006464 " prints the monitored information in real time\n"
Avichal Rakesh84147132021-11-11 17:47:11 -08006465 " Hit return to exit\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006466 " clear clears all buffers storing information for watch command");
Biswarup Pal37a75182024-01-16 15:53:35 +00006467 return BAD_VALUE;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006468}
6469
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006470status_t CameraService::startWatchingTags(const Vector<String16> &args, int outFd) {
6471 Mutex::Autolock lock(mLogLock);
6472 size_t tagsIdx; // index of '-m'
6473 String16 tags("");
Austin Borgered99f642023-06-01 16:51:35 -07006474 for (tagsIdx = 2; tagsIdx < args.size() && args[tagsIdx] != toString16("-m"); tagsIdx++);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006475 if (tagsIdx < args.size() - 1) {
6476 tags = args[tagsIdx + 1];
6477 } else {
6478 dprintf(outFd, "No tags provided.\n");
6479 return BAD_VALUE;
6480 }
6481
6482 size_t clientsIdx; // index of '-c'
Austin Borgered99f642023-06-01 16:51:35 -07006483 // watch all clients if no clients are provided
6484 String16 clients = toString16(kWatchAllClientsFlag);
6485 for (clientsIdx = 2; clientsIdx < args.size() && args[clientsIdx] != toString16("-c");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006486 clientsIdx++);
6487 if (clientsIdx < args.size() - 1) {
6488 clients = args[clientsIdx + 1];
6489 }
Austin Borgered99f642023-06-01 16:51:35 -07006490 parseClientsToWatchLocked(toStdString(clients));
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006491
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006492 // track tags to initialize future clients with the monitoring information
Austin Borgered99f642023-06-01 16:51:35 -07006493 mMonitorTags = toStdString(tags);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006494
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006495 bool serviceLock = tryLock(mServiceLock);
6496 int numWatchedClients = 0;
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006497 auto cameraClients = mActiveClientManager.getAll();
6498 for (const auto &clientDescriptor: cameraClients) {
6499 if (clientDescriptor == nullptr) { continue; }
6500 sp<BasicClient> client = clientDescriptor->getValue();
6501 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006502
6503 if (isClientWatchedLocked(client.get())) {
6504 client->startWatchingTags(mMonitorTags, outFd);
6505 numWatchedClients++;
6506 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006507 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006508 dprintf(outFd, "Started watching %d active clients\n", numWatchedClients);
6509
6510 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006511 return OK;
6512}
6513
6514status_t CameraService::stopWatchingTags(int outFd) {
6515 // clear mMonitorTags to prevent new clients from monitoring tags at initialization
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006516 Mutex::Autolock lock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006517 mMonitorTags = "";
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006518
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006519 mWatchedClientPackages.clear();
6520 mWatchedClientsDumpCache.clear();
6521
6522 bool serviceLock = tryLock(mServiceLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006523 auto cameraClients = mActiveClientManager.getAll();
6524 for (const auto &clientDescriptor : cameraClients) {
6525 if (clientDescriptor == nullptr) { continue; }
6526 sp<BasicClient> client = clientDescriptor->getValue();
6527 if (client.get() == nullptr) { continue; }
6528 client->stopWatchingTags(outFd);
6529 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006530 dprintf(outFd, "Stopped watching all clients.\n");
6531 if (serviceLock) { mServiceLock.unlock(); }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006532 return OK;
6533}
6534
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006535status_t CameraService::clearCachedMonitoredTagDumps(int outFd) {
6536 Mutex::Autolock lock(mLogLock);
6537 size_t clearedSize = mWatchedClientsDumpCache.size();
6538 mWatchedClientsDumpCache.clear();
6539 dprintf(outFd, "Cleared tag information of %zu cached clients.\n", clearedSize);
6540 return OK;
6541}
6542
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006543status_t CameraService::printWatchedTags(int outFd) {
6544 Mutex::Autolock logLock(mLogLock);
Austin Borgered99f642023-06-01 16:51:35 -07006545 std::set<std::string> connectedMonitoredClients;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006546
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006547 bool printedSomething = false; // tracks if any monitoring information was printed
6548 // (from either cached or active clients)
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006549
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006550 bool serviceLock = tryLock(mServiceLock);
6551 // get all watched clients that are currently connected
6552 for (const auto &clientDescriptor: mActiveClientManager.getAll()) {
6553 if (clientDescriptor == nullptr) { continue; }
6554
6555 sp<BasicClient> client = clientDescriptor->getValue();
6556 if (client.get() == nullptr) { continue; }
6557 if (!isClientWatchedLocked(client.get())) { continue; }
6558
6559 std::vector<std::string> dumpVector;
6560 client->dumpWatchedEventsToVector(dumpVector);
6561
6562 size_t printIdx = dumpVector.size();
6563 if (printIdx == 0) {
6564 continue;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006565 }
6566
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006567 // Print tag dumps for active client
Austin Borgered99f642023-06-01 16:51:35 -07006568 const std::string &cameraId = clientDescriptor->getKey();
6569 dprintf(outFd, "Client: %s (active)\n", client->getPackageName().c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006570 while(printIdx > 0) {
6571 printIdx--;
Austin Borgered99f642023-06-01 16:51:35 -07006572 dprintf(outFd, "%s:%s %s", cameraId.c_str(), client->getPackageName().c_str(),
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006573 dumpVector[printIdx].c_str());
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006574 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006575 dprintf(outFd, "\n");
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006576 printedSomething = true;
6577
6578 connectedMonitoredClients.emplace(client->getPackageName());
6579 }
6580 if (serviceLock) { mServiceLock.unlock(); }
6581
6582 // Print entries in mWatchedClientsDumpCache for clients that are not connected
6583 for (const auto &kv: mWatchedClientsDumpCache) {
Austin Borgered99f642023-06-01 16:51:35 -07006584 const std::string &package = kv.first;
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006585 if (connectedMonitoredClients.find(package) != connectedMonitoredClients.end()) {
6586 continue;
6587 }
6588
Austin Borgered99f642023-06-01 16:51:35 -07006589 dprintf(outFd, "Client: %s (cached)\n", package.c_str());
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006590 dprintf(outFd, "%s\n", kv.second.c_str());
6591 printedSomething = true;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006592 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006593
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006594 if (!printedSomething) {
6595 dprintf(outFd, "No monitoring information to print.\n");
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006596 }
6597
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006598 return OK;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006599}
6600
Avichal Rakesh84147132021-11-11 17:47:11 -08006601// Print all events in vector `events' that came after lastPrintedEvent
6602void printNewWatchedEvents(int outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006603 const std::string &cameraId,
6604 const std::string &packageName,
Avichal Rakesh84147132021-11-11 17:47:11 -08006605 const std::vector<std::string> &events,
6606 const std::string &lastPrintedEvent) {
6607 if (events.empty()) { return; }
6608
6609 // index of lastPrintedEvent in events.
6610 // lastPrintedIdx = events.size() if lastPrintedEvent is not in events
6611 size_t lastPrintedIdx;
6612 for (lastPrintedIdx = 0;
6613 lastPrintedIdx < events.size() && lastPrintedEvent != events[lastPrintedIdx];
6614 lastPrintedIdx++);
6615
6616 if (lastPrintedIdx == 0) { return; } // early exit if no new event in `events`
6617
Avichal Rakesh84147132021-11-11 17:47:11 -08006618 // print events in chronological order (latest event last)
6619 size_t idxToPrint = lastPrintedIdx;
6620 do {
6621 idxToPrint--;
Austin Borgered99f642023-06-01 16:51:35 -07006622 dprintf(outFd, "%s:%s %s", cameraId.c_str(), packageName.c_str(),
6623 events[idxToPrint].c_str());
Avichal Rakesh84147132021-11-11 17:47:11 -08006624 } while (idxToPrint != 0);
Avichal Rakesh84147132021-11-11 17:47:11 -08006625}
6626
6627// Returns true if adb shell cmd watch should be interrupted based on data in inFd. The watch
6628// command should be interrupted if the user presses the return key, or if user loses any way to
6629// signal interrupt.
6630// If timeoutMs == 0, this function will always return false
6631bool shouldInterruptWatchCommand(int inFd, int outFd, long timeoutMs) {
6632 struct timeval startTime;
6633 int startTimeError = gettimeofday(&startTime, nullptr);
6634 if (startTimeError) {
6635 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6636 return true;
6637 }
6638
6639 const nfds_t numFds = 1;
6640 struct pollfd pollFd = { .fd = inFd, .events = POLLIN, .revents = 0 };
6641
6642 struct timeval currTime;
6643 char buffer[2];
6644 while(true) {
6645 int currTimeError = gettimeofday(&currTime, nullptr);
6646 if (currTimeError) {
6647 dprintf(outFd, "Failed waiting for interrupt, aborting.\n");
6648 return true;
6649 }
6650
6651 long elapsedTimeMs = ((currTime.tv_sec - startTime.tv_sec) * 1000L)
6652 + ((currTime.tv_usec - startTime.tv_usec) / 1000L);
6653 int remainingTimeMs = (int) (timeoutMs - elapsedTimeMs);
6654
6655 if (remainingTimeMs <= 0) {
6656 // No user interrupt within timeoutMs, don't interrupt watch command
6657 return false;
6658 }
6659
6660 int numFdsUpdated = poll(&pollFd, numFds, remainingTimeMs);
6661 if (numFdsUpdated < 0) {
6662 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6663 return true;
6664 }
6665
6666 if (numFdsUpdated == 0) {
6667 // No user input within timeoutMs, don't interrupt watch command
6668 return false;
6669 }
6670
6671 if (!(pollFd.revents & POLLIN)) {
6672 dprintf(outFd, "Failed while waiting for user input. Exiting.\n");
6673 return true;
6674 }
6675
6676 ssize_t sizeRead = read(inFd, buffer, sizeof(buffer) - 1);
6677 if (sizeRead < 0) {
6678 dprintf(outFd, "Error reading user input. Exiting.\n");
6679 return true;
6680 }
6681
6682 if (sizeRead == 0) {
6683 // Reached end of input fd (can happen if input is piped)
6684 // User has no way to signal an interrupt, so interrupt here
6685 return true;
6686 }
6687
6688 if (buffer[0] == '\n') {
6689 // User pressed return, interrupt watch command.
6690 return true;
6691 }
6692 }
6693}
6694
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006695status_t CameraService::printWatchedTagsUntilInterrupt(const Vector<String16> &args,
6696 int inFd, int outFd) {
6697 // Figure out refresh interval, if present in args
6698 long refreshTimeoutMs = 1000L; // refresh every 1s by default
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006699 if (args.size() > 2) {
6700 size_t intervalIdx; // index of '-n'
Austin Borgered99f642023-06-01 16:51:35 -07006701 for (intervalIdx = 2; intervalIdx < args.size() && toString16("-n") != args[intervalIdx];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006702 intervalIdx++);
6703
6704 size_t intervalValIdx = intervalIdx + 1;
6705 if (intervalValIdx < args.size()) {
Austin Borgered99f642023-06-01 16:51:35 -07006706 refreshTimeoutMs = strtol(toStdString(args[intervalValIdx]).c_str(), nullptr, 10);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006707 if (errno) { return BAD_VALUE; }
6708 }
6709 }
6710
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006711 // Set min timeout of 10ms. This prevents edge cases in polling when timeout of 0 is passed.
6712 refreshTimeoutMs = refreshTimeoutMs < 10 ? 10 : refreshTimeoutMs;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006713
Avichal Rakesh84147132021-11-11 17:47:11 -08006714 dprintf(outFd, "Press return to exit...\n\n");
Austin Borgered99f642023-06-01 16:51:35 -07006715 std::map<std::string, std::string> packageNameToLastEvent;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006716
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006717 while (true) {
Avichal Rakesha14d9832021-11-11 01:41:55 -08006718 bool serviceLock = tryLock(mServiceLock);
6719 auto cameraClients = mActiveClientManager.getAll();
6720 if (serviceLock) { mServiceLock.unlock(); }
6721
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006722 for (const auto& clientDescriptor : cameraClients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006723 Mutex::Autolock lock(mLogLock);
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006724 if (clientDescriptor == nullptr) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006725
6726 sp<BasicClient> client = clientDescriptor->getValue();
6727 if (client.get() == nullptr) { continue; }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006728 if (!isClientWatchedLocked(client.get())) { continue; }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006729
Austin Borgered99f642023-06-01 16:51:35 -07006730 const std::string &packageName = client->getPackageName();
Avichal Rakesha14d9832021-11-11 01:41:55 -08006731 // This also initializes the map entries with an empty string
6732 const std::string& lastPrintedEvent = packageNameToLastEvent[packageName];
6733
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006734 std::vector<std::string> latestEvents;
6735 client->dumpWatchedEventsToVector(latestEvents);
6736
6737 if (!latestEvents.empty()) {
6738 printNewWatchedEvents(outFd,
Austin Borgered99f642023-06-01 16:51:35 -07006739 clientDescriptor->getKey(),
Avichal Rakesha14d9832021-11-11 01:41:55 -08006740 packageName,
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006741 latestEvents,
6742 lastPrintedEvent);
Avichal Rakesha14d9832021-11-11 01:41:55 -08006743 packageNameToLastEvent[packageName] = latestEvents[0];
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006744 }
6745 }
Avichal Rakesh9e5a1e42021-11-15 12:11:21 -08006746 if (shouldInterruptWatchCommand(inFd, outFd, refreshTimeoutMs)) {
Avichal Rakesh84147132021-11-11 17:47:11 -08006747 break;
6748 }
Avichal Rakesh7e53cad2021-10-05 13:46:30 -07006749 }
6750 return OK;
6751}
6752
Austin Borgered99f642023-06-01 16:51:35 -07006753void CameraService::parseClientsToWatchLocked(const std::string &clients) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006754 mWatchedClientPackages.clear();
6755
Austin Borgered99f642023-06-01 16:51:35 -07006756 std::istringstream iss(clients);
6757 std::string nextClient;
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006758
Austin Borgered99f642023-06-01 16:51:35 -07006759 while (std::getline(iss, nextClient, ',')) {
6760 if (nextClient == kWatchAllClientsFlag) {
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006761 // Don't need to track any other package if 'all' is present
6762 mWatchedClientPackages.clear();
6763 mWatchedClientPackages.emplace(kWatchAllClientsFlag);
6764 break;
6765 }
6766
6767 // track package names
6768 mWatchedClientPackages.emplace(nextClient);
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006769 }
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006770}
6771
Svet Ganova453d0d2018-01-11 15:37:58 -08006772status_t CameraService::printHelp(int out) {
6773 return dprintf(out, "Camera service commands:\n"
Nicholas Sauera3620332019-04-03 14:05:17 -07006774 " get-uid-state <PACKAGE> [--user USER_ID] gets the uid state\n"
6775 " set-uid-state <PACKAGE> <active|idle> [--user USER_ID] overrides the uid state\n"
6776 " reset-uid-state <PACKAGE> [--user USER_ID] clears the uid state override\n"
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006777 " set-rotate-and-crop <ROTATION> overrides the rotate-and-crop value for AUTO backcompat\n"
6778 " Valid values 0=0 deg, 1=90 deg, 2=180 deg, 3=270 deg, 4=No override\n"
6779 " get-rotate-and-crop returns the current override rotate-and-crop value\n"
Bharatt Kukreja7146ced2022-10-25 15:45:29 +00006780 " set-autoframing <VALUE> overrides the autoframing value for AUTO\n"
6781 " Valid values 0=false, 1=true, 2=auto\n"
6782 " get-autoframing returns the current override autoframing value\n"
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08006783 " set-image-dump-mask <MASK> specifies the formats to be saved to disk\n"
6784 " Valid values 0=OFF, 1=ON for JPEG\n"
6785 " get-image-dump-mask returns the current image-dump-mask value\n"
Eino-Ville Talvala305cec62020-11-12 14:18:17 -08006786 " set-camera-mute <0/1> enable or disable camera muting\n"
Shuzhen Wang16610a62022-12-15 22:38:07 -08006787 " set-stream-use-case-override <usecase1> <usecase2> ... override stream use cases\n"
6788 " Use cases applied in descending resolutions. So usecase1 is assigned to the\n"
6789 " largest resolution, usecase2 is assigned to the 2nd largest resolution, and so\n"
6790 " on. In case the number of usecases is smaller than the number of streams, the\n"
6791 " last use case is assigned to all the remaining streams. In case of multiple\n"
6792 " streams with the same resolution, the tie-breaker is (JPEG, RAW, YUV, and PRIV)\n"
6793 " Valid values are (case sensitive): DEFAULT, PREVIEW, STILL_CAPTURE, VIDEO_RECORD,\n"
6794 " PREVIEW_VIDEO_STILL, VIDEO_CALL, CROPPED_RAW\n"
6795 " clear-stream-use-case-override clear the stream use case override\n"
Shuzhen Wangaf22e912023-04-11 16:03:17 -07006796 " set-zoom-override <-1/0/1> enable or disable zoom override\n"
6797 " Valid values -1: do not override, 0: override to OFF, 1: override to ZOOM\n"
Ravneet Dhanjalad99ff52023-07-24 05:21:07 +00006798 " set-watchdog <VALUE> enables or disables the camera service watchdog\n"
6799 " Valid values 0=disable, 1=enable\n"
Avichal Rakesh3a85d2d2021-11-10 16:21:33 -08006800 " watch <start|stop|dump|print|clear> manages tag monitoring in connected clients\n"
malikakash73125c62023-07-21 22:44:34 +00006801 " remap-camera-id <PACKAGE> <Id0> <Id1> remaps camera ids. Must use adb root\n"
Svet Ganova453d0d2018-01-11 15:37:58 -08006802 " help print this message\n");
6803}
6804
Avichal Rakesh7fbc3982021-10-20 04:35:03 -07006805bool CameraService::isClientWatched(const BasicClient *client) {
6806 Mutex::Autolock lock(mLogLock);
6807 return isClientWatchedLocked(client);
6808}
6809
6810bool CameraService::isClientWatchedLocked(const BasicClient *client) {
6811 return mWatchedClientPackages.find(kWatchAllClientsFlag) != mWatchedClientPackages.end() ||
6812 mWatchedClientPackages.find(client->getPackageName()) != mWatchedClientPackages.end();
6813}
6814
Yin-Chia Yehdba03232019-08-19 15:54:28 -07006815int32_t CameraService::updateAudioRestriction() {
6816 Mutex::Autolock lock(mServiceLock);
6817 return updateAudioRestrictionLocked();
6818}
6819
6820int32_t CameraService::updateAudioRestrictionLocked() {
6821 int32_t mode = 0;
6822 // iterate through all active client
6823 for (const auto& i : mActiveClientManager.getAll()) {
6824 const auto clientSp = i->getValue();
6825 mode |= clientSp->getAudioRestriction();
6826 }
6827
6828 bool modeChanged = (mAudioRestriction != mode);
6829 mAudioRestriction = mode;
6830 if (modeChanged) {
6831 mAppOps.setCameraAudioRestriction(mode);
6832 }
6833 return mode;
6834}
6835
Austin Borgered99f642023-06-01 16:51:35 -07006836status_t CameraService::checkIfInjectionCameraIsPresent(const std::string& externalCamId,
Cliff Wu646bd612021-11-23 23:21:29 +08006837 sp<BasicClient> clientSp) {
6838 std::unique_ptr<AutoConditionLock> lock =
6839 AutoConditionLock::waitAndAcquire(mServiceLockWrapper);
6840 status_t res = NO_ERROR;
6841 if ((res = checkIfDeviceIsUsable(externalCamId)) != NO_ERROR) {
Austin Borgered99f642023-06-01 16:51:35 -07006842 ALOGW("Device %s is not usable!", externalCamId.c_str());
Cliff Wu646bd612021-11-23 23:21:29 +08006843 mInjectionStatusListener->notifyInjectionError(
6844 externalCamId, UNKNOWN_TRANSACTION);
6845 clientSp->notifyError(
6846 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DISCONNECTED,
6847 CaptureResultExtras());
6848
6849 // Do not hold mServiceLock while disconnecting clients, but retain the condition blocking
6850 // other clients from connecting in mServiceLockWrapper if held
6851 mServiceLock.unlock();
6852
6853 // Clear caller identity temporarily so client disconnect PID checks work correctly
Austin Borger22c5c852024-03-08 13:31:36 -08006854 int64_t token = clearCallingIdentity();
Cliff Wu646bd612021-11-23 23:21:29 +08006855 clientSp->disconnect();
Austin Borger22c5c852024-03-08 13:31:36 -08006856 restoreCallingIdentity(token);
Cliff Wu646bd612021-11-23 23:21:29 +08006857
6858 // Reacquire mServiceLock
6859 mServiceLock.lock();
6860 }
6861
6862 return res;
6863}
6864
Cliff Wud3a05312021-04-26 23:07:31 +08006865void CameraService::clearInjectionParameters() {
6866 {
6867 Mutex::Autolock lock(mInjectionParametersLock);
Cliff Wu646bd612021-11-23 23:21:29 +08006868 mInjectionInitPending = false;
Cliff Wud3a05312021-04-26 23:07:31 +08006869 mInjectionInternalCamId = "";
6870 }
6871 mInjectionExternalCamId = "";
Cliff Wud8cae102021-03-11 01:37:42 +08006872 mInjectionStatusListener->removeListener();
Cliff Wud8cae102021-03-11 01:37:42 +08006873}
6874
Biswarup Pal37a75182024-01-16 15:53:35 +00006875} // namespace android